Java Code Examples for java.nio.file.Paths

The following are top voted examples for showing how to use java.nio.file.Paths. 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: RDF2PT   File: DefaultIRIConverterPortuguese.java   Source Code and License 7 votes vote down vote up
public DefaultIRIConverterPortuguese(QueryExecutionFactory qef, String cacheDirectory) {
	this.qef = qef;

	// use tmp as default cache directory
	if (cacheDirectory == null) {
		cacheDirectory = System.getProperty("java.io.tmpdir") + "/triple2nl/cache/portuguese";
	}

	cacheDirectory += "/dereferenced";
	try {
		Files.createDirectories(Paths.get(cacheDirectory));
	} catch (IOException e) {
		logger.error("Creation of folder + " + cacheDirectory + " failed.", e);
	}
	logger.debug("Using folder " + cacheDirectory + " as cache for IRI converter.");

	uriDereferencer = new URIDereferencer(new File(cacheDirectory));
}
 
Example 2
Project: flow-platform   File: LogEventHandler.java   Source Code and License 6 votes vote down vote up
private void initZipLogFile(final Cmd cmd) throws IOException {
    // init log directory
    try {
        Files.createDirectories(DEFAULT_LOG_PATH);
    } catch (FileAlreadyExistsException ignore) {
        LOGGER.warn("Log path %s already exist", DEFAULT_LOG_PATH);
    }

    // init zipped log file for tmp
    Path stdoutPath = Paths.get(DEFAULT_LOG_PATH.toString(), getLogFileName(cmd, Log.Type.STDOUT, true));
    Files.deleteIfExists(stdoutPath);

    stdoutLogPath = Files.createFile(stdoutPath);

    // init zip stream for stdout log
    stdoutLogStream = new FileOutputStream(stdoutLogPath.toFile());
    stdoutLogZipStream = new ZipOutputStream(stdoutLogStream);
    ZipEntry outEntry = new ZipEntry(cmd.getId() + ".out");
    stdoutLogZipStream.putNextEntry(outEntry);
}
 
Example 3
Project: openjdk-jdk10   File: CLICompatibility.java   Source Code and License 6 votes vote down vote up
@Test
public void extractReadFromStdin() throws IOException {
    Path path = Paths.get("extract");
    Path jarPath = path.resolve("extractReadFromStdin.jar"); // for extracting
    createJar(jarPath, RES1);

    for (String opts : new String[]{"x" ,"-x", "--extract"}) {
        if (legacyOnly && opts.startsWith("--"))
            continue;

        jarWithStdinAndWorkingDir(jarPath.toFile(), path.toFile(), opts)
            .assertSuccess()
            .resultChecker(r ->
                assertTrue(Files.exists(path.resolve(RES1)),
                           "Expected to find:" + path.resolve(RES1))
            );
        FileUtils.deleteFileIfExistsWithRetry(path.resolve(RES1));
    }
    FileUtils.deleteFileTreeWithRetry(path);
}
 
Example 4
Project: MantaroRPG   File: SimpleFileDataManager.java   Source Code and License 6 votes vote down vote up
@SneakyThrows
public SimpleFileDataManager(String file) {
	this.path = Paths.get(file);
	if (!this.path.toFile().exists()) {
		log.info("Could not find config file at " + this.path.toFile().getAbsolutePath() + ", creating a new one...");
		if (this.path.toFile().createNewFile()) {
			log.info("Generated new config file at " + this.path.toFile().getAbsolutePath() + ".");
			FileIOUtils.write(this.path, this.data.stream().collect(Collectors.joining()));
			log.info("Please, fill the file with valid properties.");
		} else {
			log.warn("Could not create config file at " + file);
		}
	}

	Collections.addAll(data, NEWLINE_PATTERN.split(FileIOUtils.read(this.path)));
	data.removeIf(s -> s.startsWith("//"));
}
 
Example 5
Project: jpeek   File: ResultsTest.java   Source Code and License 6 votes vote down vote up
@Test
public void acceptsAndRenders() throws Exception {
    final Path output = Files.createTempDirectory("").resolve("x2");
    final Path input = Paths.get(".");
    new App(input, output).analyze();
    final Results results = new Results();
    results.add("org.takes:takes", output);
    MatcherAssert.assertThat(
        XhtmlMatchers.xhtml(
            new Xembler(
                new Directives().add("repos").append(
                    new Joined<Directive>(results.recent())
                )
            ).xmlQuietly()
        ),
        XhtmlMatchers.hasXPath("/repos")
    );
}
 
Example 6
Project: IO   File: AdvancedOptions.java   Source Code and License 6 votes vote down vote up
/**
    * Saves these options to disk, with the given file name.
    * @param name The name to save as.
    * @return True if the save was successful, false if there was an error.
    */
public boolean saveConfig(String name) {
    File saveFile = Paths.get(BASE_CONFIG_STRING + name).toFile();
    saveFile.getParentFile().mkdirs();
	try {
	    saveFile.createNewFile();
	    FileOutputStream writeTo = new FileOutputStream(saveFile);
		this.store(writeTo, "");
		writeTo.close();
		return true;
	} catch (IOException e) {
		Logging.log(ERROR_SAVING_MSG, LogMessageType.ERROR);
		Logging.log(e);
	}
	return false;

}
 
Example 7
Project: openjdk-jdk10   File: FailOverDirectExecutionControlTest.java   Source Code and License 6 votes vote down vote up
@BeforeMethod
@Override
public void setUp() {
    Logger logger = Logger.getLogger("jdk.jshell.execution");
    logger.setLevel(Level.ALL);
    hndlr = new LogTestHandler();
    logger.addHandler(hndlr);
    logged = new HashMap<>();
    Compiler compiler = new Compiler();
    Path modDir = Paths.get("mod");
    compiler.compile(modDir,
            "package my.provide; import java.util.Map;\n" +
            "import jdk.jshell.spi.ExecutionControl;\n" +
            "import jdk.jshell.spi.ExecutionControlProvider;\n" +
            "import jdk.jshell.spi.ExecutionEnv;\n" +
            "public class AlwaysFailingProvider implements ExecutionControlProvider {\n" +
            "    @Override\n" +
            "    public String name() {\n" +
            "        return \"alwaysFailing\";\n" +
            "    }\n" +
            "    @Override\n" +
            "    public ExecutionControl generate(ExecutionEnv env, Map<String, String> parameters) throws Throwable {\n" +
            "        throw new UnsupportedOperationException(\"This operation intentionally broken.\");\n" +
            "    }\n" +
            "}\n",
            "module my.provide {\n" +
            "    requires transitive jdk.jshell;\n" +
            "    provides jdk.jshell.spi.ExecutionControlProvider\n" +
            "        with my.provide.AlwaysFailingProvider;\n" +
            " }");
    Path modPath = compiler.getPath(modDir);
    ccl = createAndRunFromModule("my.provide", modPath);

    provider = new FailOverExecutionControlProvider();
    Map<String, String> pm = provider.defaultParameters();
    pm.put("0", "alwaysFailing");
    pm.put("1", "alwaysFailing");
    pm.put("2", "jdi");
    setUp(builder -> builder.executionEngine(provider, pm));
}
 
