• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.cts;
18 
19 import java.io.File;
20 import java.io.FileNotFoundException;
21 import java.io.FileOutputStream;
22 import java.io.IOException;
23 import java.nio.channels.FileLock;
24 
25 /**
26  * Host lock to make sure just one CTS host is running.
27  */
28 public class HostLock {
29     private static FileOutputStream mFileOs;
30     private static FileLock mLock;
31     private static File mFile;
32 
33     /**
34      * Lock the host.
35      *
36      * @return If succeed in locking the host, return true; else , return false.
37      */
lock()38     public static boolean lock() {
39         try {
40             String tmpdir = System.getProperty("java.io.tmpdir");
41             mFile = new File(tmpdir + File.separator + "ctsLockFile.txt");
42             mFileOs = new FileOutputStream(mFile);
43             mLock = mFileOs.getChannel().tryLock();
44             if (mLock != null) {
45                 return true;
46             } else {
47                 return false;
48             }
49         } catch (FileNotFoundException e1) {
50             return false;
51         }catch (IOException e1) {
52             return false;
53         }
54     }
55 
56     /**
57      * Release the host lock.
58      */
release()59     public static void release() {
60         try {
61             if (mLock != null) {
62                 mLock.release();
63             }
64 
65             if (mFileOs != null) {
66                 mFileOs.close();
67             }
68             // On systems with permissions, it's possible for this lock file
69             // (depending on the default permissions set) to lock other users
70             // out from using CTS on the same host.  So remove the file and
71             // play nice with others.
72             mFile.delete();
73         } catch (IOException e) {
74         }
75     }
76 }
77