1 package org.apache.maven.surefire.booter;
2
3 /*
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
19 * under the License.
20 */
21
22 /**
23 * Immutable object which encapsulates PID and elapsed time (Unix) or start time (Windows).
24 * <br>
25 * Methods
26 * ({@link #getPID()}, {@link #getTime()}, {@link #isTimeBefore(ProcessInfo)}, {@link #isTimeEqualTo(ProcessInfo)})
27 * throw {@link IllegalStateException}
28 * if {@link #canUse()} returns {@code false} or {@link #isError()} returns {@code true}.
29 *
30 * @author <a href="mailto:tibordigana@apache.org">Tibor Digana (tibor17)</a>
31 * @since 2.20.1
32 */
33 final class ProcessInfo
34 {
35 static final ProcessInfo INVALID_PROCESS_INFO = new ProcessInfo( null, null );
36 static final ProcessInfo ERR_PROCESS_INFO = new ProcessInfo( null, null );
37
38 /**
39 * On Unix we do not get PID due to the command is interested only to etime of PPID:
40 * <br>
41 * <pre>/bin/ps -o etime= -p 123</pre>
42 */
43 static ProcessInfo unixProcessInfo( long pid, long etime )
44 {
45 return new ProcessInfo( pid, etime );
46 }
47
48 static ProcessInfo windowsProcessInfo( long pid, long startTimestamp )
49 {
50 return new ProcessInfo( pid, startTimestamp );
51 }
52
53 private final Long pid;
54 private final Comparable time;
55
56 private ProcessInfo( Long pid, Comparable time )
57 {
58 this.pid = pid;
59 this.time = time;
60 }
61
62 boolean canUse()
63 {
64 return !isInvalid() && !isError();
65 }
66
67 boolean isInvalid()
68 {
69 return this == INVALID_PROCESS_INFO;
70 }
71
72 boolean isError()
73 {
74 return this == ERR_PROCESS_INFO;
75 }
76
77 long getPID()
78 {
79 checkValid();
80 return pid;
81 }
82
83 Comparable getTime()
84 {
85 checkValid();
86 return time;
87 }
88
89 @SuppressWarnings( "unchecked" )
90 boolean isTimeEqualTo( ProcessInfo that )
91 {
92 checkValid();
93 that.checkValid();
94 return this.time.compareTo( that.time ) == 0;
95 }
96
97 @SuppressWarnings( "unchecked" )
98 boolean isTimeBefore( ProcessInfo that )
99 {
100 checkValid();
101 that.checkValid();
102 return this.time.compareTo( that.time ) < 0;
103 }
104
105 private void checkValid()
106 {
107 if ( !canUse() )
108 {
109 throw new IllegalStateException( "invalid process info" );
110 }
111 }
112 }