Example 8
Project: rebazer   File: BitbucketServiceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void getAllPullRequests_should_return_all_pull_requests_as_list() throws Exception {
	final Repository repo = mock( Repository.class );
	final String json = new String( Files.readAllBytes(
			Paths.get( "src/test/resources/org/retest/rebazer/service/bitbucketservicetest/response.json" ) ) );
	final DocumentContext documentContext = JsonPath.parse( json );
	when( config.getTeam() ).thenReturn( "test_team" );
	when( repo.getName() ).thenReturn( "test_repo_name" );
	when( bitbucketTemplate.getForObject( anyString(), eq( String.class ) ) ).thenReturn( json );

	final int expectedId = (int) documentContext.read( "$.values[0].id" );
	final String expectedUrl =
			"/repositories/" + config.getTeam() + "/" + repo.getName() + "/pullrequests/" + expectedId;
	final List<PullRequest> expected = Arrays.asList( PullRequest.builder().id( expectedId ).repo( repo.getName() )
			.source( documentContext.read( "$.values[0].source.branch.name" ) )
			.destination( documentContext.read( "$.values[0].destination.branch.name" ) ).url( expectedUrl )
			.lastUpdate( documentContext.read( "$.values[0].updated_on" ) ).build() );
	final List<PullRequest> actual = cut.getAllPullRequests( repo );

	assertThat( actual ).isEqualTo( expected );
}
 
Example 9
Project: web3j-maven-plugin   File: IssueITest.java   Source Code and License 6 votes vote down vote up
@Test
@Ignore("works with solc version > 0.4.18")
public void issue9_library() throws Exception {
    File pom = new File(resources.getBasedir("issue"), "issue9.pom.xml");
    assertNotNull(pom);
    assertTrue(pom.exists());

    JavaClassGeneratorMojo mojo = (JavaClassGeneratorMojo) mojoRule.lookupMojo("generate-sources", pom);
    assertNotNull(mojo);

    mojo.sourceDestination = testFolder.getRoot().getPath();
    mojo.execute();

    Path path = Paths.get(mojo.sourceDestination);

    List<Path> files = Files.find(path, 99, (p, bfa) -> bfa.isRegularFile()).collect(Collectors.toList());
    assertThat("ConvertLib is created", files.size(), is(1));
    assertThat(files.get(0).getFileName().toString(), is("ConvertLib.java"));
}
 
Example 10
Project: Java-9-Programming-Blueprints   File: FileFinder.java   Source Code and License 6 votes vote down vote up
private void calculateHash(FileInfo file) {
    try {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA3-256");
        messageDigest.update(Files.readAllBytes(Paths.get(file.getPath())));
        ByteArrayInputStream inputStream = new ByteArrayInputStream(messageDigest.digest());
        String hash = IntStream.generate(inputStream::read)
                .limit(inputStream.available())
                .mapToObj(i -> Integer.toHexString(i))
                .map(s -> ("00" + s).substring(s.length()))
                .collect(Collectors.joining());
        file.setHash(hash);
    } catch (NoSuchAlgorithmException | IOException ex) {
        // This algorithm is guaranteed to be there by the JDK, so we'll
        // wrap the checked exception in an unchecked exception so that we
        // don't have to expose it to consuming classes. This *should* never
        // actually run, but it's probably best to be cautious here.
        throw new RuntimeException(ex);
    }
}
 
Example 11
Project: litiengine   File: EditorScreen.java   Source Code and License 6 votes vote down vote up
private void loadCustomEmitters(String projectPath) {
  for (String xmlFile : FileUtilities.findFilesByExtension(new ArrayList<>(), Paths.get(projectPath), "xml")) {
    boolean isEmitter = false;
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    try {
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(xmlFile);
      doc.getDocumentElement().normalize();
      if (doc.getDocumentElement().getNodeName().equalsIgnoreCase("emitter")) {
        isEmitter = true;
      }
    } catch (SAXException | IOException | ParserConfigurationException e) {
      log.log(Level.SEVERE, e.getLocalizedMessage(), e);
    }

    if (isEmitter) {
      CustomEmitter.load(xmlFile);
    }
  }
}
 
Example 12
Project: openjdk-jdk10   File: WrongLNTForLambdaTest.java   Source Code and License 6 votes vote down vote up
void run() throws Exception {
    compileTestClass();
    checkClassFile(new File(Paths.get(System.getProperty("user.dir"),
            "Foo.class").toUri()), "lambda$bar$0", simpleLambdaExpectedLNT);
    checkClassFile(new File(Paths.get(System.getProperty("user.dir"),
            "Foo.class").toUri()), "lambda$variablesInLambdas$1", lambdaWithVarsExpectedLNT);
    checkClassFile(new File(Paths.get(System.getProperty("user.dir"),
            "Foo$1FooBar.class").toUri()), "run", insideLambdaWithVarsExpectedLNT);
    checkClassFile(new File(Paths.get(System.getProperty("user.dir"),
            "Foo.class").toUri()), "lambda$variablesInLambdas$2", lambdaVoid2VoidExpectedLNT);
    checkClassFile(new File(Paths.get(System.getProperty("user.dir"),
            "Foo.class").toUri()), "$deserializeLambda$", deserializeExpectedLNT);
    checkClassFile(new File(Paths.get(System.getProperty("user.dir"),
            "Foo.class").toUri()), "lambda$variablesInLambdas$3", lambdaBridgeExpectedLNT);
    checkClassFile(new File(Paths.get(System.getProperty("user.dir"),
            "Foo.class").toUri()), "assignLambda", assignmentExpectedLNT);
    checkClassFile(new File(Paths.get(System.getProperty("user.dir"),
            "Foo.class").toUri()), "callLambda", callExpectedLNT);
}
 
Example 13
Project: uroborosql   File: AuditLogSqlFilterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testExecuteQueryFilter() throws Exception {
	cleanInsert(Paths.get("src/test/resources/data/setup", "testExecuteQuery.ltsv"));

	List<String> log = TestAppender.getLogbackLogs(() -> {
		SqlContext ctx = agent.contextFrom("example/select_product")
				.paramList("product_id", new BigDecimal("0"), new BigDecimal("2"))
				.param("_userName", "testUserName").param("_funcId", "testFunction").setSqlId("111");
		ctx.setResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE);

		agent.query(ctx);
	});

	assertThat(log, is(Files.readAllLines(
			Paths.get("src/test/resources/data/expected/AuditLogSqlFilter", "testExecuteQueryFilter.txt"),
			StandardCharsets.UTF_8)));
}
 
