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 import javax.annotation.Nonnull;
23
24 /**
25 * Immutable object which encapsulates PID and elapsed time (Unix) or start time (Windows).
26 * <br>
27 * Methods
28 * ({@link #getPID()}, {@link #getTime()}, {@link #isTimeBefore(ProcessInfo)}, {@link #isTimeEqualTo(ProcessInfo)})
29 * throw {@link IllegalStateException}
30 * if {@link #canUse()} returns {@code false} or {@link #isError()} returns {@code true}.
31 *
32 * @author <a href="mailto:tibordigana@apache.org">Tibor Digana (tibor17)</a>
33 * @since 2.20.1
34 */
35 final class ProcessInfo
36 {
37 static final ProcessInfo INVALID_PROCESS_INFO = new ProcessInfo( null, 0 );
38 static final ProcessInfo ERR_PROCESS_INFO = new ProcessInfo( null, 0 );
39
40 /**
41 * On Unix we do not get PID due to the command is interested only to etime of PPID:
42 * <br>
43 * <pre>/bin/ps -o etime= -p 123</pre>
44 */
45 static @Nonnull ProcessInfo unixProcessInfo( String pid, long etime )
46 {
47 return new ProcessInfo( pid, etime );
48 }
49
50 static @Nonnull ProcessInfo windowsProcessInfo( String pid, long startTimestamp )
51 {
52 return new ProcessInfo( pid, startTimestamp );
53 }
54
55 private final String pid;
56 private final long time;
57
58 private ProcessInfo( String pid, long time )
59 {
60 this.pid = pid;
61 this.time = time;
62 }
63
64 boolean canUse()
65 {
66 return !isError();
67 }
68
69 boolean isInvalid()
70 {
71 return this == INVALID_PROCESS_INFO;
72 }
73
74 boolean isError()
75 {
76 return this == ERR_PROCESS_INFO;
77 }
78
79 String getPID()
80 {
81 checkValid();
82 return pid;
83 }
84
85 long getTime()
86 {
87 checkValid();
88 return time;
89 }
90
91 boolean isTimeEqualTo( ProcessInfo that )
92 {
93 checkValid();
94 that.checkValid();
95 return time == that.time;
96 }
97
98 boolean isTimeBefore( ProcessInfo that )
99 {
100 checkValid();
101 that.checkValid();
102 return time < that.time;
103 }
104
105 private void checkValid()
106 {
107 if ( !canUse() )
108 {
109 throw new IllegalStateException( "invalid process info" );
110 }
111 }
112 }