List of usage examples for java.nio.file Path toFile
default File toFile()
From source file:ec.edu.chyc.manejopersonal.managebean.GestorAcuerdoConfidencialidad.java
public void fileUploadListener(FileUploadEvent event) { UploadedFile file = event.getFile(); //nombre del archivo que ya se encuentra almacenado en las propiedades String nombreArchivoGuardado; nombreArchivoGuardado = acuerdoConfidencial.getArchivoAcuerdoConf(); if (nombreArchivoGuardado.isEmpty() && !modoModificar) { //si la propiedad esta llena, significa que antes ya se subi un archivo y ahora est subiendo uno nuevo para reemplazarlo // por lo tanto hay que eliminar el archivo anterior Path pathArchivoAnterior = ServerUtils.getPathTemp().resolve(nombreArchivoGuardado).normalize(); File archivoEliminar = pathArchivoAnterior.toFile(); //borrar el archivo anterior en caso de existir if (archivoEliminar.isFile()) { archivoEliminar.delete();//from ww w.j a va 2 s.c o m } } if (file != null) { String extensionSubida = FilenameUtils.getExtension(file.getFileName()); String nombreArchivoSubido = ServerUtils.generarNombreValidoArchivo(extensionSubida); Path pathArchivo = ServerUtils.getPathTemp().resolve(nombreArchivoSubido).normalize(); File newFile = pathArchivo.toFile(); try { BeansUtils.subirArchivoPrimefaces(file, newFile); acuerdoConfidencial.setArchivoAcuerdoConf(nombreArchivoSubido); tamanoArchivo = ServerUtils.humanReadableByteCount(file.getSize()); } catch (IOException ex) { GestorMensajes.getInstance().mostrarMensajeError(ex.getLocalizedMessage()); Logger.getLogger(GestorAcuerdoConfidencialidad.class.getName()).log(Level.SEVERE, null, ex); } } else { System.err.println("Error al subir archivo"); } }
From source file:com.mesosphere.dcos.cassandra.executor.tasks.RestoreSnapshot.java
@Override public void run() { try {/*from w w w .ja va 2 s. co m*/ // Send TASK_RUNNING sendStatus(driver, Protos.TaskState.TASK_RUNNING, "Started restoring snapshot"); if (Objects.equals(context.getRestoreType(), new String("new"))) { final String keyspaceDirectory = context.getLocalLocation() + File.separator + context.getName() + File.separator + context.getNodeId(); final String ssTableLoaderBinary = CassandraPaths.create(version).bin().resolve("sstableloader") .toString(); final String cassandraYaml = CassandraPaths.create(version).cassandraConfig().toString(); final File keyspacesDirectory = new File(keyspaceDirectory); LOGGER.info("Keyspace Directory {} exists: {}", keyspaceDirectory, keyspacesDirectory.exists()); final File[] keyspaces = keyspacesDirectory.listFiles(); String libProcessAddress = System.getenv("LIBPROCESS_IP"); libProcessAddress = StringUtils.isBlank(libProcessAddress) ? InetAddress.getLocalHost().getHostAddress() : libProcessAddress; for (File keyspace : keyspaces) { final File[] columnFamilies = keyspace.listFiles(); final String keyspaceName = keyspace.getName(); if (keyspaceName.equals(StorageUtil.SCHEMA_FILE)) continue; LOGGER.info("Going to bulk load keyspace: {}", keyspaceName); for (File columnFamily : columnFamilies) { final String columnFamilyName = columnFamily.getName(); if (columnFamilyName.equals(StorageUtil.SCHEMA_FILE)) continue; LOGGER.info("Bulk loading... keyspace: {} column family: {}", keyspaceName, columnFamilyName); final String columnFamilyPath = columnFamily.getAbsolutePath(); final List<String> command = Arrays.asList(ssTableLoaderBinary, "-d", libProcessAddress, "-u", context.getUsername(), "-pw", context.getPassword(), "-f", cassandraYaml, columnFamilyPath); LOGGER.info("Executing command: {}", command); final ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { LOGGER.info(line); } int exitCode = process.waitFor(); LOGGER.info("Command exit code: {}", exitCode); // Send TASK_ERROR if (exitCode != 0) { final String errMessage = String.format("Error restoring snapshot. Exit code: %s", (exitCode + "")); LOGGER.error(errMessage); sendStatus(driver, Protos.TaskState.TASK_ERROR, errMessage); } LOGGER.info("Done bulk loading! keyspace: {} column family: {}", keyspaceName, columnFamilyName); } LOGGER.info("Successfully bulk loaded keyspace: {}", keyspaceName); } // cleanup downloaded snapshot directory recursively. Path rootPath = Paths.get(context.getLocalLocation() + File.separator + context.getName()); if (rootPath.toFile().exists()) { Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()) .map(Path::toFile).forEach(File::delete); } } else { // run nodetool refresh rather than SSTableLoader, as on performance test // I/O stream was pretty slow between mesos container processes final String localLocation = context.getLocalLocation(); final List<String> keyspaces = cassandra.getNonSystemKeySpaces(); for (String keyspace : keyspaces) { final String keySpaceDirPath = localLocation + "/" + keyspace; File keySpaceDir = new File(keySpaceDirPath); File[] cfNames = keySpaceDir .listFiles((current, name) -> new File(current, name).isDirectory()); for (File cfName : cfNames) { String columnFamily = cfName.getName().substring(0, cfName.getName().indexOf("-")); cassandra.getProbe().loadNewSSTables(keyspace, columnFamily); LOGGER.info("Completed nodetool refresh for keyspace {} & columnfamily {}", keyspace, columnFamily); } } } final String message = "Finished restoring snapshot"; LOGGER.info(message); sendStatus(driver, Protos.TaskState.TASK_FINISHED, message); } catch (Throwable t) { // Send TASK_FAILED final String errorMessage = "Failed restoring snapshot. Reason: " + t; LOGGER.error(errorMessage, t); sendStatus(driver, Protos.TaskState.TASK_FAILED, errorMessage); } }
From source file:business.services.FileService.java
@PostConstruct public void init() throws IOException { Path path = fileSystem.getPath(uploadPath).normalize(); if (!path.toFile().exists()) { Files.createDirectory(path); }/*from www.j a va2 s .com*/ log.info("File upload path: " + path.toAbsolutePath()); }
From source file:de.fenvariel.mavenfreemarker.FreemarkerPlugin.java
private void generate(TemplateConfiguration config) throws MojoExecutionException { Template template;// w ww .j av a 2 s. c o m try { template = getFreemarker(config.getVersion()).getTemplate(config.getFtlTemplate(), "UTF-8"); } catch (Exception ex) { throw new MojoExecutionException("error reading template-file " + config.getFtlTemplate(), ex); } File outputDir = config.getOutputDir(); if (!outputDir.exists()) { outputDir.mkdirs(); } for (SourceBundle source : config.getSourceBundles()) { Collection<File> sourceFiles; try { sourceFiles = source.getSourceFiles(baseDir); } catch (IOException ex) { throw new MojoExecutionException("error reading source files", ex); } if (sourceFiles == null || sourceFiles.isEmpty()) { throw new MojoExecutionException("no source files found for bundle"); } for (File sourceFile : sourceFiles) { String destinationFilename = config.getPrefix() + getNameWithoutExtension(sourceFile) + config.getSuffix(); Path destinationFilePath = Paths.get(outputDir.getAbsolutePath(), destinationFilename + config.getTargetExtension()); File destinationFile = destinationFilePath.toFile(); Map<String, Object> root = new HashMap<String, Object>(); root.put("data", readJson(sourceFile)); root.put("additionalData", source.getAdditionalData()); Map<String, Object> configMap = getConfig(config); configMap.put("destinationFilePath", destinationFilePath); configMap.put("destinationFilename", destinationFilename); root.put("config", configMap); generate(template, destinationFile, root, config.getEditableSectionNames()); } } }
From source file:ee.ria.xroad.confproxy.util.OutputBuilder.java
/** * Computes the verification hash of the certificate at the given path. * @param certPath path to the certificate file * @return verification hash for the certificate * @throws Exception if failed to open the certificate file *///w ww . jav a 2s . c o m private String getVerificationCertHash(final Path certPath) throws Exception { try (InputStream is = new FileInputStream(certPath.toFile())) { byte[] certBytes = CryptoUtils.readCertificate(is).getEncoded(); return hashCalculator.calculateFromBytes(certBytes); } }
From source file:org.red5.server.service.ShutdownServer.java
/** * Starts internal server listening for shutdown requests. *///from w w w . j av a2 s .com public void start() { // dump to stdout System.out.printf("Token: %s%n", token); // write out the token to a file so that red5 may be shutdown external to this VM instance. try { // delete existing file Files.deleteIfExists(Paths.get(shutdownTokenFileName)); // write to file Path path = Files.createFile(Paths.get(shutdownTokenFileName)); File tokenFile = path.toFile(); RandomAccessFile raf = new RandomAccessFile(tokenFile, "rws"); raf.write(token.getBytes()); raf.close(); } catch (Exception e) { log.warn("Exception handling token file", e); } while (!shutdown.get()) { try (ServerSocket serverSocket = new ServerSocket(port); Socket clientSocket = serverSocket.accept(); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));) { log.info("Connected - local: {} remote: {}", clientSocket.getLocalSocketAddress(), clientSocket.getRemoteSocketAddress()); String inputLine = in.readLine(); if (inputLine != null && token.equals(inputLine)) { log.info("Shutdown request validated using token"); out.println("Ok"); shutdownOrderly(); } else { out.println("Bye"); } } catch (BindException be) { log.error("Cannot bind to port: {}, ensure no other instances are bound or choose another port", port, be); shutdownOrderly(); } catch (IOException e) { log.warn("Exception caught when trying to listen on port {} or listening for a connection", port, e); } } }
From source file:cc.sferalabs.libs.telegram.bot.api.TelegramBot.java
/** * Sends a request to the server./*from ww w . ja v a2s . co m*/ * * @param <T> * the class to cast the returned value to * @param request * the request to be sent * @param timeout * the read timeout value (in milliseconds) to be used for server * response. A timeout of zero is interpreted as an infinite * timeout * @return the JSON object representing the value of the field "result" of * the response JSON object cast to the specified type parameter * @throws ResponseError * if the server returned an error response, i.e. the value of * the field "ok" of the response JSON object is {@code false} * @throws ParseException * if an error occurs while parsing the server response * @throws IOException * if an I/O exception occurs */ @SuppressWarnings("unchecked") public <T> T sendRequest(Request request, int timeout) throws IOException, ParseException, ResponseError { HttpURLConnection connection = null; try { URL url = buildUrl(request); log.debug("Performing request: {}", url); connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(timeout); if (request instanceof SendFileRequest) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); Path filePath = ((SendFileRequest) request).getFilePath(); builder.addBinaryBody(((SendFileRequest) request).getFileParamName(), filePath.toFile()); HttpEntity multipart = builder.build(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", multipart.getContentType().getValue()); connection.setRequestProperty("Content-Length", "" + multipart.getContentLength()); try (OutputStream out = connection.getOutputStream()) { multipart.writeTo(out); } } else { connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Length", "0"); } boolean httpOk = connection.getResponseCode() == HttpURLConnection.HTTP_OK; try (InputStream in = httpOk ? connection.getInputStream() : connection.getErrorStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) { JSONObject resp = (JSONObject) parser.parse(br); log.debug("Response: {}", resp); boolean ok = (boolean) resp.get("ok"); if (!ok) { String description = (String) resp.get("description"); if (description == null) { description = "ok=false"; } throw new ResponseError(description); } return (T) resp.get("result"); } } finally { if (connection != null) { connection.disconnect(); } } }
From source file:com.surevine.gateway.scm.IncomingProcessorImpl.java
public TarArchiveInputStream openTarGz(final Path archivePath) throws IOException { final File file = archivePath.toFile(); return new TarArchiveInputStream( new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(file)))); }
From source file:joachimeichborn.geotag.io.writer.kml.KmlWriter.java
/** * Create the output KML file containing: * <ul>//ww w .j av a2 s. c o m * <li>placemarks for all positions * <li>a path connecting all positions in chronological order * <li>circles showing the accuracy information for all positions * </ul> * * @throws IOException */ public void write(final Track aTrack, final Path aOutputFile) throws IOException { final String documentTitle = FilenameUtils.removeExtension(aOutputFile.getFileName().toString()); final GeoTagKml kml = createKml(documentTitle, aTrack); try (final Writer kmlWriter = new OutputStreamWriter( new BufferedOutputStream(new FileOutputStream(aOutputFile.toFile())), StandardCharsets.UTF_8)) { kml.marshal(kmlWriter); } logger.fine("Wrote track to " + aOutputFile); }
From source file:gov.vha.isaac.rf2.filter.RF2Filter.java
@Override public void execute() throws MojoExecutionException { if (!inputDirectory.exists() || !inputDirectory.isDirectory()) { throw new MojoExecutionException("Path doesn't exist or isn't a folder: " + inputDirectory); }// w w w . j av a 2s. co m if (module == null) { throw new MojoExecutionException("You must provide a module or namespace for filtering"); } moduleStrings_.add(module + ""); outputDirectory.mkdirs(); File temp = new File(outputDirectory, inputDirectory.getName()); temp.mkdirs(); Path source = inputDirectory.toPath(); Path target = temp.toPath(); try { getLog().info("Reading from " + inputDirectory.getAbsolutePath()); getLog().info("Writing to " + outputDirectory.getCanonicalPath()); summary_.append("This content was filtered by an RF2 filter tool. The parameters were module: " + module + " software version: " + converterVersion); summary_.append("\r\n\r\n"); getLog().info("Checking for nested child modules"); //look in sct2_Relationship_ files, find anything where the 6th column (destinationId) is the //starting module ID concept - and add that sourceId (5th column) to our list of modules to extract Files.walkFileTree(source, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.toFile().getName().startsWith("sct2_Relationship_")) { //don't look for quotes, the data is bad, and has floating instances of '"' all by itself CSVReader csvReader = new CSVReader( new InputStreamReader(new FileInputStream(file.toFile())), '\t', CSVParser.NULL_CHARACTER); String[] line = csvReader.readNext(); if (!line[4].equals("sourceId") || !line[5].equals("destinationId")) { csvReader.close(); throw new IOException("Unexpected error looking for nested modules"); } line = csvReader.readNext(); while (line != null) { if (line[5].equals(moduleStrings_.get(0))) { moduleStrings_.add(line[4]); } line = csvReader.readNext(); } csvReader.close(); } return FileVisitResult.CONTINUE; } }); log("Full module list (including detected nested modules: " + Arrays.toString(moduleStrings_.toArray(new String[moduleStrings_.size()]))); Files.walkFileTree(source, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Path targetdir = target.resolve(source.relativize(dir)); try { //this just creates the sub-directory in the target Files.copy(dir, targetdir); } catch (FileAlreadyExistsException e) { if (!Files.isDirectory(targetdir)) throw e; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { handleFile(file, target.resolve(source.relativize(file))); return FileVisitResult.CONTINUE; } }); Files.write(new File(temp, "FilterInfo.txt").toPath(), summary_.toString().getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException e) { throw new MojoExecutionException("Failure", e); } getLog().info("Filter Complete"); }