Example 14
Project: APCSAB   File: AreaFill_shell.java   Source Code and License 6 votes vote down vote up
public static char[][] read(String filename) {
    try {
        // Read contents of the file.
        return Files.readAllLines(Paths.get(filename))
                // Convert to a stream without first line
                // Because we don't need row and col count
                .stream().skip(1)
                // Filter out empty lines.
                .filter(line -> line.length() > 0)
                // Transform each string to array of chars.
                .map(String::toCharArray)
                // Collect the arrays into a 2D array.
                .toArray(char[][]::new);
    } catch (Exception e) {
        // Handle file not found, etc.
        return null;
    }
}
 
Example 15
Project: displaydirect   File: PlanningLoader.java   Source Code and License 6 votes vote down vote up
public void loadFiles(boolean today) {
    // This seems backwards, but at 01:00, we want to download today (starting at 04:00)
    interestingDates = Arrays.asList(LocalDate.now(), LocalDate.now().plusDays(1));

    Log.send(LogCode.PLANNING_STARTED_LOADING, "Started loading");
    LOGGER.info("Starting to load calendar files");
    handleFiles(Paths.get(Configuration.getKv7CalendarPath()), this::getCalendar);
    LOGGER.info("Starting to load planning files");
    handleFiles(Paths.get(Configuration.getKv7PlanningPath()), this::getPlanning);
    QuayDataProvider.replace(planningRecords);

    LineProvider.backup();
    DestinationProvider.backup();
    TimingPointProvider.backup();

    Log.send(LogCode.PLANNING_LOADED, String.format("Loaded %s records for %s and %s", planningRecords.size(), interestingDates.get(0).toString(),
            interestingDates.get(1).toString()));
}
 
Example 16
Project: openjdk-jdk10   File: CLICompatibility.java   Source Code and License 6 votes vote down vote up
@Test
public void updateReadStdinWriteStdout() throws IOException {
    Path path = Paths.get("updateReadStdinWriteStdout.jar");

    for (String opts : new String[]{"u", "-u", "--update"}) {
        if (legacyOnly && opts.startsWith("--"))
            continue;

        createJar(path, RES1);
        jarWithStdin(path.toFile(), opts, RES2)
            .assertSuccess()
            .resultChecker(r -> {
                ASSERT_CONTAINS_RES1.accept(r.stdoutAsStream());
                ASSERT_CONTAINS_RES2.accept(r.stdoutAsStream());
                ASSERT_CONTAINS_MAINFEST.accept(r.stdoutAsStream());
            });
    }
    FileUtils.deleteFileIfExistsWithRetry(path);
}
 
Example 17
Project: web3j-maven-plugin   File: JavaClassGeneratorITest.java   Source Code and License 6 votes vote down vote up
@Test
public void pomStandard() throws Exception {
    File pom = new File(resources.getBasedir("valid"), "pom.xml");
    assertNotNull(pom);
    assertTrue(pom.exists());

    JavaClassGeneratorMojo mojo = (JavaClassGeneratorMojo) mojoRule.lookupMojo("generate-sources", pom);
    assertNotNull(mojo);

    mojo.sourceDestination = testFolder.getRoot().getPath();
    mojo.execute();

    Path path = Paths.get(mojo.sourceDestination);

    List<Path> files = Files.find(path, 99, (p, bfa) -> bfa.isRegularFile()).collect(Collectors.toList());
    assertEquals("Greeter and Mortal Class", 2l, files.size());
}
 
Example 18
Project: pdf-converter   File: ZipCreator.java   Source Code and License 6 votes vote down vote up
private static void pack(String sourceDirPath, String zipFilePath) throws IOException {
        Path p = Files.createFile(Paths.get(zipFilePath));
        try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(p))) {
            Path pp = Paths.get(sourceDirPath);
            Files.walk(pp)
                    .filter(path -> !Files.isDirectory(path))
                    .forEach(path -> {
                        ZipEntry zipEntry = new ZipEntry(pp.relativize(path).toString());
                        try {
                            zs.putNextEntry(zipEntry);
                            zs.write(Files.readAllBytes(path));
                            zs.closeEntry();
                        } catch (Exception e) {
//                            log.warn("Failed to create zip file", e);
                        }
                    });
        }
    }
 
Example 19
Project: smart-testing   File: ClassDependenciesGraphTest.java   Source Code and License 6 votes vote down vote up
@Test
public void should_detect_tests_by_change_of_watched_file() {
    // given
    final Configuration configuration = ConfigurationLoader.load(CURRENT_DIR);
    configuration.loadStrategyConfigurations(AFFECTED);

    final ClassDependenciesGraph
        classDependenciesGraph = new ClassDependenciesGraph(new EndingWithTestTestVerifier(), configuration, new File(".").getAbsoluteFile());

    final String testLocation = getClassLocation(XTest.class);
    final String testLocaion2 = getClassLocation(YTest.class);
    classDependenciesGraph.buildTestDependencyGraph(Arrays.asList(new File(testLocation), new File(testLocaion2)));

    // when
    Set<File> mainObjectsChanged = new HashSet<>();
    final File changedFile =
        Paths.get(new File(".").getAbsolutePath(), "src/main/resources/META-INF/persistence.xml").normalize().toFile();
    mainObjectsChanged.add(changedFile);

    final Set<String> testsDependingOn = classDependenciesGraph.findTestsDependingOn(toChange(mainObjectsChanged));

    // then
    assertThat(testsDependingOn)
        .containsExactly("org.arquillian.smart.testing.strategies.affected.fakeproject.test.XTest");
}
 
Example 20
Project: openjdk-jdk10   File: GraalDebugHandlersFactoryTest.java   Source Code and License 6 votes vote down vote up
@Test
public void createUniqueTest() throws Exception {
    Field maxFileNameLengthField = GraalDebugHandlersFactory.class.getDeclaredField("MAX_FILE_NAME_LENGTH");
    maxFileNameLengthField.setAccessible(true);
    int maxFileNameLength = maxFileNameLengthField.getInt(null);
    Method createUniqueMethod = GraalDebugHandlersFactory.class.getDeclaredMethod("createUnique", Path.class, String.class, String.class, String.class, boolean.class);
    createUniqueMethod.setAccessible(true);
    Path tmpDir = Files.createTempDirectory(Paths.get("."), "createUniqueTest");
    try {
        for (boolean createDirectory : new boolean[]{true, false}) {
            for (String ext : new String[]{"", ".bgv", ".graph-strings"}) {
                for (int i = 0; i < maxFileNameLength + 5; i++) {
                    String id = new String(new char[i]).replace('\0', 'i');
                    String label = "";
                    createUniqueMethod.invoke(null, tmpDir, id, label, ext, createDirectory);

                    id = "";
                    label = new String(new char[i]).replace('\0', 'l');
                    createUniqueMethod.invoke(null, tmpDir, id, label, ext, createDirectory);
                }
            }
        }
    } finally {
        deleteTree(tmpDir);
    }
}
 
