View Javadoc
1   package org.apache.maven.surefire.api.util;
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 java.io.File;
23  import java.util.Objects;
24  import java.util.stream.Stream;
25  
26  /**
27   * Centralized file management of temporary files in surefire.<br>
28   * Files are deleted on VM exit.
29   *
30   * @author Markus Spann
31   */
32  public final class SureFireFileManager
33  {
34  
35      private static TempFileManager instance = create();
36  
37      private static TempFileManager create()
38      {
39          String subDirName = "surefire";
40  
41          // create directory name suffix from legal chars in the current user name
42          // or a millisecond timestamp as fallback
43          String userSuffix = Stream.of( "user.name", "USER", "USERNAME" )
44                          .map( System::getProperty )
45                          .filter( Objects::nonNull )
46                          .findFirst()
47                          .map( u -> u.replaceAll( "[^A-Za-z0-9\\-_]", "" ) )
48                          .map( u -> u.isEmpty() ? null : u )
49                          .orElse( Long.toString( System.currentTimeMillis() ) );
50  
51          if ( userSuffix != null )
52          {
53              subDirName += "-" + userSuffix;
54          }
55  
56          TempFileManager tfm = TempFileManager.instance( subDirName );
57          tfm.setDeleteOnExit( true );
58          return tfm;
59      }
60  
61      public static File createTempFile( String prefix, String suffix )
62      {
63          return instance.createTempFile( prefix, suffix );
64      }
65  
66  }