Java Code Examples for java.nio.file.Files

The following are top voted examples for showing how to use java.nio.file.Files. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openapi-annotation-processor   File: PathUtils.java   Source Code and License 8 votes vote down vote up
/**
 * @param path The patch to scan
 * @return All direct and indirect sub files
 */
public static List<Path> subFiles(Path path) {
    List<Path> files = new ArrayList<>();
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path)) {
        for (Path subPath : directoryStream) {
            if (Files.isDirectory(subPath)) {
                files.addAll(subFiles(subPath));
            } else {
                files.add(subPath);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return files;
}
 
Example 2
Project: OpenJSharp   File: Main.java   Source Code and License 7 votes vote down vote up
/**
 * Outputs the class index table to the INDEX.LIST file of the
 * root jar file.
 */
void dumpIndex(String rootjar, JarIndex index) throws IOException {
    File jarFile = new File(rootjar);
    Path jarPath = jarFile.toPath();
    Path tmpPath = createTempFileInSameDirectoryAs(jarFile).toPath();
    try {
        if (update(Files.newInputStream(jarPath),
                   Files.newOutputStream(tmpPath),
                   null, index)) {
            try {
                Files.move(tmpPath, jarPath, REPLACE_EXISTING);
            } catch (IOException e) {
                throw new IOException(getMsg("error.write.file"), e);
            }
        }
    } finally {
        Files.deleteIfExists(tmpPath);
    }
}
 
Example 3
Project: smart-testing   File: CustomProviderInfo.java   Source Code and License 6 votes vote down vote up
void retrieveCustomProviderInformation(File projectDir, String failsafePluginVersion) {

        final boolean isFailsafePlugin = failsafePluginVersion != null;
        final String prefix = isFailsafePlugin ? LoaderVersionExtractor.ARTIFACT_ID_MAVEN_FAILSAFE_PLUGIN
            : LoaderVersionExtractor.ARTIFACT_ID_MAVEN_SUREFIRE_PLUGIN;

        File dir = TemporaryInternalFiles.createCustomProvidersDirAction(projectDir, prefix).getFile();

        if (dir.exists() && dir.listFiles().length > 0) {
            File customProviderInfoFile = dir.listFiles()[0];
            gav = customProviderInfoFile.getName();
            try {
                providerClassName = new String(Files.readAllBytes(customProviderInfoFile.toPath()));
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }
    }
 
Example 4
Project: rdf4j-schema-generator   File: SchemaGeneratorTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test method for {@link com.github.ansell.rdf4j.schemagenerator.RDF4JSchemaGeneratorCore#generate(java.nio.file.Path)}.
 */
@Test
public final void testUpperUnderscoreCaseString() throws Exception {
    Path outputPath = testDir.resolve("output");
    Files.createDirectories(outputPath);

    RDF4JSchemaGeneratorCore testBuilder = new RDF4JSchemaGeneratorCore(inputPath.toAbsolutePath().toString(), format);

    testBuilder.setStringConstantCase(CaseFormat.UPPER_UNDERSCORE);

    Path javaFilePath = outputPath.resolve("Test.java");
    testBuilder.generate(javaFilePath);
    assertTrue("Java file was not found", Files.exists(javaFilePath));
    assertTrue("Java file was empty", Files.size(javaFilePath) > 0);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Files.copy(javaFilePath, out);
    String result = new String(out.toByteArray(), StandardCharsets.UTF_8);
    assertTrue("Did not find expected key case", result.contains("PROPERTY_LOCALISED4 = "));
    assertTrue("Did not find original URI", result.contains("\"http://example.com/ns/ontology#propertyLocalised4\""));
}
 
Example 5
Project: openjdk-jdk10   File: ValidateModulesTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test two modules with the same name in different directories.
 */
public void testShadowed() throws Exception {
    Path tmpdir = Files.createTempDirectory("tmp");

    Path classes = Files.createDirectory(tmpdir.resolve("classes"));
    touch(classes, "org/foo/Bar.class");

    Path lib1 = Files.createDirectory(tmpdir.resolve("lib1"));
    JarUtils.createJarFile(lib1.resolve("foo-1.0.jar"), classes);

    Path lib2 = Files.createDirectory(tmpdir.resolve("lib2"));
    JarUtils.createJarFile(lib2.resolve("foo-2.0.jar"), classes);

    run("-p", lib1 + File.pathSeparator + lib2, "--validate-modules")
            .shouldContain("shadowed by")
            .shouldHaveExitValue(0);
}
 
Example 6
Project: incubator-netbeans   File: ModuleMainClassTest.java   Source Code and License 6 votes vote down vote up
private String getMainClass(Path p) throws IOException {
    try(final InputStream in = Files.newInputStream(p)) {
        final ClassFile cf = new ClassFile(in);
        final ConstantPool cp = cf.getConstantPool();
        for (Attribute attr : cf.getAttributes()) {
            int nameIndex = attr.getNameIndex();
            ConstantPool.CPInfo entry = cp.get(nameIndex);
            if ("ModuleMainClass".equals(entry.getValue())) {   //NOI18N
                byte[] value = attr.getValue();
                nameIndex = (value[0] & 0xff) << 8 | (value[1] & 0xff);
                entry = cp.get(nameIndex);
                return ((String)entry.getValue()).replace('/', '.');    //NOI18N
            }
        }
    }
    return null;
}
 
Example 7
Project: octane-cucumber-jvm   File: OutputFile.java   Source Code and License 6 votes vote down vote up
public File getOutputFile(Class testClass) {
	if(testClass == null) {
		throw new IllegalArgumentException("testClass cannot be null");
	}

	try {
		File outputFolder = new File(Constants.RESULTS_FOLDER);
		Files.createDirectories(outputFolder.toPath()); // if directory already exists will do nothing

		//testClass.getName() is the unique identifier of the class
		String fileName = String.format("%s_%s", testClass.getName(), Constants.RESULTS_FILE_NAME_POSTFIX);
		File outputFile = new File(outputFolder, fileName);
		outputFile.createNewFile(); // if file already exists will do nothing
		return outputFile;
	} catch (IOException e) {
		throw new CucumberException(Constants.errorPrefix + "Failed to create cucumber results output directory", e);
	}
}
 
Example 8
Project: CloudNet   File: PacketInInstallUpdate.java   Source Code and License 6 votes vote down vote up
@Override
public void handleInput(Document data, PacketSender packetSender)
{
    try
    {
        URLConnection url = new java.net.URL(data.getString("url")).openConnection();
        url.connect();
        if(System.getProperty("os.name").toLowerCase().contains("windows"))
        {
            Files.copy(url.getInputStream(), Paths.get("CloudNet-Wrapper-" + NetworkUtils.RANDOM.nextLong() + ".jar"));
        }
        else
        {
            Files.copy(url.getInputStream(), Paths.get("CloudNet-Wrapper.jar"));
        }
    }catch (Exception ex){
        ex.printStackTrace();
    }
}
 
Example 9
Project: openjdk-jdk10   File: ModuleReaderTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test ModuleReader to JMOD
 */
public void testJMod() throws IOException {
    Path dir = Files.createTempDirectory(USER_DIR, "mlib");

    // jmod create --class-path mods/${TESTMODULE}  mlib/${TESTMODULE}.jmod
    String cp = MODS_DIR.resolve(TEST_MODULE).toString();
    String jmod = dir.resolve("m.jmod").toString();
    String[] args = { "create", "--class-path", cp, jmod };
    ToolProvider jmodTool = ToolProvider.findFirst("jmod")
        .orElseThrow(() ->
            new RuntimeException("jmod tool not found")
        );
    assertEquals(jmodTool.run(System.out, System.out, args), 0);

    test(dir);
}
 
Example 10
Project: Avalon-Executive   File: PreProcessor.java   Source Code and License 6 votes vote down vote up
public File createFile(Submission submission) throws IOException {
	File workDirFile = new File(Constants._WORK_DIR());

	if (!workDirFile.exists() && !workDirFile.mkdirs())
		throw new IOException("failed to create directory: " + Constants._WORK_DIR());

	Language language = submission.getLanguage();
	String codeFilePath = String.format("%s/%s.%s", Constants._WORK_DIR(),
			submission.getSubmitTime(), getCodeFileSuffix(language.getCompileCmd()));

	String[] codeLinesArray = replaceClassName(language, submission.getDecodedCode())
			.replace("\r", "")
			.split("\n");

	Files.createDirectories(Paths.get(codeFilePath).getParent());

	BufferedWriter writer = new BufferedWriter(new FileWriter(codeFilePath));
	for (String thisLineCode : codeLinesArray) {
		writer.write(thisLineCode);
		writer.newLine();
	}
	IOUtils.closeQuietly(writer);
	return new File(codeFilePath);
}
 
Example 11
Project: Learning-Spring-Boot-2.0-Second-Edition   File: ImageService.java   Source Code and License 6 votes vote down vote up
/**
 * Pre-load some fake images
 *
 * @return Spring Boot {@link CommandLineRunner} automatically run after app context is loaded.
 */
@Bean
CommandLineRunner setUp() throws IOException {
	return (args) -> {
		FileSystemUtils.deleteRecursively(new File(UPLOAD_ROOT));

		Files.createDirectory(Paths.get(UPLOAD_ROOT));

		FileCopyUtils.copy("Test file",
			new FileWriter(UPLOAD_ROOT +
				"/learning-spring-boot-cover.jpg"));

		FileCopyUtils.copy("Test file2",
			new FileWriter(UPLOAD_ROOT +
				"/learning-spring-boot-2nd-edition-cover.jpg"));

		FileCopyUtils.copy("Test file3",
			new FileWriter(UPLOAD_ROOT + "/bazinga.png"));
	};
}
 
Example 12
Project: elasticsearch_my   File: TruncateTranslogIT.java   Source Code and License 6 votes vote down vote up
private Set<Path> getTranslogDirs(String indexName) throws IOException {
    ClusterState state = client().admin().cluster().prepareState().get().getState();
    GroupShardsIterator shardIterators = state.getRoutingTable().activePrimaryShardsGrouped(new String[]{indexName}, false);
    final Index idx = state.metaData().index(indexName).getIndex();
    List<ShardIterator> iterators = iterableAsArrayList(shardIterators);
    ShardIterator shardIterator = RandomPicks.randomFrom(random(), iterators);
    ShardRouting shardRouting = shardIterator.nextOrNull();
    assertNotNull(shardRouting);
    assertTrue(shardRouting.primary());
    assertTrue(shardRouting.assignedToNode());
    String nodeId = shardRouting.currentNodeId();
    NodesStatsResponse nodeStatses = client().admin().cluster().prepareNodesStats(nodeId).setFs(true).get();
    Set<Path> translogDirs = new TreeSet<>(); // treeset makes sure iteration order is deterministic
    for (FsInfo.Path fsPath : nodeStatses.getNodes().get(0).getFs()) {
        String path = fsPath.getPath();
        final String relativeDataLocationPath =  "indices/"+ idx.getUUID() +"/" + Integer.toString(shardRouting.getId()) + "/translog";
        Path translogPath = PathUtils.get(path).resolve(relativeDataLocationPath);
        if (Files.isDirectory(translogPath)) {
            translogDirs.add(translogPath);
        }
    }
    return translogDirs;
}
 
Example 13
Project: springrestdoc   File: Swagger2MarkupTest.java   Source Code and License 6 votes vote down vote up
@Test
public void createJsonFileFromSwaggerEndpoint() throws Exception {
    String outputDir = Optional.ofNullable(System.getProperty("io.springfox.staticdocs.outputDir"))
            .orElse("build/swagger");
    System.err.println(outputDir);
    MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andReturn();

    MockHttpServletResponse response = mvcResult.getResponse();
    String swaggerJson = response.getContentAsString();
    Files.createDirectories(Paths.get(outputDir));
    try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"),
            StandardCharsets.UTF_8)) {
        writer.write(swaggerJson);
    }
}
 
Example 14
Project: Java-for-Data-Science   File: SentimentAnalysisTrainingData.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    try {
        String filename;
        String file;
        String text;
        List<String> lines = Files.readAllLines(Paths.get("C:\\Jenn Personal\\Packt Data Science\\Chapter 12\\Sentiment-Analysis-Dataset\\SentimentAnalysisDataset.csv"),StandardCharsets.ISO_8859_1);
        for(String s : lines){
            String[] oneLine = s.split(",");
            if(Integer.parseInt(oneLine[1])==1){
                filename = "pos";
            }else{
                filename = "neg";
            }
            file = oneLine[0]+".txt";
            text = oneLine[3];
            Files.write(Paths.get("C:\\Jenn Personal\\Packt Data Science\\Chapter 12\\review_polarity\\txt_sentoken\\"+filename+"\\"+file), text.getBytes());
        }
      
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
 
Example 15
Project: buenojo   File: ImageCompletionLoader.java   Source Code and License 6 votes vote down vote up
private void setImages(Path path, ImageCompletionExercise exercise, Boolean dryRun) throws BuenOjoDataSetException{
	try {
		
		Set<SatelliteImage> images = new HashSet<>(maxImages);
		List<Path> imageList = Files.walk(path, 1, FileVisitOption.FOLLOW_LINKS).filter(p-> {
			return BuenOjoFileUtils.contentType(p).isPresent() && !BuenOjoFileUtils.contentType(p).get().equals("text/csv")  && !isPlaceholderImage(p);
			}).collect(Collectors.toList());
		
		for (Path imagePath : imageList) {
			
			String fileName = FilenameUtils.removeExtension(imagePath.getFileName().toString());
			Path csvPath = path.resolve(fileName + FilenameUtils.EXTENSION_SEPARATOR+ BuenOjoFileUtils.CSV_EXTENSION);
			
			SatelliteImage image = satelliteImageFactory.imageFromFile(BuenOjoFileUtils.multipartFile(imagePath), BuenOjoFileUtils.multipartFile(csvPath), dryRun);
			images.add(image);
			
		}
		exercise.setSatelliteImages(new HashSet<>(satelliteImageRepository.save(images)));
	} catch (BuenOjoCSVParserException | InvalidSatelliteImageType | BuenOjoFileException | IOException
			| BuenOjoInconsistencyException e) {
		throw new BuenOjoDataSetException(e.getMessage());
	}
}
 
Example 16
Project: elasticsearch_my   File: InstallPluginCommandTests.java   Source Code and License 6 votes vote down vote up
public void testBinPermissions() throws Exception {
    assumeTrue("posix filesystem", isPosix);
    Tuple<Path, Environment> env = createEnv(fs, temp);
    Path pluginDir = createPluginDir(temp);
    Path binDir = pluginDir.resolve("bin");
    Files.createDirectory(binDir);
    Files.createFile(binDir.resolve("somescript"));
    String pluginZip = createPlugin("fake", pluginDir);
    try (PosixPermissionsResetter binAttrs = new PosixPermissionsResetter(env.v2().binFile())) {
        Set<PosixFilePermission> perms = binAttrs.getCopyPermissions();
        // make sure at least one execute perm is missing, so we know we forced it during installation
        perms.remove(PosixFilePermission.GROUP_EXECUTE);
        binAttrs.setPermissions(perms);
        installPlugin(pluginZip, env.v1());
        assertPlugin("fake", pluginDir, env.v2());
    }
}
 
Example 17
Project: grade-buddy   File: Toolbar.java   Source Code and License 6 votes vote down vote up
/**
 * Export the report.
 */
private void export() {
    final JFileChooser fc = new JFileChooser();
    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    if (JFileChooser.APPROVE_OPTION == fc.showOpenDialog(this)) {
        final File file = new File(fc.getSelectedFile(), "report.csv");
        try {
            Files.write(
                Paths.get(file.getAbsolutePath()),
                new CsvReport(this.marking.submissions())
                    .report(true)
                    .getBytes()
            );
        } catch (IOException e1) {
            e1.printStackTrace();
            JOptionPane.showMessageDialog(
                this, e1.getMessage(), "Export error", JOptionPane.ERROR_MESSAGE);
        }
    }
}
 
Example 18
Project: iopipe-java-core   File: SystemMeasurement.java   Source Code and License 6 votes vote down vote up
/**
 * Reads the first non-empty line for the given path.
 *
 * @param __p The path to read.
 * @param __def Default value if it could not be read.
 * @return The first non-empty line or {@code __def} if the file could not
 * be read or has only empty lines.
 * @throws NullPointerException On null arguments.
 * @since 2017/12/17
 */
private static String __readFirstLine(Path __p, String __def)
	throws NullPointerException
{
	if (__p == null)
		throw new NullPointerException();
	
	try
	{
		for (String l : Files.readAllLines(__p))
		{
			l = l.trim();
			if (!l.isEmpty())
				return l;
		}
		
		return __def;
	}
	
	catch (IOException e)
	{
		return __def;
	}
}
 
Example 19
Project: CloudNet   File: CloudConfig.java   Source Code and License 6 votes vote down vote up
private void defaultInitDoc(ConsoleReader consoleReader) throws Exception
{
    if (Files.exists(servicePath)) return;

    String hostName = NetworkUtils.getHostName();
    if (hostName.equals("127.0.0.1") || hostName.equalsIgnoreCase("127.0.1.1") || hostName.split("\\.").length != 4)
    {
        String input;
        System.out.println("Please write the first Wrapper IP address:");
        while ((input = consoleReader.readLine()) != null)
        {
            if ((input.equals("127.0.0.1") || input.equalsIgnoreCase("127.0.1.1") || input.split("\\.").length != 4))
            {
                System.out.println("Please write the real ip address :)");
                continue;
            }

            hostName = input;
            break;
        }
    }
    new Document("wrapper", Arrays.asList(new WrapperMeta("Wrapper-1", hostName, "admin")))
            .append("serverGroups", Arrays.asList(new LobbyGroup()))
            .append("proxyGroups", Arrays.asList(new BungeeGroup()))
            .saveAsConfig(servicePath);
}
 
Example 20
Project: jobson   File: FilesystemUserDAO.java   Source Code and License 6 votes vote down vote up
@Override
public boolean updateUserAuth(UserId id, String authName, String authField) {
    try {
        final List<UserCredentials> allCredentials = readUserCredentials().collect(Collectors.toList());

        final boolean userExists = allCredentials.stream().anyMatch(c -> c.getId().equals(id));

        if (userExists) {
            // TODO: Clean up
            final UserCredentials newUserCredentials = new UserCredentials(id, authName, authField);
            final Stream<UserCredentials> otherCredentials = allCredentials.stream().filter(c -> !c.getId().equals(id));
            final Stream<UserCredentials> upd = Stream.concat(otherCredentials, Stream.of(newUserCredentials));
            final String fileContent = String.join("", upd.map(c -> c + System.lineSeparator()).collect(Collectors.toList()));
            Files.write(usersFile.toPath(), fileContent.getBytes());
            return true;
        } else return false;
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 21
Project: csap-core   File: ServiceOsManager.java   Source Code and License 6 votes vote down vote up
public File createVersionFile (
								File versionFile, String version,
								String userid, String description ) {

	String foundTime = LocalDateTime.now().format( DateTimeFormatter.ofPattern( "HH:mm:ss MMM d" ) );
	if ( version == null ) {
		version = LocalDateTime.now().format( DateTimeFormatter.ofPattern( "MMM.d-HH.mm" ) );
	}
	List<String> lines = Arrays.asList(
		"Deployment Notes",
		"<version>" + version + "</version>",
		description + " by: " + userid + " at " + foundTime );

	try {
		Files.write( versionFile.toPath(), lines, Charset.forName( "UTF-8" ) );
	} catch (IOException ex) {
		logger.error( "Failed creating version file", ex );
	}

	return versionFile;
}
 
Example 22
Project: powsybl-core   File: XMLImporterTest.java   Source Code and License 6 votes vote down vote up
private void writeNetwork(String fileName, boolean writeExt) throws IOException {
    try (BufferedWriter writer = Files.newBufferedWriter(fileSystem.getPath(fileName), StandardCharsets.UTF_8)) {
        writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        writer.write("<iidm:network xmlns:iidm=\"http://www.itesla_project.eu/schema/iidm/1_0\" id=\"test\" caseDate=\"2013-01-15T18:45:00.000+01:00\" forecastDistance=\"0\" sourceFormat=\"test\">");
        writer.newLine();
        writer.write("    <iidm:substation id=\"P1\" country=\"FR\"/>");
        writer.newLine();
        if (writeExt) {
            writer.write("    <iidm:extension id=\"P1\">");
            writer.write("    <foo/>");
            writer.write("    </iidm:extension>");
        }
        writer.write("</iidm:network>");
        writer.newLine();
    }
}
 
Example 23
Project: oscm   File: EclipseProjectReader.java   Source Code and License 6 votes vote down vote up
/**
 * Reads the path to the project from the Eclipse' .location meta data file.
 * This file can be found in
 * 'workspace\.metadata\.plugins\org.eclipse.core.resources\.projects\
 * PROJECTNAME\.lo c a t i o n ' .<br />
 * The .location files is written with a special Outpustream and read with
 * an special InputStream implementation. You can find them in the eclipse
 * project org.eclipse.core.resource. The class names are<br />
 * org.eclipse.core.internal.localstore.SafeChunkyInputStream and <br />
 * org.eclipse.core.internal.localstore.SafeChunkyOutputStream.
 * <p>
 * The eclipse implementation which reads the .location file can be found in
 * the same project, the class name is
 * org.eclipse.core.internal.resources.LocalMetaArea, refer to method
 * readPrivateDescription.
 * <p>
 * Basically the first 16 bytes of the .location file are for consistency
 * reason there, the next bytes are the path to the project source. Those
 * bytes must be read via DataInputStream.readUTF.
 */
private String readFromLocationFile(File project) throws IOException {
    String result = "";
    Path location = Paths.get(project.getAbsolutePath())
            .resolve(".location");
    InputStream inputStream = Files.newInputStream(location);
    try (DataInputStream dataStream = new DataInputStream(inputStream);) {
        byte[] begin_chunk = new byte[16];
        dataStream.read(begin_chunk, 0, 16);
        result = dataStream.readUTF();

        String uriPrefix = "URI//file:";
        if (System.getProperty("os.name").startsWith("Windows")) {
            uriPrefix = uriPrefix.concat("/");
        }

        if (result.startsWith(uriPrefix)) {
            result = result.substring(uriPrefix.length());
        }
    }
    return result;
}
 
Example 24
Project: AptSpring   File: TestResourceLoader.java   Source Code and License 6 votes vote down vote up
/**
 * Doesn't appear to work in docker, will never work in windows.
 * @throws IOException if any of the setup fails
 */
@Test
public void testBrokenEnvironment() throws IOException {
  File root = testFolder.newFolder();
  File workingDir = new File(root, FileStore.STANDARD.getPath() + File.separator);
  DefinitionModel model = new DefinitionModel(SIMPLE_MODEL);
  Files.createDirectories(workingDir.toPath(),
      PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(NO_PERMS)));
  if (PosixFilePermissions.fromString(NO_PERMS).equals(Files.getPosixFilePermissions(workingDir.toPath()))) {
    TestFileStore fileStore = new TestFileStore(root);
    assertThatThrownBy(() -> fileStore.store(model)).isInstanceOf(IOException.class)
      .hasMessage("could not write directories for model storage");
    Files.setPosixFilePermissions(workingDir.toPath(), PosixFilePermissions.fromString("rwxrwxrwx"));
  }
  cleanUp(root);
}
 
Example 25
Project: ios-device-control   File: SimulatorDeviceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void installApplication(Path ipaOrAppPath) throws IosDeviceException {
  try {
    if (Files.isDirectory(ipaOrAppPath)) {
      await(simctl.install(ipaOrAppPath.toString()));
    } else {
      Path tmpDir = Files.createTempDirectory("app");
      try {
        unzipFile(ipaOrAppPath, tmpDir);
        Path appPath =
            tmpDir
                .resolve("Payload")
                .resolve(MoreFiles.getNameWithoutExtension(ipaOrAppPath) + ".app");
        await(simctl.install(appPath.toString()));
      } finally {
        MoreFiles.deleteRecursively(tmpDir, RecursiveDeleteOption.ALLOW_INSECURE);
      }
    }
  } catch (IOException e) {
    throw new IosDeviceException(this, e);
  }
}
 
Example 26
Project: incubator-netbeans   File: ApplyDiffPatchAction.java   Source Code and License 6 votes vote down vote up
private static boolean isNetBeansPatch (File patchFile) {
    try (BufferedReader reader = Files.newBufferedReader(patchFile.toPath(), Charset.forName("UTF-8"))) {
        boolean netbeansPatch = false;
        boolean cont = true;
        for (String line = reader.readLine(); line != null && cont; line = reader.readLine()) {
            if (line.trim().isEmpty()) {
                // skip
            } else if (line.startsWith("#")) {
                line = line.substring(1).trim();
                if (line.startsWith(ExportDiffChangesAction.PATCH_FILE_HEADER)) {
                    // line was generated by NB HG diff action
                    netbeansPatch = true;
                    cont = false;
                }
            } else {
                // start of the patch file itself, NB header not found
                cont = false;
            }
        }
        return netbeansPatch;
    } catch (IOException ex) {
        return false;
    }
}
 
Example 27
Project: security-karate   File: CredentialFileParser.java   Source Code and License 6 votes vote down vote up
public Optional<Stream<Credentials>> loadFile(Path filePath){
    if(filePath == null){
        return Optional.empty();
    }

    try{
        bufferedReader = Files.newBufferedReader(filePath);
        return Optional.of(bufferedReader.lines()
                .map(line -> extractCredentials(line, true))
                .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
        );
    } catch (IOException e) {
        logger.error("failed to load credentials from file.",e);
        return Optional.empty();
    }
}
 
Example 28
Project: elasticsearch_my   File: FileUtils.java   Source Code and License 6 votes vote down vote up
private static void collectFiles(final Path dir, final String fileSuffix, final Map<String, Set<Path>> files) throws IOException {
    Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (file.toString().endsWith(fileSuffix)) {
                String groupName = dir.relativize(file.getParent()).toString();
                Set<Path> filesSet = files.get(groupName);
                if (filesSet == null) {
                    filesSet = new HashSet<>();
                    files.put(groupName, filesSet);
                }
                filesSet.add(file);
            }
            return FileVisitResult.CONTINUE;
        }
    });
}
 
Example 29
Project: smarti   File: MongoDbMigrationService.java   Source Code and License 6 votes vote down vote up
public void runDatabaseMigration() throws IOException {
    final ScriptOperations scriptOps = mongoTemplate.scriptOps();

    if (migrationProperties.getScriptHome() != null) {
        try {
            Files.list(migrationProperties.getScriptHome())
                    .filter(s -> migrationProperties.getPattern().matcher(s.getFileName().toString()).find())
                    .sorted(this::compareCaseInsensitive)
                    .forEachOrdered(s -> runDatabaseMigration(s, scriptOps));
        } catch (UncheckedIOException ex) {
            throw ex.getCause();
        }
    } else {
        log.error("smarti.migration.mongo.script-home not set - not running database migration!");
    }
}
 
Example 30
Project: elasticsearch_my   File: MetaDataStateFormat.java   Source Code and License 6 votes vote down vote up
long findMaxStateId(final String prefix, Path... locations) throws IOException {
    long maxId = -1;
    for (Path dataLocation : locations) {
        final Path resolve = dataLocation.resolve(STATE_DIR_NAME);
        if (Files.exists(resolve)) {
            try (DirectoryStream<Path> stream = Files.newDirectoryStream(resolve, prefix + "*")) {
                for (Path stateFile : stream) {
                    final Matcher matcher = stateFilePattern.matcher(stateFile.getFileName().toString());
                    if (matcher.matches()) {
                        final long id = Long.parseLong(matcher.group(1));
                        maxId = Math.max(maxId, id);
                    }
                }
            }
        }
    }
    return maxId;
}
 
Example 31
Project: family-tree-xml-parser   File: ScheduledFileReaderTest.java   Source Code and License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void doNothingWhenPathCannotBeParsed() throws Exception {
  mockStatic(Files.class);

  when(validator.isValid(path)).thenReturn(true);

  DirectoryStream<Path> directoryStream = mock(DirectoryStream.class);
  when(Files.newDirectoryStream(path, "*.xml")).thenReturn(directoryStream);

  Iterator<Path> iterator = mock(Iterator.class);
  when(directoryStream.iterator()).thenReturn(iterator);

  when(iterator.hasNext()).thenReturn(true, false);
  Path file = mock(Path.class);
  when(iterator.next()).thenReturn(file);

  when(xmlParser.parseXml(file)).thenReturn(Optional.empty());

  scheduledFileReader.parseXmlFiles();

  verifyZeroInteractions(service);

  verifyStatic(Files.class);
  Files.newDirectoryStream(path, "*.xml");
}
 
Example 32
Project: openjdk-jdk10   File: DefaultImageBuilder.java   Source Code and License 5 votes vote down vote up
/**
 * chmod ugo-w file
 */
private void setReadOnly(Path file) {
    try {
        Set<PosixFilePermission> perms = Files.getPosixFilePermissions(file);
        perms.remove(PosixFilePermission.OWNER_WRITE);
        perms.remove(PosixFilePermission.GROUP_WRITE);
        perms.remove(PosixFilePermission.OTHERS_WRITE);
        Files.setPosixFilePermissions(file, perms);
    } catch (IOException ioe) {
        throw new UncheckedIOException(ioe);
    }
}
 
Example 33
Project: ats-framework   File: LocalFileSystemOperations.java   Source Code and License 5 votes vote down vote up
/**
 *
 * @param filename the file name
 * @return the file user id
 * @throws FileSystemOperationException
 */
private long getUserId(
                        String filename ) {

    try {
        Integer uid = ( Integer ) Files.getAttribute( new File( filename ).toPath(), "unix:uid",
                                                      LinkOption.NOFOLLOW_LINKS );
        return uid.longValue();

    } catch( Exception e ) {
        throw new FileSystemOperationException( "Could not get UID for '" + filename + "'", e );
    }
}
 
Example 34
Project: openjdk-jdk10   File: CreateSymbolsTestImpl.java   Source Code and License 5 votes vote down vote up
void doTestEquivalence(String code7, String code8, String testClass) throws Exception {
    Path classes = prepareVersionedCTSym(code7, code8);
    Path classfile = classes.resolve("78").resolve(testClass.replace('.', '/') + ".class");

    if (!Files.isReadable(classfile)) {
        throw new AssertionError("Cannot find expected class.");
    }
}
 
Example 35
Project: jdk8u-jdk   File: PaddingTest.java   Source Code and License 5 votes vote down vote up
private static void diff(String fname1, String fname2) throws Exception {
    if (!Arrays.equals(Files.readAllBytes(Paths.get(fname1)),
            Files.readAllBytes(Paths.get(fname2)))) {
        throw new Exception(
                "files " + fname1 + " and " + fname2 + " differ");
    }
}
 
Example 36
Project: marathonv5   File: Copy.java   Source Code and License 5 votes vote down vote up
/**
 * Copy source file to target location.
 *
 * @return
 */
static boolean copyFile(Path source, Path target) {
    CopyOption[] options = new CopyOption[] { COPY_ATTRIBUTES, REPLACE_EXISTING };
    target = getUnique(target);
    try {
        Files.copy(source, target, options);
        return true;
    } catch (Exception x) {
        System.err.format("Unable to copy: %s: %s%n", source, x);
        return false;
    }
}
 
Example 37
Project: uroborosql   File: UroboroSQLTest.java   Source Code and License 5 votes vote down vote up
@Test
public void builderWithSqlAgentFactory() throws Exception {
	SqlConfig config = UroboroSQL.builder("jdbc:h2:mem:SqlAgentTest", "", "")
			.setSqlAgentFactory(new SqlAgentFactoryImpl().setDefaultMapKeyCaseFormat(CaseFormat.CAMEL_CASE))
			.build();
	try (SqlAgent agent = config.agent()) {
		String[] sqls = new String(Files.readAllBytes(Paths.get("src/test/resources/sql/ddl/create_tables.sql")),
				StandardCharsets.UTF_8).split(";");
		for (String sql : sqls) {
			if (StringUtils.isNotBlank(sql)) {
				agent.updateWith(sql.trim()).count();
			}
		}

		insert(agent, Paths.get("src/test/resources/data/setup", "testExecuteQuery.ltsv"));

		agent.query("example/select_product").paramList("product_id", 0, 1)
				.stream().forEach((m) -> {
					assertTrue(m.containsKey("productId"));
					assertTrue(m.containsKey("productName"));
					assertTrue(m.containsKey("productKanaName"));
					assertTrue(m.containsKey("janCode"));
					assertTrue(m.containsKey("productDescription"));
					assertTrue(m.containsKey("insDatetime"));
					assertTrue(m.containsKey("updDatetime"));
					assertTrue(m.containsKey("versionNo"));
				});

		agent.rollback();
	}

	assertEquals(new H2Dialect().getName(), config.getDialect().getName());
}
 
Example 38
Project: write_api_service   File: Publish.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the Output object from the filepath
 *
 * @param filePath The path to the file containing json output from the add command
 * @return The output object
 */
private static Output getJson(String filePath) {
    Output output = null;
    try {
        Path path = Paths.get(filePath);
        String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
        Gson gson = new Gson();
        output = gson.fromJson(content, Output.class);
    } catch (IOException e) {
        ExceptionHelper.errorMessage(LOGGER, "Could not read json file" + e.getMessage(), ExceptionHelper.IO_ERROR);
    }
    return output;
}
 
Example 39
Project: JavaRushTasks   File: Solution.java   Source Code and License 5 votes vote down vote up
public Class<?> load(Path path) {
    try {
        if (path.getFileName().toString().lastIndexOf(".class") == -1)
            return null;

        byte[] b = Files.readAllBytes(path);
        return defineClass(null, b, 0, b.length); //here main magic
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 40
Project: ArchUnit   File: ClassFileSource.java   Source Code and License 5 votes vote down vote up
FromFilePath(Path path, ImportOptions importOptions) {
    this.importOptions = importOptions;
    if (path.toFile().exists()) {
        try {
            Files.walkFileTree(path, this);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example 41
Project: helper   File: GsonStorageHandler.java   Source Code and License 5 votes vote down vote up
@Override
protected T readFromFile(Path path) {
    try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
        return gson.fromJson(reader, type);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 42
Project: openjdk-jdk10   File: OptionModesTester.java   Source Code and License 5 votes vote down vote up
void writeFile(String path, String body) throws IOException {
    Path p = Paths.get(path);
    if (p.getParent() != null)
        Files.createDirectories(p.getParent());
    try (FileWriter w = new FileWriter(path)) {
        w.write(body);
    }
}
 
Example 43
Project: aem-epic-tool   File: PackageOps.java   Source Code and License 5 votes vote down vote up
public static void relocatePackageFile(PackageType pkg, File destination) throws IOException {
    String filename = getPackageFileName(pkg);
    File packageFile = packageFiles.get(filename);
    File target = new File(destination, filename + ".zip");
    if (packageFile != null) {
        String tmpDir = System.getProperty("java.io.tmpdir");
        if (packageFile.getAbsolutePath().contains(tmpDir)) {
            Files.move(packageFile.toPath(), target.toPath(), StandardCopyOption.ATOMIC_MOVE);
            packageFiles.put(filename, target);
        } else {
            Files.copy(packageFile.toPath(), target.toPath(), StandardCopyOption.ATOMIC_MOVE);
        }
    }
}
 
Example 44
Project: openjdk-jdk10   File: JImageGenerator.java   Source Code and License 5 votes vote down vote up
public static Path createNewFile(Path root, String pathName, String extension) {
    Path out = root.resolve(pathName + extension);
    int i = 1;
    while (Files.exists(out)) {
        out = root.resolve(pathName + "-" + (++i) + extension);
    }
    return out;
}
 
Example 45
Project: Dr-Assistant   File: EditPatientController.java   Source Code and License 5 votes vote down vote up
private String copyImage() {
    if (file != null) {
        copyFile = new File(path + "\\Documents\\DrAssistant\\" + n + file.getName());
    } else {
        return patient.getThumbnail();
    }
    System.out.println(copyFile.getPath());
    try {
        Files.copy(Paths.get(file.getPath()), Paths.get(copyFile.getPath()), StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException ex) {
        Logger.getLogger(NewPatientController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return copyFile.getName();

}
 
Example 46
Project: mmm   File: ItemsetMinerRunner.java   Source Code and License 5 votes vote down vote up
private void readDataPoints() throws URISyntaxException, IOException {

        // create structure parser options
        StructureParserOptions structureParserOptions = new StructureParserOptions();
        structureParserOptions.retrieveLigandInformation(true);
        structureParserOptions.omitHydrogens(true);

        logger.info(">>>STEP 1<<< reading data points");
        // input path is resource
        String inputListLocation = itemsetMinerConfiguration.getInputListLocation();

        // decide whether to use directory, chain list, or given IDs
        DataPointReader dataPointReader;
        if (itemsetMinerConfiguration.getInputListLocation() == null) {
            List<Path> structurePaths = Files.list(Paths.get(itemsetMinerConfiguration.getInputDirectoryLocation()))
                                             .filter(path -> path.toFile().isFile())
                                             .collect(Collectors.toList());
            dataPointReader = new DataPointReader(itemsetMinerConfiguration.getDataPointReaderConfiguration(), structurePaths);

        } else {
            Path inputListPath;
            URL inputListResourceURL = Thread.currentThread().getContextClassLoader()
                                             .getResource(inputListLocation);
            if (inputListResourceURL != null) {
                inputListPath = Paths.get(inputListResourceURL.toURI());
                logger.info("found input list in resources");
            } else {
                inputListPath = Paths.get(inputListLocation);
                logger.info("external input list will be used");
            }
            dataPointReader = new DataPointReader(itemsetMinerConfiguration.getDataPointReaderConfiguration(), inputListPath);
        }
        dataPoints = dataPointReader.readDataPoints();
    }
 
Example 47
Project: openjdk-jdk10   File: FaultyFileSystem.java   Source Code and License 5 votes vote down vote up
@Override
public void checkAccess(Path file, AccessMode... modes)
    throws IOException
{
    triggerEx(file, "checkAccess");
    // hack
    if (modes.length == 0) {
        if (Files.exists(unwrap(file)))
            return;
        else
            throw new NoSuchFileException(file.toString());
    }
    throw new RuntimeException("not implemented yet");
}
 
Example 48
Project: litiengine   File: FileUtilities.java   Source Code and License 5 votes vote down vote up
public static List<String> findFilesByExtension(final List<String> fileNames, final Path dir, final String extension) {
  try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
    for (final Path path : stream) {
      if (path.toFile().isDirectory()) {
        if (isBlackListedDirectory(path)) {
          continue;
        }

        findFilesByExtension(fileNames, path, extension);
      } else if (path.toAbsolutePath().toString().endsWith(extension)) {
        fileNames.add(path.toAbsolutePath().toString());
      }
    }
  } catch (final IOException e) {
    log.log(Level.SEVERE, e.getMessage(), e);
  }

  return fileNames;
}
 
Example 49
Project: openjdk-jdk10   File: Helper.java   Source Code and License 5 votes vote down vote up
private void generateGarbage(Path compiled) throws IOException {
    Path metaInf = compiled.resolve("META-INF").resolve("services");
    Files.createDirectories(metaInf);
    Path provider = metaInf.resolve("MyProvider");
    Files.createFile(provider);
    Files.createFile(compiled.resolve("toto.jcov"));
}
 
Example 50
Project: jdk8u-jdk   File: FaultyFileSystem.java   Source Code and License 5 votes vote down vote up
@Override
public SeekableByteChannel newByteChannel(Path file,
                                          Set<? extends OpenOption> options,
                                          FileAttribute<?>... attrs)
    throws IOException
{
    triggerEx(file, "newByteChannel");
    return Files.newByteChannel(unwrap(file), options, attrs);
}
 
Example 51
Project: goobi-viewer-indexer   File: Utils.java   Source Code and License 5 votes vote down vote up
/**
 * Creates the file Path to the updated anchor file
 * 
 * @param destFolderPath
 * @param baseName
 * @param extension
 * @return
 * @should construct path correctly and avoid collisions
 */
public static Path getCollisionFreeDataFilePath(String destFolderPath, String baseName, String separator, String extension) {
    if (destFolderPath == null) {
        throw new IllegalArgumentException("destFolderPath may not be null");
    }
    if (baseName == null) {
        throw new IllegalArgumentException("pi may not be null");
    }
    if (extension == null) {
        throw new IllegalArgumentException("extension may not be null");
    }

    StringBuilder sbFilePath = new StringBuilder(baseName);
    Path path = Paths.get(destFolderPath, baseName + extension);
    if (Files.exists(path)) {
        // If an updated anchor file already exists, use a different file name
        int iteration = 0;
        while (Files.exists(path = Paths.get(destFolderPath, baseName + "#" + iteration + extension))) {
            iteration++;
        }
        if (StringUtils.isNotEmpty(separator)) {
            sbFilePath.append(separator);
        }
        sbFilePath.append(iteration).append(extension);
        path = Paths.get(destFolderPath, sbFilePath.toString());
    }

    return path;
}
 
Example 52
Project: SoftUni   File: Tester.java   Source Code and License 5 votes vote down vote up
private void printOutput(String mismatchPath, boolean isMismatch) throws IOException {
    if(isMismatch){
        List<String> mismatchStrings = Files.readAllLines(Paths.get(mismatchPath));
        mismatchStrings.forEach(OutputWriter::writeMessageOnNewLine);
        return;
    }

    OutputWriter.writeMessageOnNewLine("Files are identical. There are no mismatches.");
}
 
Example 53
Project: twister2   File: FileUtils.java   Source Code and License 5 votes vote down vote up
public static byte[] readFromFile(String filename) {
  Path path = new File(filename).toPath();
  byte[] res;
  try {
    res = Files.readAllBytes(path);
  } catch (IOException e) {
    LOG.log(Level.SEVERE, "Failed to read from file. ", e);
    res = new byte[0];
  }

  return res;
}
 
Example 54
Project: joanne   File: XMLManager.java   Source Code and License 5 votes vote down vote up
private Properties getFoldersList() throws FileNotFoundException, IOException{
    Properties p = new Properties();
            
        if(Files.exists(new File(PATH).toPath())){
            FileInputStream in = new FileInputStream(new File(PATH));
            p.loadFromXML(in);
            BiConsumer<Object,Object> bi = (x,y) ->{
                p.getProperty(x.toString(), new File(y.toString()).getName());
            };
            p.forEach(bi);

        }
        return p;
}
 
Example 55
Project: monarch   File: MTableDUnitConfigFramework.java   Source Code and License 5 votes vote down vote up
private void truncateStoreFiles(String storeName) {
  try {
    Stream<Path> list = Files.list(new File(".").toPath());
    Object[] paths = list.toArray();
    for (Object path : paths) {
      if (path.toString().contains(storeName)) {
        Files.write((Path) path, new byte[0], StandardOpenOption.TRUNCATE_EXISTING);
      }
    }
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example 56
Project: openjdk-jdk10   File: CompilerUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Compile all the java sources in {@code <source>/**} to
 * {@code <destination>/**}. The destination directory will be created if
 * it doesn't exist.
 *
 * All warnings/errors emitted by the compiler are output to System.out/err.
 *
 * @return true if the compilation is successful
 *
 * @throws IOException
 *         if there is an I/O error scanning the source tree or
 *         creating the destination directory
 * @throws UnsupportedOperationException
 *         if there is no system java compiler
 */
public static boolean compile(Path source, Path destination, String... options)
    throws IOException
{
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        // no compiler available
        throw new UnsupportedOperationException("Unable to get system java compiler. "
                + "Perhaps, jdk.compiler module is not available.");
    }
    StandardJavaFileManager jfm = compiler.getStandardFileManager(null, null, null);

    List<Path> sources
        = Files.find(source, Integer.MAX_VALUE,
            (file, attrs) -> (file.toString().endsWith(".java")))
            .collect(Collectors.toList());

    Files.createDirectories(destination);
    jfm.setLocation(StandardLocation.CLASS_PATH, Collections.emptyList());
    jfm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT,
            Collections.singletonList(destination));

    List<String> opts = Arrays.asList(options);
    JavaCompiler.CompilationTask task
        = compiler.getTask(null, jfm, null, opts, null,
            jfm.getJavaFileObjectsFromPaths(sources));

    return task.call();
}
 
Example 57
Project: StegoProxy   File: Config.java   Source Code and License 5 votes vote down vote up
/**
 * Creates new config from specified path
 * @param conf - path to .conf file
 * @throws IOException on reading failure
 */
public Config(Path conf) throws IOException {
    String[] lines = new String(Files.readAllBytes(conf)).split("\n");
    for (String line : lines) {
        if (line.length() == 0 || line.charAt(0) == '#')
            continue;

        String[] tokens = line.replaceAll(" +", " ").split(" ");
        options.put(tokens[0], tokens[1]);
    }
}
 
Example 58
Project: elasticsearch_my   File: InstallPluginCommand.java   Source Code and License 5 votes vote down vote up
/** Downloads a zip from the url, into a temp file under the given temp dir. */
@SuppressForbidden(reason = "We use getInputStream to download plugins")
private Path downloadZip(Terminal terminal, String urlString, Path tmpDir) throws IOException {
    terminal.println(VERBOSE, "Retrieving zip from " + urlString);
    URL url = new URL(urlString);
    Path zip = Files.createTempFile(tmpDir, null, ".zip");
    URLConnection urlConnection = url.openConnection();
    urlConnection.addRequestProperty("User-Agent", "elasticsearch-plugin-installer");
    int contentLength = urlConnection.getContentLength();
    try (InputStream in = new TerminalProgressInputStream(urlConnection.getInputStream(), contentLength, terminal)) {
        // must overwrite since creating the temp file above actually created the file
        Files.copy(in, zip, StandardCopyOption.REPLACE_EXISTING);
    }
    return zip;
}
 
Example 59
Project: openjdk-jdk10   File: CodeStoreAndPathTest.java   Source Code and License 5 votes vote down vote up
@Test
public void codeCacheTestOpt() throws ScriptException, IOException {
    System.setProperty("nashorn.persistent.code.cache", codeCache);
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    final ScriptEngine e = fac.getScriptEngine(ENGINE_OPTIONS_OPT);
    final Path codeCachePath = getCodeCachePath(true);
    e.eval(code1);
    e.eval(code2);
    e.eval(code3);// less than minimum size for storing
    // adding code1 and code2.
    final DirectoryStream<Path> stream = Files.newDirectoryStream(codeCachePath);
    checkCompiledScripts(stream, 4);
}
 
Example 60
Project: cyberduck   File: LocalCopyFeature.java   Source Code and License 5 votes vote down vote up
@Override
public Path copy(final Path source, final Path target, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
    try {
        Files.copy(session.toPath(source), session.toPath(target), StandardCopyOption.REPLACE_EXISTING);
        // Copy attributes from original file
        return new Path(target.getParent(), target.getName(), target.getType(),
                new LocalAttributesFinderFeature(session).find(target));
    }
    catch(IOException e) {
        throw new LocalExceptionMappingService().map("Cannot copy {0}", e, source);
    }
}