Example 21
Project: TechComparisonProject   File: Server.java   Source Code and License 6 votes vote down vote up
/**
 * Obtains the persistent log stored in the clinet_log.dat file and displays it in the GUI.
 */
private static void dispLog ()
{
	Path path = Paths.get( "client_log.dat" );
	
	if ( Files.exists( path ) )
	{
		try ( BufferedReader in = Files.newBufferedReader( path ) )
		{
			String logLine;
			
			while ( ( logLine = in.readLine() ) != null )
			{
				ServerGUI.getTextArea().append( logLine + System.lineSeparator() );
			}
		}
		catch ( IOException e )
		{
			System.out.println( e.getMessage() );
		}
	}
}
 
Example 22
Project: jdk8u-jdk   File: FinalizeOverride.java   Source Code and License 6 votes vote down vote up
static void patchPrivateFinalize() throws IOException {
    // patch the private f_nal_ze method name to "finalize"
    String testClasses = System.getProperty("test.classes", ".");
    Path p = Paths.get(testClasses, "FinalizeOverride$PrivateFinalize.class");
    byte[] bytes = Files.readAllBytes(p);
    int len = "f_nal_ze".length();
    for (int i=0; i < bytes.length-len; i++) {
        if (bytes[i] == 'f' &&
            bytes[i+1] == '_' &&
            bytes[i+2] == 'n' &&
            bytes[i+3] == 'a' &&
            bytes[i+4] == 'l' &&
            bytes[i+5] == '_' &&
            bytes[i+6] == 'z' &&
            bytes[i+7] == 'e')
        {
            // s%_%i%
            bytes[i+1] = 'i';
            bytes[i+5] = 'i';
            break;
        }
    }
    Files.write(p, bytes);
}
 
Example 23
Project: openjdk-jdk10   File: Correctness.java   Source Code and License 6 votes vote down vote up
static void contains0(String s1, String s2, int expected) throws Exception {
    Path p1 = Paths.get(s1);
    Path p2 = Paths.get(s2);
    int d = (int)containsMethod.invoke(null, p1, p2);
    Path p;
    try {
        p = p2.relativize(p1);
    } catch (Exception e) {
        p = null;
    }
    System.out.printf("%-20s -> %-20s: %20s %5d %5d %s\n", s1, s2, p,
            d, expected, d==expected?"":" WRONG");
    if (d != expected) {
        err = true;
    }
}
 
Example 24
Project: openjdk-jdk10   File: GetResourceAsStream.java   Source Code and License 6 votes vote down vote up
/**
 * Prepare jars files for the tests
 */
private static void setup () throws IOException {
    Path classes = Paths.get(WORK_DIR);
    Path testSrc = Paths.get(System.getProperty("test.src"),
            "test1", "com", "foo", "TestClass.java");
    Path targetDir = classes.resolve("test3");
    Path testTarget = targetDir.resolve("TestClass.java");
    Files.createDirectories(targetDir);
    Files.copy(testSrc, testTarget, StandardCopyOption.REPLACE_EXISTING);
    // Compile sources for corresponding test
    CompilerUtils.compile(targetDir, targetDir);
    // Prepare txt files
    Files.write(targetDir.resolve("hello.txt"), "Hello world".getBytes(),
                StandardOpenOption.CREATE);
    Files.write(targetDir.resolve("bye.txt"), "Bye world".getBytes(),
                StandardOpenOption.CREATE);
    // Create jar
    JarUtils.createJarFile(classes.resolve("foo.jar"), targetDir);
}
 
Example 25
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 26
Project: RollenspielAlexaSkill   File: SimpleDBConnectionFactory.java   Source Code and License 6 votes vote down vote up
public static Properties getFileProps(String dbname) {
	String prefix = ((dbname==null)||dbname.isEmpty()) ? "" : (dbname+"-");
	Properties result = new Properties();
	String configFile = System.getProperty(dbname+"-conf", "/etc/"+prefix+"db.properties");
	File dbPropsFile = Paths.get(configFile).toFile().getAbsoluteFile();
	if (!dbPropsFile.exists()) {
		logger.info("PROPS FILE '"+dbPropsFile.getAbsolutePath()+"' NOT FOUND FOR DB WITH NAME '"+dbname+"'.");
		return null;
	}
	logger.info("using '"+dbPropsFile.getAbsolutePath()+"' for db "+dbname+".");
	try {
		result.load(new FileInputStream(dbPropsFile));
	} catch (IOException e) {
		throw new RuntimeException("could not read db properties for "+dbname+" from "+dbPropsFile.getAbsolutePath());
	}
	return result;
}
 
Example 27
Project: CloudNet   File: MasterTemplateLoader.java   Source Code and License 6 votes vote down vote up
public MasterTemplateLoader load()
{
    try
    {
        HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setRequestProperty("-Xcloudnet-user", simpledUser.getUserName());
        urlConnection.setRequestProperty("-Xcloudnet-token", simpledUser.getApiToken());
        urlConnection.setRequestProperty("-Xmessage", customName != null ? "custom" : "template");
        urlConnection.setRequestProperty("-Xvalue",customName != null ? customName : new Document("template", template.getName()).append("group", group).convertToJsonString());
        urlConnection.setUseCaches(false);
        urlConnection.connect();

        if(urlConnection.getHeaderField("-Xresponse") == null)
        {
            Files.copy(urlConnection.getInputStream(), Paths.get(dest));
        }
        urlConnection.disconnect();
    } catch (IOException e)
    {
        e.printStackTrace();
    }
    return this;
}
 
Example 28
Project: S3Mock   File: FileStoreTest.java   Source Code and License 5 votes vote down vote up
@Test
public void copyPart() throws Exception {

  final String sourceFile = UUID.randomUUID().toString();
  final String uploadId = UUID.randomUUID().toString();

  final String targetFile = UUID.randomUUID().toString();
  final String partNumber = "1";

  final byte[] contentBytes = UUID.randomUUID().toString().getBytes();
  fileStore.putS3Object(TEST_BUCKET_NAME, sourceFile, DEFAULT_CONTENT_TYPE,
      new ByteArrayInputStream(contentBytes), false);

  fileStore.prepareMultipartUpload(TEST_BUCKET_NAME, targetFile, DEFAULT_CONTENT_TYPE, uploadId,
      TEST_OWNER, TEST_OWNER);

  fileStore.copyPart(
      TEST_BUCKET_NAME, sourceFile, 0, contentBytes.length, false, partNumber,
      TEST_BUCKET_NAME, targetFile, uploadId);

  assertThat("Part does not exist!",
      Paths.get(rootFolder.getAbsolutePath(), TEST_BUCKET_NAME, targetFile, uploadId,
          partNumber + ".part")
          .toFile()
          .exists(),
      is(true));
}
 
