List of usage examples for java.nio.file Files isReadable
public static boolean isReadable(Path path)
From source file:org.codice.ddf.cxf.client.impl.SecureCxfClientFactoryImpl.java
@SuppressWarnings("squid:S3776") private void configureConduit(ClientConfiguration clientConfig) { HTTPConduit httpConduit = clientConfig.getHttpConduit(); if (httpConduit == null) { LOGGER.info("HTTPConduit was null for {}. Unable to configure security.", this); return;// w ww .j a v a 2 s . com } if (allowRedirects) { HTTPClientPolicy clientPolicy = httpConduit.getClient(); if (clientPolicy != null) { clientPolicy.setAutoRedirect(true); Bus bus = clientConfig.getBus(); if (bus != null) { bus.getProperties().put(AUTO_REDIRECT_ALLOW_REL_URI, true); bus.getProperties().put(AUTO_REDIRECT_MAX_SAME_URI_COUNT, getSameUriRedirectMax()); } } } TLSClientParameters tlsParams = httpConduit.getTlsClientParameters(); if (tlsParams == null) { tlsParams = new TLSClientParameters(); } tlsParams.setDisableCNCheck(disableCnCheck); tlsParams.setUseHttpsURLConnectionDefaultHostnameVerifier(!disableCnCheck); String cipherSuites = System.getProperty("https.cipherSuites"); if (cipherSuites != null) { tlsParams.setCipherSuites(Arrays.asList(cipherSuites.split(","))); } KeyStore keyStore = null; KeyStore trustStore = null; try { keyStore = SecurityConstants.newKeystore(); trustStore = SecurityConstants.newTruststore(); } catch (KeyStoreException e) { LOGGER.debug("Unable to create keystore instance of type {}", System.getProperty(SecurityConstants.KEYSTORE_TYPE), e); } Path keyStoreFile; if (keyInfo != null && StringUtils.isNotBlank(keyInfo.getKeystorePath())) { keyStoreFile = Paths.get(keyInfo.getKeystorePath()); } else { keyStoreFile = Paths.get(SecurityConstants.getKeystorePath()); } Path trustStoreFile = Paths.get(SecurityConstants.getTruststorePath()); String ddfHome = System.getProperty("ddf.home"); if (ddfHome != null) { Path ddfHomePath = Paths.get(ddfHome); if (!keyStoreFile.isAbsolute()) { keyStoreFile = Paths.get(ddfHomePath.toString(), keyStoreFile.toString()); } if (!trustStoreFile.isAbsolute()) { trustStoreFile = Paths.get(ddfHomePath.toString(), trustStoreFile.toString()); } } String keyStorePassword = SecurityConstants.getKeystorePassword(); String trustStorePassword = SecurityConstants.getTruststorePassword(); if (!Files.isReadable(keyStoreFile) || !Files.isReadable(trustStoreFile)) { LOGGER.debug("Unable to read system key/trust store files: [ {} ] [ {} ]", keyStoreFile, trustStoreFile); return; } try (InputStream kfis = Files.newInputStream(keyStoreFile)) { if (keyStore != null) { keyStore.load(kfis, keyStorePassword.toCharArray()); } } catch (NoSuchAlgorithmException | CertificateException | IOException e) { LOGGER.debug("Unable to load system key file.", e); } try (InputStream tfis = Files.newInputStream(trustStoreFile)) { if (trustStore != null) { trustStore.load(tfis, trustStorePassword.toCharArray()); } } catch (NoSuchAlgorithmException | CertificateException | IOException e) { LOGGER.debug("Unable to load system trust file.", e); } KeyManager[] keyManagers = null; try { KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, keyStorePassword.toCharArray()); keyManagers = keyManagerFactory.getKeyManagers(); tlsParams.setKeyManagers(keyManagers); } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException e) { LOGGER.debug("Unable to initialize KeyManagerFactory.", e); } TrustManager[] trustManagers = null; try { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); trustManagers = trustManagerFactory.getTrustManagers(); tlsParams.setTrustManagers(trustManagers); } catch (NoSuchAlgorithmException | KeyStoreException e) { LOGGER.debug("Unable to initialize TrustManagerFactory.", e); } if (keyInfo != null) { LOGGER.trace("Using keystore file: {}, alias: {}", keyStoreFile, keyInfo.getAlias()); tlsParams.setUseHttpsURLConnectionDefaultSslSocketFactory(false); tlsParams.setCertAlias(keyInfo.getAlias()); try { if (keyManagers == null) { throw new KeyManagementException("keyManagers was null"); } boolean validProtocolFound = false; String validProtocolsStr = System.getProperty("jdk.tls.client.protocols"); if (StringUtils.isNotBlank(validProtocolsStr)) { String[] validProtocols = validProtocolsStr.split(","); for (String validProtocol : validProtocols) { if (validProtocol.equals(sslProtocol)) { validProtocolFound = true; break; } } if (!validProtocolFound) { LOGGER.error("{} is not in list of valid SSL protocols {}", sslProtocol, validProtocolsStr); } } else { validProtocolFound = true; } if (validProtocolFound) { tlsParams.setSSLSocketFactory( getSSLSocketFactory(sslProtocol, keyInfo.getAlias(), keyManagers, trustManagers)); } } catch (KeyManagementException | NoSuchAlgorithmException e) { LOGGER.debug("Unable to override default SSL Socket Factory", e); } } else { tlsParams.setUseHttpsURLConnectionDefaultSslSocketFactory(true); tlsParams.setCertAlias(SystemBaseUrl.INTERNAL.getHost()); } httpConduit.setTlsClientParameters(tlsParams); }
From source file:org.niord.core.batch.BatchService.java
/** Returns the list of regular files in the given directory **/ private List<Path> getDirectoryFiles(Path dir) { List<Path> files = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { for (Path p : stream) { if (Files.isReadable(p) && Files.isRegularFile(p) && !Files.isHidden(p)) { files.add(p);/*from ww w . ja v a2 s .c o m*/ } } } catch (IOException ignored) { } return files; }
From source file:misc.FileHandler.java
/** * Transmits the given file over the given output stream. Note that the * output stream is not closed by this function. * /*from w w w. ja va 2 s. c om*/ * @param file * the file to transmit. * @param byteFirst * first byte of the file to transmit. One-based. If * <code>null</code>, transmission starts at the first byte. * @param byteLast * the last byte of the file to transmit. Can be the file size at * max. If <code>null</code>, the file size is taken as this * argument. * @param out * the output stream over which the file should be sent. * @return <code>true</code>, if the file was successfully transmitted. * <code>false</code>, otherwise. */ public static boolean transmitFile(Path file, Long byteFirst, Long byteLast, OutputStream out) { if ((file == null) || !Files.isReadable(file)) { throw new IllegalArgumentException("file must exist and be readable!"); } if (byteFirst == null) { byteFirst = 1L; } else if (byteFirst < 1) { throw new IllegalArgumentException("byteFirst must be at least one!"); } if (byteLast == null) { try { byteLast = Files.size(file); } catch (IOException e) { Logger.logError(e); return false; } } else if (byteLast < 1) { throw new IllegalArgumentException("byteLast must be at least one!"); } if (out == null) { throw new NullPointerException("out may not be null!"); } boolean success = false; try (FileInputStream in = new FileInputStream(file.toFile());) { byte[] buffer = new byte[BUFFER_SIZE]; int count = 0; int read; in.skip(byteFirst - 1L); while ((count < byteLast) && ((read = in.read(buffer, 0, Math.min(buffer.length, (int) (byteLast - count)))) != -1)) { out.write(buffer, 0, read); count += read; } out.flush(); success = true; } catch (IOException e) { Logger.logError(e); } return success; }
From source file:org.vpac.ndg.cli.Client.java
/** * Querying data from the storage pool./* www.ja va 2 s. co m*/ * @param remainingArgs query file name * @throws TaskInitialisationException * @throws TaskException * @throws IOException * @throws QueryConfigurationException */ public void queryData(List<String> remainingArgs) throws IOException, TaskInitialisationException, TaskException { log.info("Querying data."); DataQuery queryRunner = sm.getDataQuery(); validateAsync(); // Dataset ID Path queryPath; try { queryPath = workingDirectory.resolve(remainingArgs.get(0)); } catch (IndexOutOfBoundsException e) { throw new IllegalArgumentException("Dataset ID not specified."); } if (!Files.isRegularFile(queryPath) || !Files.isReadable(queryPath)) { log.warn("Query definition \"{}\" does not appear to be readable.", queryPath); } queryRunner.setQueryPath(queryPath); // Spatial extents try { if (cmd.hasOption("e")) { String[] extents = cmd.getOptionValues("e"); queryRunner.setExtents(extents[0], extents[1], extents[2], extents[3]); } } catch (IndexOutOfBoundsException e) { throw new IllegalArgumentException("Spatial extents invalid."); } // Temporal extents try { if (cmd.hasOption("t")) { String[] extents = cmd.getOptionValues("t"); queryRunner.setTimeRange(extents[0], extents[1]); } } catch (IndexOutOfBoundsException e) { throw new IllegalArgumentException("Temporal extents invalid."); } // Multithreading if (cmd.hasOption("threads")) { String threads = cmd.getOptionValue("threads"); queryRunner.setThreads(threads); } // Output format if (cmd.hasOption("of")) queryRunner.setNetcdfVersion(cmd.getOptionValue("of")); String defaultFileName = queryPath.getFileName().toString(); defaultFileName += ".nc"; Path outputFile = getFileLocation(defaultFileName); queryRunner.setOutputPath(outputFile); log.debug("running query"); String taskId = queryRunner.start(); if (cmd.hasOption("async")) { printTask(taskId); } else { printTaskInline(taskId); JobProgress task = sm.getTaskConnector().get(taskId); if (task.getState() == TaskState.FINISHED) { sm.getDataDownloader().Download(taskId, outputFile); } } }