use of java.nio.file.NoSuchFileException in project helios by spotify.
the class TemporaryJobs method removeOldJobs.
/**
* Undeploys and deletes jobs leftover from previous runs of TemporaryJobs. This would happen if
* the test was terminated before the cleanup code was called. This method will iterate over each
* file in the specified directory. Each filename is the prefix that was used for job names
* during previous runs. The method will undeploy and delete any jobs that have a matching
* prefix, and the delete the file. If the file is locked, it is currently in use, and will be
* skipped.
*/
private void removeOldJobs() throws ExecutionException, InterruptedException, IOException {
// is used as a @Rule in a test class with many test methods
if (removedOldJobs) {
return;
}
final File[] files = prefixDirectory.toFile().listFiles();
if (files == null || files.length == 0) {
return;
}
log.info("Removing old temporary jobs");
final Map<JobId, Job> jobs = client.jobs(jobPrefixFile.prefix()).get();
// Iterate over all files in the directory
for (final File file : files) {
// directories. We don't expect any, but skip them just in case.
if (file.getName().endsWith(".tmp") || file.isDirectory()) {
continue;
}
// used by another process. In either case, skip over it.
try (JobPrefixFile prefixFile = JobPrefixFile.tryFromExistingFile(file.toPath())) {
if (prefixFile == null) {
log.debug("Unable to create JobPrefixFile for {}", file.getPath());
continue;
}
boolean jobRemovalFailed = false;
// Iterate over jobs, looking for ones with a matching prefix.
for (final Map.Entry<JobId, Job> entry : jobs.entrySet()) {
final JobId jobId = entry.getKey();
// Skip over job if the id doesn't start with current filename.
if (!jobId.getName().startsWith(prefixFile.prefix())) {
continue;
}
// Get list of all hosts where this job is deployed, and undeploy
final JobStatus status = client.jobStatus(entry.getKey()).get();
final List<String> hosts = ImmutableList.copyOf(status.getDeployments().keySet());
final List<AssertionError> errors = undeploy(client, entry.getValue(), hosts, new ArrayList<AssertionError>());
// Set flag indicating if any errors occur
if (!errors.isEmpty()) {
jobRemovalFailed = true;
}
}
// leave it there so we can try again next time.
if (!jobRemovalFailed) {
prefixFile.delete();
}
} catch (NoSuchFileException e) {
log.debug("File {} already processed by somebody else.", file.getPath());
} catch (Exception e) {
// log exception and continue on to next file
log.warn("Exception processing file {}", file.getPath(), e);
}
}
removedOldJobs = true;
}
use of java.nio.file.NoSuchFileException in project jena by apache.
the class RDFParser method openTypedInputStream.
@SuppressWarnings("resource")
private TypedInputStream openTypedInputStream(String urlStr, Path path) {
// If path, use that.
if (path != null) {
try {
InputStream in = Files.newInputStream(path);
ContentType ct = RDFLanguages.guessContentType(urlStr);
return new TypedInputStream(in, ct);
} catch (NoSuchFileException | FileNotFoundException ex) {
throw new RiotNotFoundException();
} catch (IOException ex) {
IO.exception(ex);
}
}
TypedInputStream in;
// Need more control than LocatorURL provides to get the Accept header in and the HttpCLient.
// So map now.
urlStr = streamManager.mapURI(urlStr);
if (urlStr.startsWith("http://") || urlStr.startsWith("https://")) {
// HTTP
String acceptHeader = HttpLib.dft(appAcceptHeader, WebContent.defaultRDFAcceptHeader);
HttpRequest request = HttpLib.newGetRequest(urlStr, (b) -> {
if (httpHeaders != null)
httpHeaders.forEach(b::header);
b.setHeader(HttpNames.hAccept, acceptHeader);
});
HttpResponse<InputStream> response = HttpLib.execute(httpClient, request);
in = HttpLib.handleResponseTypedInputStream(response);
} else {
// Already mapped.
in = streamManager.openNoMapOrNull(urlStr);
}
if (in == null)
throw new RiotNotFoundException("Not found: " + urlStr);
return in;
}
use of java.nio.file.NoSuchFileException in project runesource by PureCS.
the class Player method login.
public void login(String username, String password) throws Exception {
Server server = Server.getInstance();
Settings settings = server.getSettings();
int response = Misc.LOGIN_RESPONSE_OK;
// Updating credentials
attributes.setUsername(username);
attributes.setPassword(settings.isHashingPasswords() ? Misc.hashSha256(password) : password);
// Check if the player is already logged in.
if (WorldHandler.getInstance().isPlayerOnline(username)) {
response = Misc.LOGIN_RESPONSE_ACCOUNT_ONLINE;
}
// Load the player and send the login response.
PlayerAttributes attributes;
boolean validPassword = true;
boolean newPlayer = false;
try {
attributes = server.getPlayerFileHandler().load(this.attributes.getUsername());
validPassword = attributes.getPassword().equals(getAttributes().getPassword());
this.attributes = attributes;
} catch (NoSuchFileException e) {
newPlayer = true;
} catch (Exception e) {
response = Misc.LOGIN_RESPONSE_PLEASE_TRY_AGAIN;
}
boolean validCredentials = server.getCredentialValidator().validate(this.attributes.getUsername(), password);
// Invalid username/password - we skip the check if the account is found because the validation may have changed since
if ((newPlayer && !validCredentials) || !validPassword) {
response = Misc.LOGIN_RESPONSE_INVALID_CREDENTIALS;
ConnectionThrottle.enter(getHost());
}
// Check if banned
if (this.attributes.getInfractions().isBanned()) {
response = Misc.LOGIN_RESPONSE_ACCOUNT_DISABLED;
}
// Check if connection limit is exceeded
if (HostGateway.count(getHost()) >= settings.getMaxConsPerHost() + 1) {
response = Misc.LOGIN_RESPONSE_LOGIN_LIMIT_EXCEEDED;
}
// Check if login attempts exceeded
if (ConnectionThrottle.throttled(getHost())) {
response = Misc.LOGIN_RESPONSE_LOGIN_ATTEMPTS_EXCEEDED;
}
// Sending response
StreamBuffer.WriteBuffer resp = StreamBuffer.createWriteBuffer(3);
resp.writeByte(response);
resp.writeByte(getAttributes().getPrivilege().toInt());
resp.writeByte(0);
send(resp.getBuffer());
if (response != Misc.LOGIN_RESPONSE_OK) {
disconnect();
} else {
initSession(newPlayer);
}
}
use of java.nio.file.NoSuchFileException in project runesource by PureCS.
the class JsonPlayerFileHandler method load.
@Override
public PlayerAttributes load(String username) throws Exception {
// Checking if file exists
File file = new File(getStorageDirectory() + username + ".json");
if (!file.exists()) {
throw new NoSuchFileException(file.getAbsolutePath());
}
// Reading file
JsonReader reader = new JsonReader(new FileInputStream(file));
PlayerAttributes attributes = (PlayerAttributes) reader.readObject();
reader.close();
return attributes;
}
use of java.nio.file.NoSuchFileException in project jimfs by google.
the class JimfsUnixLikeFileSystemTest method testWriteLines_withStandardOptions.
@Test
public void testWriteLines_withStandardOptions() throws IOException {
Path test = path("/test.txt");
ImmutableList<String> lines = ImmutableList.of("hello", "world");
try {
// CREATE and CREATE_NEW not specified
Files.write(test, lines, UTF_8, WRITE);
fail();
} catch (NoSuchFileException expected) {
assertEquals(test.toString(), expected.getMessage());
}
// succeeds, file does not exist
Files.write(test, lines, UTF_8, CREATE_NEW);
assertThatPath(test).containsLines(lines);
try {
// CREATE_NEW requires file not exist
Files.write(test, lines, UTF_8, CREATE_NEW);
fail();
} catch (FileAlreadyExistsException expected) {
}
// succeeds, ok for file to already exist
Files.write(test, ImmutableList.of("foo"), UTF_8, CREATE);
// did not truncate or append, so overwrote
if (System.getProperty("line.separator").length() == 2) {
// on Windows, an extra character is overwritten by the \r\n line separator
assertThatPath(test).containsLines("foo", "", "world");
} else {
assertThatPath(test).containsLines("foo", "o", "world");
}
// default options
Files.write(test, lines, UTF_8, WRITE, CREATE, TRUNCATE_EXISTING);
assertThatPath(test).containsLines(lines);
Files.write(test, lines, UTF_8, WRITE, APPEND);
assertThatPath(test).containsLines("hello", "world", "hello", "world");
Files.write(test, lines, UTF_8, WRITE, CREATE, TRUNCATE_EXISTING, APPEND, SPARSE, DSYNC, SYNC);
assertThatPath(test).containsLines(lines);
try {
// READ not allowed
Files.write(test, lines, UTF_8, READ, WRITE);
fail();
} catch (UnsupportedOperationException expected) {
}
}
Aggregations