Example 29
Project: openjdk-jdk10   File: AnnotatedExtendsTest.java   Source Code and License 5 votes vote down vote up
public static strictfp void main(String args[]) throws Exception {
    ToolBox tb = new ToolBox();
    Path classPath = Paths.get(ToolBox.testClasses, "AnnotatedExtendsTest$Inner.class");
    String javapOut = new JavapTask(tb)
            .options("-v", "-p")
            .classes(classPath.toString())
            .run()
            .getOutput(Task.OutputKind.DIRECT);
    if (!javapOut.contains("0: #21(): CLASS_EXTENDS, type_index=65535"))
        throw new AssertionError("Expected output missing: " + javapOut);
}
 
Example 30
Project: log4j2-elasticsearch   File: IndexTemplate.java   Source Code and License 5 votes vote down vote up
private String loadFileSystemResource() {
    try {
        return new String(Files.readAllBytes(Paths.get(path)));
    } catch (IOException e){
        throw new ConfigurationException(e.getMessage(), e);
    }
}
 
Example 31
Project: jdk8u-jdk   File: CopyClassFile.java   Source Code and License 5 votes vote down vote up
private static void copyFile(File f) {
    try {
        Path classFilePath = Paths.get(classFile);
        String packagePath = classFilePath.getParent() == null ? "" : classFilePath.getParent().toString();
        Path p = Paths.get(destinationDir + packagePath + File.separator + f.getName());
        Files.createDirectories(p.getParent());
        try (InputStream is = new FileInputStream(f)) {
            Files.copy(is, p, StandardCopyOption.REPLACE_EXISTING);
        }
    } catch (IOException ex) {
        throw new RuntimeException("Could not copy file " + f, ex);
    }
}
 
Example 32
Project: GuildBot   File: GuildBot.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unused")
public static void main(final String[] args) throws Exception
{
    final File config = new File(System.getProperty("guildbot.config", "config.hjson"));

    String token = PropertyUtil.getProperty("guildbot.token", Paths.get(".token"));
    if (token == null)
        throw new RuntimeException("could not find a token");

    String webhook = PropertyUtil.getProperty("guildbot.webhook.error", Paths.get(".error-hook"));
    if (webhook == null)
        GuildBot.log.warn("could not find a error webhook token, disabling webhook");

    new GuildBot(config, token, webhook);
}
 
Example 33
Project: personium-core   File: CellImportResource.java   Source Code and License 5 votes vote down vote up
/**
 * GET method.
 * @return JAX-RS Response
 */
@GET
public Response get() {
    // Check the authority required for execution.
    cellRsCmp.checkAccessContext(cellRsCmp.getAccessContext(), CellPrivilege.ROOT);

    String jsonString = "";
    if (Cell.STATUS_NORMAL.equals(cellRsCmp.getDavCmp().getCellStatus())) {
        // Get processing status from cache.
        // If it returns null, it is regarded as ready state.
        String key = SnapshotFileImportProgressInfo.getKey(cellRsCmp.getCell().getId());
        Progress progress = ProgressManager.getProgress(key);
        if (progress == null) {
            JSONObject response = SnapshotFileImportProgressInfo.getReadyJson();
            jsonString = response.toJSONString();
        } else {
            jsonString = progress.getValue();
        }
    } else {
        // Get status from error file.
        Path errorFilePath = Paths.get(PersoniumUnitConfig.getBlobStoreRoot(),
                cellRsCmp.getCell().getDataBundleName(), cellRsCmp.getCell().getId(), Cell.IMPORT_ERROR_FILE_NAME);
        try {
            jsonString = new String(Files.readAllBytes(errorFilePath), Charsets.UTF_8);
        } catch (IOException e) {
            throw PersoniumCoreException.Common.FILE_IO_ERROR.params("read error json file").reason(e);
        }
    }
    return Response.ok().entity(jsonString).build();
}
 
Example 34
Project: S3Mock   File: FileStoreTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldCreateMultipartUploadFolder() {
  fileStore.prepareMultipartUpload(TEST_BUCKET_NAME, "aFile", DEFAULT_CONTENT_TYPE, "12345",
      TEST_OWNER, TEST_OWNER);

  final File destinationFolder =
      Paths.get(rootFolder.getAbsolutePath(), TEST_BUCKET_NAME, "aFile", "12345").toFile();

  assertThat("Destination folder does not exist", destinationFolder.exists(), is(true));
  assertThat("Destination folder is not a directory", destinationFolder.isDirectory(), is(true));
}
 
Example 35
Project: jfrog-idea-plugin   File: NpmScanManager.java   Source Code and License 5 votes vote down vote up
/**
 * Return a callback that handle fs operations on files.
 * Specifically in our case, each change in 'package.json', 'package-lock.json' or '.npmrc' trigger a call to this callback.
 * @return callback that handle fs operations on files
 */
private FileChangeListener.Callback getFileListenerCbk() {
    return (virtualFileEvent, fileEventType) -> {
        if (project.isDisposed()) {
            return;
        }
        String projectBasePath = getProjectBasePath(project);
        Path originPath = Paths.get(virtualFileEvent.getFile().getPath());
        String relativeOriginPath = new File(projectBasePath).toURI().relativize(originPath.toUri()).getPath();
        Path installationFilePath = Paths.get(projectBasePath, INSTALLATION_DIR, relativeOriginPath);
        try {
            switch (fileEventType) {
                case Copy:
                case Create:
                case Change:
                case Move:
                    // Nothing to do. The 'Refresh Dependencies' copies all relevant files.
                    break;
                case Delete:
                    Files.deleteIfExists(installationFilePath);
                    break;
            }

        } catch (IOException e) {
            Utils.notify(logger, "Failed to delete file", e, NotificationType.WARNING);
        }

        NpmScanManager.super.asyncScanAndUpdateResults(true);
    };
}
 
Example 36
Project: openjdk-jdk10   File: JAXPTestUtilities.java   Source Code and License 5 votes vote down vote up
/**
 * Compare contents of golden file with test output file line by line.
 * return true if they're identical.
 * @param goldfile Golden output file name.
 * @param outputfile Test output file name.
 * @param cs the charset to use for decoding.
 * @return true if two files are identical.
 *         false if two files are not identical.
 * @throws IOException if an I/O error occurs reading from the file or a
 *         malformed or unmappable byte sequence is read.
 */
