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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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);
        }
    }
}