List of usage examples for java.nio.file Path getParent
Path getParent();
From source file:org.eclipse.winery.repository.backend.filebased.FilebasedRepository.java
@Override public void doImport(InputStream in) { ZipInputStream zis = new ZipInputStream(in); ZipEntry entry;//ww w . j a v a 2 s .c o m try { while ((entry = zis.getNextEntry()) != null) { if (!entry.isDirectory()) { Path path = this.repositoryRoot.resolve(entry.getName()); FileUtils.createDirectory(path.getParent()); Files.copy(zis, path); } } } catch (IOException e) { FilebasedRepository.logger.error(e.getMessage()); } }
From source file:business.services.FileService.java
public File uploadPart(User user, String name, File.AttachmentType type, MultipartFile file, Integer chunk, Integer chunks, String flowIdentifier) { try {//from w w w . j a v a 2 s .c o m String identifier = user.getId().toString() + "_" + flowIdentifier; String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE; log.info("File content-type: " + file.getContentType()); try { contentType = MediaType.valueOf(file.getContentType()).toString(); log.info("Media type: " + contentType); } catch (InvalidMediaTypeException e) { log.warn("Invalid content type: " + e.getMediaType()); //throw new FileUploadError("Invalid content type: " + e.getMediaType()); } InputStream input = file.getInputStream(); // Create temporary file for chunk Path path = fileSystem.getPath(uploadPath).normalize(); if (!path.toFile().exists()) { Files.createDirectory(path); } name = URLEncoder.encode(name, "utf-8"); String prefix = getBasename(name); String suffix = getExtension(name); Path f = Files.createTempFile(path, prefix, suffix + "." + chunk + ".chunk").normalize(); // filter path names that point to places outside the upload path. // E.g., to prevent that in cases where clients use '../' in the filename // arbitrary locations are reachable. if (!Files.isSameFile(path, f.getParent())) { // Path f is not in the upload path. Maybe 'name' contains '..'? throw new FileUploadError("Invalid file name"); } log.info("Copying file to " + f.toString()); // Copy chunk to temporary file Files.copy(input, f, StandardCopyOption.REPLACE_EXISTING); // Save chunk location in chunk map SortedMap<Integer, Path> chunkMap; synchronized (uploadChunks) { // FIXME: perhaps use a better identifier? Not sure if this one // is unique enough... chunkMap = uploadChunks.get(identifier); if (chunkMap == null) { chunkMap = new TreeMap<Integer, Path>(); uploadChunks.put(identifier, chunkMap); } } chunkMap.put(chunk, f); log.info("Chunk " + chunk + " saved to " + f.toString()); // Assemble complete file if all chunks have been received if (chunkMap.size() == chunks.intValue()) { uploadChunks.remove(identifier); Path assembly = Files.createTempFile(path, prefix, suffix).normalize(); // filter path names that point to places outside the upload path. // E.g., to prevent that in cases where clients use '../' in the filename // arbitrary locations are reachable. if (!Files.isSameFile(path, assembly.getParent())) { // Path assembly is not in the upload path. Maybe 'name' contains '..'? throw new FileUploadError("Invalid file name"); } log.info("Assembling file " + assembly.toString() + " from " + chunks + " chunks..."); OutputStream out = Files.newOutputStream(assembly, StandardOpenOption.CREATE, StandardOpenOption.APPEND); // Copy chunks to assembly file, delete chunk files for (int i = 1; i <= chunks; i++) { //log.info("Copying chunk " + i + "..."); Path source = chunkMap.get(new Integer(i)); if (source == null) { log.error("Cannot find chunk " + i); throw new FileUploadError("Cannot find chunk " + i); } Files.copy(source, out); Files.delete(source); } // Save assembled file name to database log.info("Saving attachment to database..."); File attachment = new File(); attachment.setName(URLDecoder.decode(name, "utf-8")); attachment.setType(type); attachment.setMimeType(contentType); attachment.setDate(new Date()); attachment.setUploader(user); attachment.setFilename(assembly.getFileName().toString()); attachment = fileRepository.save(attachment); return attachment; } return null; } catch (IOException e) { log.error(e); throw new FileUploadError(e.getMessage()); } }
From source file:org.apache.taverna.download.impl.DownloadManagerImpl.java
@Override public void download(URI source, Path destination, String digestAlgorithm, URI digestSource) throws DownloadException { MessageDigest md = null;/*from w ww. j a v a2 s . co m*/ if (digestAlgorithm != null) { try { md = MessageDigest.getInstance(digestAlgorithm); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("Unsupported digestAlgorithm: " + digestAlgorithm, e); } } // download the file Path tempFile; try { tempFile = Files.createTempFile(destination.getParent(), "." + destination.getFileName(), ".tmp"); } catch (IOException e1) { // perhaps a permission problem? throw new DownloadException("Can't create temporary file in folder " + destination.getParent(), e1); } logger.info(String.format("Downloading %1$s to %2$s", source, tempFile)); downloadToFile(source, tempFile); if (digestSource != null) { // download the digest file String expectedDigest; expectedDigest = downloadHash(digestSource).trim().toLowerCase(Locale.ROOT); // check if the digest matches try { try (InputStream s = Files.newInputStream(tempFile)) { DigestUtils.updateDigest(md, s); String actualDigest = Hex.encodeHexString(md.digest()); if (!actualDigest.equals(expectedDigest)) { throw new DownloadException( String.format("Error downloading file: checksum mismatch (%1$s != %2$s)", actualDigest, expectedDigest)); } } } catch (IOException e) { throw new DownloadException(String.format("Error checking digest for %1$s", destination), e); } } // All fine, move to destination try { logger.info(String.format("Copying %1$s to %2$s", tempFile, destination)); Files.move(tempFile, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new DownloadException(String.format("Error downloading %1$s to %2$s.", source, destination), e); } }
From source file:de.appsolve.padelcampus.utils.HtmlResourceUtil.java
private void replaceVariables(ServletContext context, List<CssAttribute> cssAttributes, String FILE_NAME, File destDir) throws IOException { InputStream lessIs = context.getResourceAsStream(FILE_NAME); Path outputPath = new File(destDir, FILE_NAME).toPath(); String content = IOUtils.toString(lessIs, Constants.UTF8); for (CssAttribute attribute : cssAttributes) { if (!StringUtils.isEmpty(attribute.getCssValue())) { content = content.replaceAll(attribute.getCssDefaultValue(), attribute.getCssValue()); }/*from www . j av a 2s.c o m*/ } //overwrite variables.less in data directory if (!Files.exists(outputPath)) { if (!Files.exists(outputPath.getParent())) { Files.createDirectory(outputPath.getParent()); } Files.createFile(outputPath); } Files.write(outputPath, content.getBytes(Constants.UTF8), StandardOpenOption.CREATE, StandardOpenOption.WRITE); }
From source file:net.mozq.picto.core.ProcessCore.java
public static void findFiles(ProcessCondition processCondition, Consumer<ProcessData> processDataSetter, BooleanSupplier processStopper) throws IOException { Set<FileVisitOption> fileVisitOptionSet; if (processCondition.isFollowLinks()) { fileVisitOptionSet = EnumSet.of(FileVisitOption.FOLLOW_LINKS); } else {/*from ww w .java 2s . c om*/ fileVisitOptionSet = Collections.emptySet(); } Files.walkFileTree(processCondition.getSrcRootPath(), fileVisitOptionSet, processCondition.getDept(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (processStopper.getAsBoolean()) { return FileVisitResult.TERMINATE; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (attrs.isDirectory()) { return FileVisitResult.SKIP_SUBTREE; } if (processStopper.getAsBoolean()) { return FileVisitResult.TERMINATE; } if (!processCondition.getPathFilter().accept(file, attrs)) { return FileVisitResult.SKIP_SUBTREE; } Path rootRelativeSubPath = processCondition.getSrcRootPath().relativize(file.getParent()); ImageMetadata imageMetadata = getImageMetadata(file); Date baseDate; if (processCondition.isChangeFileCreationDate() || processCondition.isChangeFileModifiedDate() || processCondition.isChangeFileAccessDate() || processCondition.isChangeExifDate()) { baseDate = getBaseDate(processCondition, file, attrs, imageMetadata); } else { baseDate = null; } String destSubPathname = processCondition.getDestSubPathFormat().format(varName -> { try { switch (varName) { case "Now": return new Date(); case "ParentSubPath": return rootRelativeSubPath.toString(); case "FileName": return file.getFileName().toString(); case "BaseName": return FileUtilz.getBaseName(file.getFileName().toString()); case "Extension": return FileUtilz.getExt(file.getFileName().toString()); case "Size": return Long.valueOf(Files.size(file)); case "CreationDate": return (processCondition.isChangeFileCreationDate()) ? baseDate : new Date(attrs.creationTime().toMillis()); case "ModifiedDate": return (processCondition.isChangeFileModifiedDate()) ? baseDate : new Date(attrs.lastModifiedTime().toMillis()); case "AccessDate": return (processCondition.isChangeFileAccessDate()) ? baseDate : new Date(attrs.lastAccessTime().toMillis()); case "PhotoTakenDate": return (processCondition.isChangeExifDate()) ? baseDate : getPhotoTakenDate(file, imageMetadata); case "Width": return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXIF_IMAGE_WIDTH); case "Height": return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXIF_IMAGE_LENGTH); case "FNumber": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_FNUMBER); case "Aperture": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_APERTURE_VALUE); case "MaxAperture": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_MAX_APERTURE_VALUE); case "ISO": return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_ISO); case "FocalLength": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_FOCAL_LENGTH); // ? case "FocalLength35mm": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_FOCAL_LENGTH_IN_35MM_FORMAT); case "ShutterSpeed": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_SHUTTER_SPEED_VALUE); case "Exposure": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXPOSURE); // case "ExposureTime": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXPOSURE_TIME); // case "ExposureMode": return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXPOSURE_MODE); case "ExposureProgram": return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXPOSURE_PROGRAM); case "Brightness": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_BRIGHTNESS_VALUE); case "WhiteBalance": return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_WHITE_BALANCE_1); case "LightSource": return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_LIGHT_SOURCE); case "Lens": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_LENS); case "LensMake": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_LENS_MAKE); case "LensModel": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_LENS_MODEL); case "LensSerialNumber": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_LENS_SERIAL_NUMBER); case "Make": return getEXIFStringValue(imageMetadata, TiffTagConstants.TIFF_TAG_MAKE); case "Model": return getEXIFStringValue(imageMetadata, TiffTagConstants.TIFF_TAG_MODEL); case "SerialNumber": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_SERIAL_NUMBER); case "Software": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_SOFTWARE); case "ProcessingSoftware": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_PROCESSING_SOFTWARE); case "OwnerName": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_OWNER_NAME); case "CameraOwnerName": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_CAMERA_OWNER_NAME); case "GPSLat": return getEXIFGpsLat(imageMetadata); case "GPSLatDeg": return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE, 0); case "GPSLatMin": return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE, 1); case "GPSLatSec": return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE, 2); case "GPSLatRef": return getEXIFStringValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE_REF); case "GPSLon": return getEXIFGpsLon(imageMetadata); case "GPSLonDeg": return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE, 0); case "GPSLonMin": return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE, 1); case "GPSLonSec": return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE, 2); case "GPSLonRef": return getEXIFStringValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE_REF); case "GPSAlt": return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_ALTITUDE); case "GPSAltRef": return getEXIFIntValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_ALTITUDE_REF); default: throw new PictoInvalidDestinationPathException(Messages .getString("message.warn.invalid.destSubPath.varName", varName)); } } catch (PictoException e) { throw e; } catch (Exception e) { throw new PictoInvalidDestinationPathException( Messages.getString("message.warn.invalid.destSubPath.pattern"), e); } }); Path destSubPath = processCondition.getDestRootPath().resolve(destSubPathname).normalize(); if (!destSubPath.startsWith(processCondition.getDestRootPath())) { throw new PictoInvalidDestinationPathException( Messages.getString("message.warn.invalid.destination.path", destSubPath)); } ProcessData processData = new ProcessData(); processData.setSrcPath(file); processData.setSrcFileAttributes(attrs); processData.setDestPath(destSubPath); processData.setBaseDate(baseDate); processDataSetter.accept(processData); return FileVisitResult.CONTINUE; } }); }
From source file:org.artifactory.storage.db.binstore.service.DoubleFileBinaryProviderImpl.java
@Override @Nonnull/* w ww .ja v a 2 s . c o m*/ public BinaryInfo addStream(InputStream in) throws IOException { ProviderAndTempFile[] providerAndTempFiles = null; Sha1Md5ChecksumInputStream checksumStream = null; try { // first save to a temp file and calculate checksums while saving if (in instanceof Sha1Md5ChecksumInputStream) { checksumStream = (Sha1Md5ChecksumInputStream) in; } else { checksumStream = new Sha1Md5ChecksumInputStream(in); } providerAndTempFiles = writeToTempFile(checksumStream); BinaryInfo bd = new BinaryInfoImpl(checksumStream); log.trace("Inserting {} in file binary provider", bd); String sha1 = bd.getSha1(); for (ProviderAndTempFile providerAndTempFile : providerAndTempFiles) { File tempFile = providerAndTempFile.tempFile; if (tempFile != null && providerAndTempFile.somethingWrong == null) { long fileLength = tempFile.length(); if (fileLength != checksumStream.getTotalBytesRead()) { throw new IOException("File length is " + fileLength + " while total bytes read on" + " stream is " + checksumStream.getTotalBytesRead()); } File file = providerAndTempFile.provider.getFile(sha1); Path target = file.toPath(); if (!java.nio.file.Files.exists(target)) { // move the file from the pre-filestore to the filestore java.nio.file.Files.createDirectories(target.getParent()); try { log.trace("Moving {} to {}", tempFile.getAbsolutePath(), target); java.nio.file.Files.move(tempFile.toPath(), target, StandardCopyOption.ATOMIC_MOVE); log.trace("Moved {} to {}", tempFile.getAbsolutePath(), target); } catch (FileAlreadyExistsException ignore) { // May happen in heavy concurrency cases log.trace("Failed moving {} to {}. File already exist", tempFile.getAbsolutePath(), target); } providerAndTempFile.tempFile = null; } else { log.trace("File {} already exist in the file store. Deleting temp file: {}", target, tempFile.getAbsolutePath()); } } } return bd; } finally { IOUtils.closeQuietly(checksumStream); if (providerAndTempFiles != null) { for (ProviderAndTempFile providerAndTempFile : providerAndTempFiles) { File file = providerAndTempFile.tempFile; if (file != null && file.exists()) { if (!file.delete()) { log.error("Could not delete temp file {}", file.getAbsolutePath()); } } } } } }
From source file:org.apache.marmotta.platform.core.services.importer.ImportWatchServiceImpl.java
/** * Detect the import format of the given file (mime-type) * @param file the file to check/*from w ww . j av a2 s. c o m*/ * @return the mime-type * @throws MarmottaImportException */ private String detectFormat(Path file) throws MarmottaImportException { String format = null; final String fileName = file.toFile().getName(); final Path config = file.getParent() .resolve(configurationService.getStringConfiguration(CONFIG_KEY_CONF_FILE, "config")); if (Files.isReadable(config)) { Properties prop = loadConfigFile(file); final String fmt = prop.getProperty("format"); if (fmt != null) { RDFFormat rdfFormat = Rio.getParserFormatForMIMEType(fmt); if (rdfFormat != null) { format = rdfFormat.getDefaultMIMEType(); log.debug("Using format {} from config file {}", format, config); } else { log.debug("Unknown format {} in config file {}, ignoring", fmt, config); } } else { log.trace("No format defined in {}", config); } } // mimetype detection based on file-extension if (format == null) { // FIXME: Maybe use GzipUtils and BZip2Utils instead? RDFFormat rdfFormat = Rio.getParserFormatForFileName(fileName.replaceFirst("\\.(gz|bz2)$", "")); if (rdfFormat != null) { format = rdfFormat.getDefaultMIMEType(); log.trace("Using format {} based on file-name {}", format, fileName); } } if (format == null || !importService.getAcceptTypes().contains(format)) { throw new MarmottaImportException("Suitable RDF parser not found"); } // encoding detection // FIXME: is this required? try (BufferedInputStream bis = new BufferedInputStream(openStream(file))) { CharsetDetector cd = new CharsetDetector(); cd.setText(bis); CharsetMatch cm = cd.detect(); if (cm != null) { log.trace("Detected charset {} in {}", cm.getName(), file); format += "; charset=" + cm.getName(); } bis.close(); } catch (IOException e) { log.error("Error detecting charset for '{}': {}", fileName, e.getMessage()); } return format; }
From source file:org.esa.s2tbx.dataio.gdal.GDALInstaller.java
private void processInstalledDistribution(Path gdalFolderPath, Path gdalBinFolderPath, OSCategory osCategory, String mapLibraryName) throws IOException { Path pathItem = gdalBinFolderPath.resolve(mapLibraryName); if (Files.exists(pathItem)) { // the library file exists on the local disk String libraryFileName = System.mapLibraryName("environment-variables"); Path libraryFilePath = gdalFolderPath.resolve(libraryFileName); if (!Files.exists(libraryFilePath)) { String libraryFilePathFromSources = SRC_PATH + "/" + libraryFileName; URL libraryFileURLFromSources = getClass().getClassLoader().getResource(libraryFilePathFromSources); FileHelper.copyFile(libraryFileURLFromSources, libraryFilePath); }/*from ww w . j ava 2 s . c o m*/ NativeLibraryUtils.registerNativePaths(libraryFilePath.getParent()); if (registerNativePaths(gdalBinFolderPath, osCategory)) { Path gdalAppsFolderPath = gdalBinFolderPath.resolve(APPS_PATH); String pathEnvironment = EnvironmentVariables.getEnvironmentVariable("PATH"); boolean foundBinFolderInPath = findFolderInPathEnvironment(gdalBinFolderPath, pathEnvironment); if (!foundBinFolderInPath) { StringBuilder newPathValue = new StringBuilder(); newPathValue.append("PATH").append("=").append(gdalBinFolderPath.toString()) .append(File.pathSeparator).append(gdalAppsFolderPath.toString()) .append(File.pathSeparator).append(pathEnvironment); EnvironmentVariables.setEnvironmentVariable(newPathValue.toString()); } Path gdalDataFolderPath = gdalBinFolderPath.resolve(DATA_PATH); StringBuilder gdalDataValue = new StringBuilder(); gdalDataValue.append("GDAL_DATA").append("=").append(gdalDataFolderPath.toString()); EnvironmentVariables.setEnvironmentVariable(gdalDataValue.toString()); Path gdalDriverFolderPath = gdalBinFolderPath.resolve(PLUGINS_PATH); StringBuilder gdalDriverValue = new StringBuilder(); gdalDriverValue.append("GDAL_DRIVER_PATH").append("=").append(gdalDriverFolderPath.toString()); EnvironmentVariables.setEnvironmentVariable(gdalDriverValue.toString()); GdalInstallInfo gdalInstallInfo = GdalInstallInfo.INSTANCE; gdalInstallInfo.setLocations(gdalBinFolderPath, gdalAppsFolderPath, gdalDriverFolderPath, gdalDataFolderPath); } } else { logger.log(Level.SEVERE, "The GDAL bin folder '" + gdalBinFolderPath.toString() + "' does not contain the library '" + mapLibraryName + "'."); } }
From source file:org.apache.taverna.robundle.TestBundles.java
@Test public void setReference() throws Exception { try (Bundle bundle = Bundles.createBundle()) { Path ref = bundle.getRoot().resolve("ref"); Bundles.setReference(ref, URI.create("http://example.org/test")); URI uri = URI.create("http://example.org/test"); Path f = Bundles.setReference(ref, uri); assertEquals("ref.url", f.getFileName().toString()); assertEquals(bundle.getRoot(), f.getParent()); assertFalse(Files.exists(ref)); List<String> uriLines = Files.readAllLines(f, Charset.forName("ASCII")); assertEquals(3, uriLines.size()); assertEquals("[InternetShortcut]", uriLines.get(0)); assertEquals("URL=http://example.org/test", uriLines.get(1)); assertEquals("", uriLines.get(2)); }/*from ww w. j a v a 2 s. c o m*/ }
From source file:org.alfresco.repo.bulkimport.impl.DirectoryAnalyserImpl.java
private Path getParentOfVersionFile(Path versionFile) { Path result = null;/*from w w w. j av a 2 s . c o m*/ if (!isVersionFile(versionFile)) { throw new IllegalStateException(FileUtils.getFileName(versionFile) + " is not a version file."); } String parentFilename = versionFile.getFileName().toString().replaceFirst(VERSION_SUFFIX_REGEX, ""); result = versionFile.getParent().resolve(parentFilename); return (result); }