public static boolean compareWithGold(String goldfile, String outputfile,
         Charset cs) throws IOException {
    boolean isSame = Files.readAllLines(Paths.get(goldfile)).
            equals(Files.readAllLines(Paths.get(outputfile), cs));
    if (!isSame) {
        System.err.println("Golden file " + goldfile + " :");
        Files.readAllLines(Paths.get(goldfile)).forEach(System.err::println);
        System.err.println("Output file " + outputfile + " :");
        Files.readAllLines(Paths.get(outputfile), cs).forEach(System.err::println);
    }
    return isSame;
}
 
Example 37
Project: openjdk-jdk10   File: PatchSystemModules.java   Source Code and License 5 votes vote down vote up
@BeforeTest
private void setup() throws Throwable {
    Path src = TEST_SRC.resolve("src");
    Path src1 = TEST_SRC.resolve("src1");

    for (String name : modules) {
        assertTrue(CompilerUtils.compile(src.resolve(name),
                                         MODS_DIR,
                                         "--module-source-path", src.toString()));
    }

    // compile patched source
    String patchDir = src1.resolve(JAVA_BASE).toString();
    assertTrue(CompilerUtils.compile(src1.resolve(JAVA_BASE),
                                     PATCH_DIR.resolve(JAVA_BASE),
                                     "--patch-module", "java.base=" + patchDir));
    assertTrue(CompilerUtils.compile(src1.resolve("m2"),
                                     PATCH_DIR.resolve("m2")));

    createJars();

    // create an image with only m1 and m2
    if (Files.exists(JMODS)) {
        // create an image with m1,m2
        createImage();
    }

    // compile a different version of m1
    Path tmp = Paths.get("tmp");
    assertTrue(CompilerUtils.compile(src1.resolve("m1"), tmp,
                                     "--module-path", MODS_DIR.toString(),
                                     "--module-source-path", src1.toString()));

    // package new_m1.jar
    jar("--create",
        "--file=" + NEW_M1_JAR.toString(),
        "-C", tmp.resolve("m1").toString(), ".");
}
 
Example 38
Project: junit-extensions   File: TemporaryFolderExtensionFieldTest.java   Source Code and License 5 votes vote down vote up
@AfterAll
public static void allTemporaryFilesAreDeleted() {
  List<String> existingFiles =
      temporaryFilePaths
          .stream()
          .filter(temporaryFilePath -> Files.exists(Paths.get(temporaryFilePath)))
          .collect(Collectors.toList());

  assertThat(existingFiles, empty());
}
 
