use of java.nio.channels.FileLock in project scheduling by ow2-proactive.
the class RMNodeUpdater method makeNodeUpToDate.
private boolean makeNodeUpToDate() {
if (!isLocalJarUpToDate(nodeJarUrl, nodeJarSaveAs)) {
logger.info("Downloading node.jar from " + nodeJarUrl + " to " + nodeJarSaveAs);
try {
File destination = new File(nodeJarSaveAs);
File lockFile = null;
FileLock lock = null;
if (destination.exists()) {
lockFile = new File(StandardSystemProperty.JAVA_IO_TMPDIR.value(), "lock");
if (!lockFile.exists()) {
lockFile.createNewFile();
}
logger.info("Getting the lock on " + lockFile.getAbsoluteFile());
FileChannel channel = new RandomAccessFile(lockFile, "rw").getChannel();
lock = channel.lock();
if (isLocalJarUpToDate(nodeJarUrl, nodeJarSaveAs)) {
logger.warn("Another process downloaded node.jar - don't do it anymore");
logger.info("Releasing the lock on " + lockFile.getAbsoluteFile());
lock.release();
channel.close();
return false;
}
}
fetchUrl(nodeJarUrl, destination);
// Align the local file modification time with the remote url.
destination.setLastModified(getRemoteLastModifiedMillis(nodeJarUrl));
logger.info("Download finished");
cleanExpandDirectory(nodeJarSaveAs);
if (lock != null && lockFile != null) {
logger.info("Releasing the lock on " + lockFile.getAbsoluteFile());
lock.release();
}
return true;
} catch (Exception e) {
logError("Cannot download node.jar from " + nodeJarUrl, e);
return false;
}
} else {
return true;
}
}
use of java.nio.channels.FileLock in project pentaho-platform by pentaho.
the class ServerSocketBasedKarafInstanceResolver method assignAvailableCacheFolderForType.
private void assignAvailableCacheFolderForType(KarafInstance instance) {
// something like karaf/caches
String cacheParentFolder = instance.getCacheParentFolder();
// We separate the caches by client type to avoid reuse of an inappropriate data folder
File clientTypeCacheFolder = new File(cacheParentFolder + "/" + instance.getClientType());
clientTypeCacheFolder.mkdirs();
File[] dataDirectories = clientTypeCacheFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith(DATA);
}
});
int maxInstanceNoFound = 0;
Pattern pattern = Pattern.compile(DATA + "\\-([0-9]+)");
// one greater
for (File dataDirectory : dataDirectories) {
boolean locked = true;
Matcher matcher = pattern.matcher(dataDirectory.getName());
if (!matcher.matches()) {
// unexpected directory, not a data folder, skipping
continue;
}
// extract the data folder number
int instanceNo = Integer.parseInt(matcher.group(1));
maxInstanceNoFound = Math.max(maxInstanceNoFound, instanceNo);
File lockFile = new File(dataDirectory, ".lock");
FileLock lock = null;
if (!lockFile.exists()) {
// Lock file was not present, we can use it
locked = false;
} else {
// Lock file was there, see if another process actually holds a lock on it
try {
FileOutputStream fileOutputStream = new FileOutputStream(lockFile);
try {
lock = fileOutputStream.getChannel().tryLock();
if (lock != null) {
// not locked by another program
instance.setCacheLock(lock);
locked = false;
}
} catch (Exception e) {
// Lock active on another program
}
} catch (FileNotFoundException e) {
logger.error("Error locking file in data cache directory", e);
}
}
if (!locked) {
instance.setCachePath(dataDirectory.getPath());
// we're good to use this one, break out of existing directory loop
break;
}
}
if (instance.getCachePath() == null) {
// Create a new cache folder
File newCacheFolder = null;
while (newCacheFolder == null) {
maxInstanceNoFound++;
File candidate = new File(clientTypeCacheFolder, DATA + "-" + maxInstanceNoFound);
if (candidate.exists()) {
// Another process slipped in and created a folder, lets skip over them
continue;
}
newCacheFolder = candidate;
}
FileOutputStream fileOutputStream = null;
try {
newCacheFolder.mkdir();
// create lock file and lock it for this process
File lockFile = new File(newCacheFolder, ".lock");
fileOutputStream = new FileOutputStream(lockFile);
FileLock lock = fileOutputStream.getChannel().lock();
instance.setCachePath(newCacheFolder.getPath());
instance.setCacheLock(lock);
} catch (IOException e) {
logger.error("Error creating data cache folder", e);
}
}
}
use of java.nio.channels.FileLock in project wso2-synapse by wso2.
the class MultiXMLConfigurationSerializer method isWritable.
private boolean isWritable(File file) {
if (file.isDirectory()) {
// Further generalize this check
if (".svn".equals(file.getName())) {
return true;
}
File[] children = file.listFiles();
for (File child : children) {
if (!isWritable(child)) {
log.warn("File: " + child.getName() + " is not writable");
return false;
}
}
if (!file.canWrite()) {
log.warn("Directory: " + file.getName() + " is not writable");
return false;
}
return true;
} else {
if (!file.canWrite()) {
log.warn("File: " + file.getName() + " is not writable");
return false;
}
FileOutputStream fos = null;
FileLock lock = null;
boolean writable;
try {
fos = new FileOutputStream(file, true);
FileChannel channel = fos.getChannel();
lock = channel.tryLock();
} catch (IOException e) {
log.warn("Error while attempting to lock the file: " + file.getName(), e);
writable = false;
} finally {
if (lock != null) {
writable = true;
try {
lock.release();
} catch (IOException e) {
log.warn("Error while releasing the lock on file: " + file.getName(), e);
writable = false;
}
} else {
log.warn("Unable to acquire lock on file: " + file.getName());
writable = false;
}
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
log.warn("Error while closing the stream on file: " + file.getName(), e);
writable = false;
}
}
return writable;
}
}
use of java.nio.channels.FileLock in project xodus by JetBrains.
the class LogLockingTests method canWrite.
private static boolean canWrite(File xdLockFile) throws IOException {
boolean can = xdLockFile.canWrite();
if (can) {
FileOutputStream stream = null;
try {
stream = new FileOutputStream(xdLockFile);
stream.write(42);
stream.flush();
stream.close();
} catch (IOException ex) {
// xdLockFile.canWrite() returns true, because of Java cannot recognize tha file is locked
can = false;
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
can = false;
}
}
}
}
// If it didn't help for some reasons (saw that it doesn't work on Solaris 10)
if (can) {
RandomAccessFile file = null;
FileChannel channel = null;
try {
file = new RandomAccessFile(xdLockFile, "rw");
channel = file.getChannel();
FileLock lock = channel.tryLock();
if (lock != null) {
lock.release();
} else {
can = false;
}
file.close();
} catch (Throwable ignore) {
can = false;
} finally {
if (channel != null)
channel.close();
if (file != null)
file.close();
}
}
return can;
}
use of java.nio.channels.FileLock in project spf4j by zolyfarkas.
the class TimeSeriesDatabase method read.
/**
* Read measurements from table.
*
* @param tableName
* @param startTime start time including
* @param endTime end time including
* @return
* @throws IOException
*/
private TimeSeries read(final long startTime, final long endTime, final long startAtFragment, final long endAtFragment, final boolean skipFirst) throws IOException {
synchronized (path) {
TLongArrayList timeStamps = new TLongArrayList();
List<long[]> data = new ArrayList<>();
if (startAtFragment > 0) {
FileLock lock = ch.lock(0, Long.MAX_VALUE, true);
try {
DataFragment frag;
long nextFragmentLocation = startAtFragment;
boolean last = false;
boolean psFirst = skipFirst;
do {
if (nextFragmentLocation == endAtFragment) {
last = true;
}
file.seek(nextFragmentLocation);
frag = new DataFragment(file);
if (psFirst) {
psFirst = false;
} else {
long fragStartTime = frag.getStartTimeMillis();
if (fragStartTime >= startTime) {
TIntArrayList fragTimestamps = frag.getTimestamps();
int nr = 0;
for (int i = 0; i < fragTimestamps.size(); i++) {
long ts = fragStartTime + fragTimestamps.get(i);
if (ts <= endTime) {
timeStamps.add(ts);
nr++;
} else {
break;
}
}
int i = 0;
for (long[] d : frag.getData()) {
if (i < nr) {
data.add(d);
} else {
break;
}
nr++;
}
if (fragTimestamps.size() > nr) {
break;
}
}
}
nextFragmentLocation = frag.getNextDataFragment();
} while (nextFragmentLocation > 0 && !last);
} catch (IOException | RuntimeException e) {
try {
lock.release();
throw e;
} catch (IOException ex) {
ex.addSuppressed(e);
throw ex;
}
}
lock.release();
}
return new TimeSeries(timeStamps.toArray(), data.toArray(new long[data.size()][]));
}
}
Aggregations