Example 39
Project: Cognizant-Intelligent-Test-Scripter   File: AppResourcePath.java   Source Code and License 5 votes vote down vote up
public static String getEngineJarPath() {
    try {
        return Files.find(
                Paths.get(getAppRoot(), "lib"),
                1,
                (path, bfa) -> path.toFile().getName().matches("cognizant-intelligent-test-scripter-engine.*.jar")
        ).map(Path::toString).findFirst().orElse("");
    } catch (IOException ex) {
        Logger.getLogger(AppResourcePath.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}
 
Example 40
Project: jdk8u-jdk   File: LogGeneratedClassesTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testDumpDirIsFile() throws IOException {
    assertTrue(Files.isRegularFile(Paths.get("file")));
    TestResult tr = doExec(JAVA_CMD.getAbsolutePath(),
                           "-cp", ".",
                           "-Djdk.internal.lambda.dumpProxyClasses=file",
                           "-Djava.security.manager",
                           "com.example.TestLambda");
    assertEquals(tr.testOutput.stream()
                              .filter(s -> s.startsWith("WARNING"))
                              .peek(s -> assertTrue(s.contains("not a directory")))
                              .count(),
                 1, "only show error once");
    tr.assertZero("Should still return 0");
}
 
Example 41
Project: openjdk-jdk10   File: DeserializeButtonTest.java   Source Code and License 5 votes vote down vote up
private static void setup() throws Exception {
    Path classes = Paths.get(System.getProperty("test.classes", ""));
    JarUtils.createJarFile(Paths.get("cb.jar"),
                           classes,
                           classes.resolve("Foo.class"),
                           classes.resolve("Foo$TestElement.class"));
}
 
Example 42
Project: monarch   File: AbstractTierStoreWriter.java   Source Code and License 5 votes vote down vote up
/**
 * Write multiple rows to file
 *
 * @param writerProperties
 * @param rows
 * @return number of rows written
 */
@Override
public int write(final Properties writerProperties, List<StoreRecord> rows) throws IOException {
  Properties newProps = new Properties();
  newProps.putAll(this.writerProperties);
  newProps.putAll(writerProperties);

  String tableName = newProps.getProperty(CommonConfig.TABLE_NAME);
  int partitionId = Integer.parseInt(newProps.getProperty(CommonConfig.PARTITION_ID));
  URI baseURI = URI.create(newProps.getProperty(CommonConfig.BASE_URI));
  final boolean timeBasedPartitioningEnabled = Boolean.parseBoolean(newProps
      .getProperty(CommonConfig.TIME_BASED_PARTITIONING, String.valueOf(TIME_BASED_PARTITION)));
  long timeInterval = 0;
  if (timeBasedPartitioningEnabled) {
    timeInterval = Long.parseLong(newProps.getProperty(CommonConfig.PARTITIIONING_INTERVAL_MS,
        String.valueOf(TierStoreConfiguration.DEFAULT_TIER_PARTITION_INTERVAL_MS)));
  }

  Configuration conf = new Configuration();
  String hdfsSiteXMLPath = newProps.getProperty(CommonConfig.HDFS_SITE_XML_PATH);
  String hadoopSiteXMLPath = newProps.getProperty(CommonConfig.HADOOP_SITE_XML_PATH);
  if (hdfsSiteXMLPath != null) {
    conf.addResource(Paths.get(hdfsSiteXMLPath).toUri().toURL());
  }
  if (hadoopSiteXMLPath != null) {
    conf.addResource(Paths.get(hadoopSiteXMLPath).toUri().toURL());
  }
  newProps.entrySet().forEach((PROP) -> {
    conf.set(String.valueOf(PROP.getKey()), String.valueOf(PROP.getValue()));
  });

  // process records and write

  return _write(newProps, rows, timeInterval, baseURI, tableName, partitionId, conf);
}
 
Example 43
Project: openjdk-jdk10   File: JlinkTask.java   Source Code and License 5 votes vote down vote up
private static Path toPathLocation(ResolvedModule m) {
    Optional<URI> ouri = m.reference().location();
    if (!ouri.isPresent())
        throw new InternalError(m + " does not have a location");
    URI uri = ouri.get();
    return Paths.get(uri);
}
 
Example 44
Project: r8   File: D8CommandTest.java   Source Code and License 5 votes vote down vote up
@Test
public void defaultOutIsCwd() throws IOException, InterruptedException {
  Path working = temp.getRoot().toPath();
  Path input = Paths.get(EXAMPLES_BUILD_DIR + "/arithmetic.jar").toAbsolutePath();
  Path output = working.resolve("classes.dex");
  assertFalse(Files.exists(output));
  assertEquals(0, ToolHelper.forkD8(working, input.toString()).exitCode);
  assertTrue(Files.exists(output));
}
 
Example 45
Project: openjdk-jdk10   File: PackageAccessTest.java   Source Code and License 5 votes vote down vote up
static void setup() throws Exception {
    Path classes = Paths.get(System.getProperty("test.classes", ""));
    JarUtils.createJarFile(Paths.get("foo.jar"), classes,
            classes.resolve("B.class"), classes.resolve("D.class"));
    Files.delete(classes.resolve("B.class"));
    Files.delete(classes.resolve("D.class"));
}
 
Example 46
Project: openjdk-jdk10   File: MultiReleaseJarTest.java   Source Code and License 5 votes vote down vote up
private void compile() throws Throwable {
    String[] vers = {"base", "v9", "v10"};
    for (String ver : vers) {
        Path classes = Paths.get("classes", ver);
        Files.createDirectories(classes);
        Path source = Paths.get(Utils.TEST_SRC,"data", "mr", ver);
        assertTrue(CompilerUtils.compile(source, classes,
                "--add-modules", "java.xml.ws"));
    }
}
 
Example 47
Project: openjdk-jdk10   File: Basic.java   Source Code and License 5 votes vote down vote up
static void viaProviderWithTemplate(String protocol,
                                    Consumer<Result> resultChecker,
                                    Path template, String... sysProps)
    throws Exception
{
    System.out.println("\nTesting " + protocol);
    Path testRoot = Paths.get("URLStreamHandlerProvider-" + protocol);
    if (Files.exists(testRoot))
        FileUtils.deleteFileTreeWithRetry(testRoot);
    Files.createDirectory(testRoot);

    Path srcPath = Files.createDirectory(testRoot.resolve("src"));
    Path srcClass = createProvider(protocol, template, srcPath);

    Path build = Files.createDirectory(testRoot.resolve("build"));
    javac(build, srcClass);
    createServices(build, protocol);
    Path testJar = testRoot.resolve("test.jar");
    jar(testJar, build);

    List<String> props = new ArrayList<>();
    for (String p : sysProps)
        props.add(p);

    Result r = java(props, asList(testJar, TEST_CLASSES),
                    "Child", protocol);

    resultChecker.accept(r);
}
 
Example 48
Project: Learning-Spring-Boot-2.0-Second-Edition   File: ImageService.java   Source Code and License 5 votes vote down vote up
public Mono<Void> createImage(Flux<FilePart> files) {
	return files
		.log("createImage-files")
		.flatMap(file -> {
			Mono<Image> saveDatabaseImage = imageRepository.save(
				new Image(
					UUID.randomUUID().toString(),
					file.filename()))
				.log("createImage-save");

			Mono<Void> copyFile = Mono.just(
				Paths.get(UPLOAD_ROOT, file.filename())
					.toFile())
				.log("createImage-picktarget")
				.map(destFile -> {
					try {
						destFile.createNewFile();
						return destFile;
					} catch (IOException e) {
						throw new RuntimeException(e);
					}
				})
				.log("createImage-newfile")
				.flatMap(file::transferTo)
				.log("createImage-copy");

			return Mono.when(saveDatabaseImage, copyFile)
				.log("createImage-when");
		})
		.log("createImage-flatMap")
		.then()
		.log("createImage-done");
}
 
Example 49
Project: de.flapdoodle.solid   File: WordpressRssConverter.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws IOException, DocumentException {
	System.out.println("solid wordpress converter");
	Preconditions.checkArgument(args.length>=2,"usage: <rss-xml> <exportDirectory>");
	
	Path rssXml = Paths.get(args[0]);
	Path target = Paths.get(args[1]);
	
	try (Reader reader = new InputStreamReader(Files.newInputStream(rssXml, StandardOpenOption.READ))) {
		WordpressRss wordpressRss = WordpressRssConverter.build(XmlParser.of(reader));
		ImmutableList<Document> documents = WordpressRss2Solid.convert(wordpressRss);
		ImmutableSet<String> allPaths = documents.stream()
			.map(Document::path)
			.collect(ImmutableSet.toImmutableSet());
		Preconditions.checkArgument(allPaths.size()==documents.size(),"path collisions");
		
		// create directory for page and post
		createDirectoryIfNotExist(target.resolve("post"));
		createDirectoryIfNotExist(target.resolve("page"));
		
		documents.forEach((Document d) -> {
			Path filePath = target.resolve(d.path());
			Try.runable(() -> {
				Files.write(filePath, asBytes(d.content()), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
			})
			.mapCheckedException(RuntimeException::new)
			.run();
		});
	}
}
 
Example 50
Project: smart-testing   File: ConfigurationOverwriteUsingInheritWithSystemPropertyTest.java   Source Code and License 5 votes vote down vote up
@Test
public void system_properties_should_take_precedence_over_config_file() throws IOException {
    // given
    System.setProperty(SMART_TESTING, "changed");
    System.setProperty(SCM_LAST_CHANGES, "3");

    temporaryFolder.newFolder(CONFIG);
    final String root = temporaryFolder.getRoot().toString();

    configurationFile()
        .inherit("../smart-testing.yml")
        .mode("ordering")
        .writeTo(Paths.get(root, CONFIG, SMART_TESTING_YML));

    configurationFile()
        .strategies("new, changed, affected")
        .writeTo(Paths.get(root, SMART_TESTING_YML));

    final Range range = new Range();
    range.setHead(HEAD);
    range.setTail(HEAD + "~3");

    // when
    final Configuration configuration = ConfigurationLoader.load(Paths.get(root, CONFIG).toFile());

    // then
    softly.assertThat(configuration)
        .hasAppliedStrategies("changed")
        .hasMode(ORDERING)
        .hasScmRange(range);
}
 
Example 51
Project: message-broker   File: SslHandlerFactory.java   Source Code and License 5 votes vote down vote up
private Path getPath(String storePath) {
    Path path = Paths.get(storePath);

    if (Files.notExists(path)) {
        String brokerHome = System.getProperty(CommonConstants.MESSAGE_BROKER_HOME_PROPERTY);
        path = Paths.get(brokerHome + File.separator + storePath);
    }
    return path;
}
 
Example 52
Project: aidos-node   File: StorageTags.java   Source Code and License 5 votes vote down vote up
@Override
public void init() throws IOException {
	tagsChannel = FileChannel.open(Paths.get(TAGS_FILE_NAME), StandardOpenOption.CREATE, StandardOpenOption.READ,
	        StandardOpenOption.WRITE);
	tagsChunks[0] = tagsChannel.map(FileChannel.MapMode.READ_WRITE, 0, SUPER_GROUPS_SIZE);
	final long tagsChannelSize = tagsChannel.size();
	while (true) {

		if ((tagsNextPointer & (CHUNK_SIZE - 1)) == 0) {
			tagsChunks[(int) (tagsNextPointer >> 27)] = tagsChannel.map(FileChannel.MapMode.READ_WRITE,
			        tagsNextPointer, CHUNK_SIZE);
		}

		if (tagsChannelSize - tagsNextPointer > CHUNK_SIZE) {
			tagsNextPointer += CHUNK_SIZE;
		} else {
			tagsChunks[(int) (tagsNextPointer >> 27)].get(mainBuffer);
			boolean empty = true;
			for (final int value : mainBuffer) {
				if (value != 0) {
					empty = false;
					break;
				}
			}
			if (empty) {
				break;
			}

			tagsNextPointer += CELL_SIZE;
		}
	}
}
 
Example 53
Project: qpp-conversion-tool   File: InputStreamSupplierSourceTest.java   Source Code and License 5 votes vote down vote up
private static InputStream stream(String path) {
	try {
		return Files.newInputStream(Paths.get(path));
	} catch (IOException exception) {
		throw new UncheckedIOException(exception);
	}
}
 
Example 54
Project: chipKIT-importer   File: LanguageToolchainLocator.java   Source Code and License 5 votes vote down vote up
private Version getVersion(LanguageToolchain lt) {
    Path p = Paths.get(lt.getDirectory());
    Path versionElement = p.getName(p.getNameCount() - 2);
    String versionString = versionElement.toString();
    if (versionString.startsWith("v")) {
        return new Version(versionString.substring(1));
    } else {
        return new Version(versionString);
    }
}
 
Example 55
Project: pcf-metrics-trace-example-spring   File: App.java   Source Code and License 5 votes vote down vote up
public Trace getTrace() throws IOException {
    String logs = new String(Files.readAllBytes(Paths.get(logFile.getAbsolutePath())));
    Matcher m = Pattern.compile("\\[[^,]*,([a-f0-9]+),([a-f0-9]+),([a-f0-9]+),?\\w*\\]").matcher(logs);
    m.find();

    return new Trace(m.group(1), m.group(2), m.group(3));
}
 
Example 56
Project: openjdk-jdk10   File: Helper.java   Source Code and License 5 votes vote down vote up
public static Helper newHelper() throws IOException {
    Path jdkHome = Paths.get(System.getProperty("test.jdk"));
    // JPRT not yet ready for jmods
    if (!Files.exists(jdkHome.resolve("jmods"))) {
        System.err.println("Test not run, NO jmods directory");
        return null;
    }
    return new Helper(jdkHome);
}
 
Example 57
Project: Meucci   File: Master.java   Source Code and License 5 votes vote down vote up
private static void deleteAll(int v, ArrayList<String> createdFiles)
throws IOException{
    /*
    v=0 elimina tutto
    v=1 lascia i .asm
    v=2 lascia i .o
    */
    for(String t:createdFiles){
        if(v!=1)
            Files.deleteIfExists(Paths.get(t+".asm"));
        if(v!=2)
            Files.deleteIfExists(Paths.get(t+".o"));
    }
}
 
Example 58
Project: r8   File: ExtraFileTest.java   Source Code and License 5 votes vote down vote up
@Test
public void splitMemberRebindingTwoFilesRelease()
    throws IOException, ProguardRuleParserException, ExecutionException, CompilationException {
  if (!ToolHelper.artSupported()) {
    return;
  }

  Path out = temp.getRoot().toPath();
  Path original = Paths.get(EXAMPLE_DIR, EXAMPLE_DEX);
  Path packageMap = Paths.get(ToolHelper.EXAMPLES_DIR, EXAMPLE_PACKAGE_MAP);
  Path proguardMap = Paths.get(ToolHelper.EXAMPLES_DIR, EXAMPLE_PROGUARD_MAP);
  R8Command command =
      R8Command.builder()
          .addProgramFiles(original)
          .setMode(CompilationMode.RELEASE)
          .setOutputPath(out)
          .setMinApiLevel(Constants.ANDROID_L_API) // Allow native multidex.
          .setProguardMapFile(proguardMap)
          .setPackageDistributionFile(packageMap)
          .build();
  ToolHelper.runR8(command);
  List<String> outs =
      new ArrayList<>(
          ImmutableList.of(
              out.resolve("classes.dex").toString(),
              out.resolve("classes2.dex").toString(),
              EXAMPLE_DIR + EXAMPLE_LIB));
  outs.forEach(f -> Assert.assertTrue("Failed to find file " + f, Files.exists(Paths.get(f))));
  ToolHelper.checkArtOutputIdentical(
      ImmutableList.of(original.toString(), EXAMPLE_DIR + EXAMPLE_LIB),
      outs,
      EXAMPLE_CLASS,
      null,
      null);
}
 
Example 59
Project: openjdk-jdk10   File: CreateSymbols.java   Source Code and License 5 votes vote down vote up
public static ExcludeIncludeList create(String files) throws IOException {
    Set<String> includeList = new HashSet<>();
    Set<String> excludeList = new HashSet<>();
    for (String file : files.split(File.pathSeparator)) {
        try (Stream<String> lines = Files.lines(Paths.get(file))) {
            lines.map(l -> l.substring(0, l.indexOf('#') != (-1) ? l.indexOf('#') : l.length()))
                 .filter(l -> !l.trim().isEmpty())
                 .forEach(l -> {
                     Set<String> target = l.startsWith("+") ? includeList : excludeList;
                     target.add(l.substring(1));
                 });
        }
    }
    return new ExcludeIncludeList(includeList, excludeList);
}
 
Example 60
Project: ShowPolicyPackage   File: HtmlUtils.java   Source Code and License 5 votes vote down vote up
/**
 * This function returns an array containing the lines that are in a given path
 *
 * @param templatePath the path to be read from
 *
 * @return a list containing all of the lines in the file that are in a given path
 */
private List<String> readHTMLTemplate(String templatePath)
{
    List<String> templateFile = null;
    try {
        templateFile = Files.readAllLines(Paths.get(templatePath), ENCODING);
    }
    catch (IOException e) {
        System.out.println("Failed to read file" + templatePath);
    }

    return templateFile;
}