Java Code Examples for java.nio.file.Files

The following examples show how to use java.nio.file.Files. These examples are extracted from open source projects.
Example 1
Project: openjdk-jdk9   File: CompilerUtils.java    License: GNU General Public License v2.0 6 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
 */
public static boolean compile(Path source, Path destination, String ... options)
    throws IOException
{
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    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.EMPTY_LIST);
    jfm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT,
                             Arrays.asList(destination));

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

    return task.call();
}
 
Example 2
Project: buck   File: RustBinaryIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void simpleBinaryIncremental() throws IOException {
  ProjectWorkspace workspace =
      TestDataHelper.createProjectWorkspaceForScenario(this, "simple_binary", tmp);
  workspace.setUp();
  BuckBuildLog buildLog;

  workspace
      .runBuckCommand("build", "-c", "rust#default.incremental=opt", "//:xyzzy#check")
      .assertSuccess();
  buildLog = workspace.getBuildLog();
  buildLog.assertTargetBuiltLocally("//:xyzzy#check");

  workspace
      .runBuckCommand("build", "-c", "rust#default.incremental=dev", "//:xyzzy")
      .assertSuccess();
  buildLog = workspace.getBuildLog();
  buildLog.assertTargetBuiltLocally("//:xyzzy");

  assertTrue(
      Files.isDirectory(workspace.resolve("buck-out/tmp/rust-incremental/dev/binary/default")));
  assertTrue(
      Files.isDirectory(workspace.resolve("buck-out/tmp/rust-incremental/opt/check/default")));
}
 
Example 3
Project: incubator-gobblin   File: RegexBasedPartitionedRetrieverTest.java    License: Apache License 2.0 6 votes vote down vote up
@AfterClass
public void cleanup() throws IOException {
  Files.walkFileTree(tempDir, new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
        throws IOException {
      Files.delete(file);
      return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc)
        throws IOException {
      Files.delete(dir);
      return FileVisitResult.CONTINUE;
    }
  });
}
 
Example 4
Project: LuckPerms   File: FileActionLogger.java    License: MIT License 6 votes vote down vote up
public Log getLog() throws IOException {
    if (!Files.exists(this.contentFile)) {
        return Log.empty();
    }

    Log.Builder log = Log.builder();

    try (BufferedReader reader = Files.newBufferedReader(this.contentFile, StandardCharsets.UTF_8)) {
        String line;
        while ((line = reader.readLine()) != null) {
            try {
                JsonElement parsed = GsonProvider.parser().parse(line);
                log.add(ActionJsonSerializer.deserialize(parsed));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    return log.build();
}
 
Example 5
Project: quarkus   File: QuteProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private void scan(Path root, Path directory, String basePath, BuildProducer<HotDeploymentWatchedFileBuildItem> watchedPaths,
        BuildProducer<TemplatePathBuildItem> templatePaths,
        BuildProducer<NativeImageResourceBuildItem> nativeImageResources)
        throws IOException {
    try (Stream<Path> files = Files.list(directory)) {
        Iterator<Path> iter = files.iterator();
        while (iter.hasNext()) {
            Path filePath = iter.next();
            if (Files.isRegularFile(filePath)) {
                LOGGER.debugf("Found template: %s", filePath);
                String templatePath = root.relativize(filePath).toString();
                if (File.separatorChar != '/') {
                    templatePath = templatePath.replace(File.separatorChar, '/');
                }
                produceTemplateBuildItems(templatePaths, watchedPaths, nativeImageResources, basePath, templatePath,
                        filePath);
            } else if (Files.isDirectory(filePath)) {
                LOGGER.debugf("Scan directory: %s", filePath);
                scan(root, filePath, basePath, watchedPaths, templatePaths, nativeImageResources);
            }
        }
    }
}
 
Example 6
Project: openjdk-jdk8u   File: FieldSetAccessibleTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
Stream<String> folderToStream(String folderName) {
    final File root = new File(folderName);
    if (root.canRead() && root.isDirectory()) {
        final Path rootPath = root.toPath();
        try {
            return Files.walk(rootPath)
                .filter(p -> p.getFileName().toString().endsWith(".class"))
                .map(rootPath::relativize)
                .map(p -> p.toString().replace(File.separatorChar, '/'));
        } catch (IOException x) {
            x.printStackTrace(System.err);
            skipped.add(folderName);
        }
    } else {
        cantread.add(folderName);
    }
    return Collections.<String>emptyList().stream();
}
 
Example 7
Project: ipst   File: MMapOfflineDb.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@Override
public Map<Integer, SecurityIndex> getSecurityIndexes(String workflowId, SecurityIndexId securityIndexId) {
    PersistenceContext context = getContext(workflowId);
    int securityIndexNum = context.getTable().getDescription().getColumnIndex(securityIndexId);
    Map<Integer, SecurityIndex> securityIndexes = new TreeMap<>();
    try {
        try (BufferedReader securityIndexesXmlReader = Files.newBufferedReader(context.getWorkflowDir().resolve(SECURITY_INDEXES_XML_FILE_NAME), StandardCharsets.UTF_8)) {
            String line;
            while ((line = securityIndexesXmlReader.readLine()) != null) {
                String[] tokens = line.split(Character.toString(CSV_SEPARATOR));
                int sampleId = Integer.parseInt(tokens[0]);
                int securityIndexNum2 = Integer.parseInt(tokens[1]);
                if (securityIndexNum2 == securityIndexNum) {
                    String xml = tokens[2];
                    try (StringReader reader = new StringReader(xml)) {
                        SecurityIndex securityIndex = SecurityIndexParser.fromXml(securityIndexId.getContingencyId(), reader).get(0);
                        securityIndexes.put(sampleId, securityIndex);
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return securityIndexes;
}
 
Example 8
Project: SerialKiller   File: SerialKillerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testReload() throws Exception {
    Path tempFile = Files.createTempFile("sk-", ".conf");
    Files.copy(new File("src/test/resources/blacklist-all-refresh-10-ms.conf").toPath(), tempFile, REPLACE_EXISTING);

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();

    try (ObjectOutputStream stream = new ObjectOutputStream(bytes)) {
        stream.writeObject(42);
    }

    try (ObjectInputStream stream = new SerialKiller(new ByteArrayInputStream(bytes.toByteArray()), tempFile.toAbsolutePath().toString())) {

        Files.copy(new File("src/test/resources/whitelist-all.conf").toPath(), tempFile, REPLACE_EXISTING);
        Thread.sleep(1000L); // Wait to ensure the file is fully copied
        Files.setLastModifiedTime(tempFile, FileTime.fromMillis(System.currentTimeMillis())); // Commons configuration watches file modified time
        Thread.sleep(1000L); // Wait to ensure a reload happens

        assertEquals(42, stream.readObject());
    }
}
 
Example 9
Project: flink   File: PackagedProgramTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testExtractContainedLibraries() throws Exception {
	String s = "testExtractContainedLibraries";
	byte[] nestedJarContent = s.getBytes(ConfigConstants.DEFAULT_CHARSET);
	File fakeJar = temporaryFolder.newFile("test.jar");
	try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(fakeJar))) {
		ZipEntry entry = new ZipEntry("lib/internalTest.jar");
		zos.putNextEntry(entry);
		zos.write(nestedJarContent);
		zos.closeEntry();
	}

	final List<File> files = PackagedProgram.extractContainedLibraries(fakeJar.toURI().toURL());
	Assert.assertEquals(1, files.size());
	Assert.assertArrayEquals(nestedJarContent, Files.readAllBytes(files.iterator().next().toPath()));
}
 
Example 10
Project: bazel   File: DumpPlatformClassPath.java    License: Apache License 2.0 6 votes vote down vote up
/** Writes the given entry names and data to a jar archive at the given path. */
private static void writeEntries(Path output, Map<String, InputStream> entries)
    throws IOException {
  if (!entries.containsKey("java/lang/Object.class")) {
    throw new AssertionError(
        "\nCould not find java.lang.Object on bootclasspath; something has gone terribly wrong.\n"
            + "Please file a bug: https://github.com/bazelbuild/bazel/issues");
  }
  try (OutputStream os = Files.newOutputStream(output);
      BufferedOutputStream bos = new BufferedOutputStream(os, 65536);
      JarOutputStream jos = new JarOutputStream(bos)) {
    entries.entrySet().stream()
        .forEachOrdered(
            entry -> {
              try {
                addEntry(jos, entry.getKey(), entry.getValue());
              } catch (IOException e) {
                throw new UncheckedIOException(e);
              }
            });
  }
}
 
Example 11
Project: che   File: PersistTestModuleBuilderTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void generatesPersistenceXml() throws Exception {
  Path path =
      new PersistTestModuleBuilder()
          .setDriver("org.h2.Driver")
          .addEntityClass(MyEntity1.class)
          .addEntityClass(
              "org.eclipse.che.commons.test.db.PersistTestModuleBuilderTest$MyEntity2")
          .setUrl("jdbc:h2:mem:test")
          .setUser("username")
          .setPassword("secret")
          .setLogLevel("FINE")
          .setPersistenceUnit("test-unit")
          .setExceptionHandler(MyExceptionHandler.class)
          .setProperty("custom-property", "value")
          .savePersistenceXml();

  URL url =
      Thread.currentThread()
          .getContextClassLoader()
          .getResource("org/eclipse/che/commons/test/db/test-persistence-1.xml");
  assertNotNull(url);
  assertEquals(new String(Files.readAllBytes(path), UTF_8), Resources.toString(url, UTF_8));
}
 
Example 12
Project: Tomcat8-Source-Read   File: TestHostConfigAutomaticDeployment.java    License: MIT License 6 votes vote down vote up
@Test
public void testSetContextClassName() throws Exception {

    Tomcat tomcat = getTomcatInstance();

    Host host = tomcat.getHost();
    if (host instanceof StandardHost) {
        StandardHost standardHost = (StandardHost) host;
        standardHost.setContextClass(TesterContext.class.getName());
    }

    // Copy the WAR file
    File war = new File(host.getAppBaseFile(),
            APP_NAME.getBaseName() + ".war");
    Files.copy(WAR_XML_SOURCE.toPath(), war.toPath());

    // Deploy the copied war
    tomcat.start();
    host.backgroundProcess();

    // Check the Context class
    Context ctxt = (Context) host.findChild(APP_NAME.getName());

    Assert.assertTrue(ctxt instanceof TesterContext);
}
 
Example 13
Project: ET_Redux   File: SesarSample.java    License: Apache License 2.0 6 votes vote down vote up
public static SesarSample createSesarSampleFromSesarRecord(String igsn) {
    SesarSample sesarSample = null;
    try {
        File sample = retrieveXMLFileFromSesarForIGSN(igsn);

        // replace the results tag with sample tag
        // todo make more robust
        Path file = sample.toPath();
        byte[] fileArray;
        fileArray = Files.readAllBytes(file);
        String str = new String(fileArray, "UTF-8");
        str = str.replace("results", "sample");
        fileArray = str.getBytes();
        Files.write(file, fileArray);

        sesarSample = (SesarSample) readXMLObject(file.toString());
    } catch (IOException | ETException iOException) {
    }

    return sesarSample;
}
 
Example 14
Project: jdk8u-jdk   File: Font.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Used with the byte count tracker for fonts created from streams.
 * If a thread can create temp files anyway, no point in counting
 * font bytes.
 */
private static boolean hasTempPermission() {

    if (System.getSecurityManager() == null) {
        return true;
    }
    File f = null;
    boolean hasPerm = false;
    try {
        f = Files.createTempFile("+~JT", ".tmp").toFile();
        f.delete();
        f = null;
        hasPerm = true;
    } catch (Throwable t) {
        /* inc. any kind of SecurityException */
    }
    return hasPerm;
}
 
Example 15
Project: gatk   File: RevertSamSpark.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@SuppressWarnings("unchecked")
static List<String>  validateOutputParamsByReadGroup(final String output, final String outputMap) throws IOException {
    final List<String> errors = new ArrayList<>();
    if (output != null) {
        if (!Files.isDirectory(IOUtil.getPath(output))) {
            errors.add("When '--output-by-readgroup' is set and output is provided, it must be a directory: " + output);
        }
        return errors;
    }
    // output is null if we reached here
    if (outputMap == null) {
        errors.add("Must provide either output or outputMap when '--output-by-readgroup' is set.");
        return errors;
    }
    if (!Files.isReadable(IOUtil.getPath(outputMap))) {
        errors.add("Cannot read outputMap " + outputMap);
        return errors;
    }
    final FeatureReader<TableFeature>  parser = AbstractFeatureReader.getFeatureReader(outputMap, new TableCodec(null),false);
    if (!isOutputMapHeaderValid((List<String>)parser.getHeader())) {
        errors.add("Invalid header: " + outputMap + ". Must be a tab-separated file with +"+OUTPUT_MAP_READ_GROUP_FIELD_NAME+"+ as first column and output as second column.");
    }
    return errors;
}
 
Example 16
Project: ph-commons   File: PathOperationsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteDir ()
{
  final Path aDir = Paths.get ("deldir.test");
  try
  {
    _expectedError (PathOperations.deleteDir (aDir), EFileIOErrorCode.SOURCE_DOES_NOT_EXIST);
    assertFalse (Files.isDirectory (aDir));
    _expectedSuccess (PathOperations.createDir (aDir));
    assertEquals (0, PathHelper.getDirectoryObjectCount (aDir));
    _expectedSuccess (PathOperations.deleteDir (aDir));
    assertFalse (Files.isDirectory (aDir));
  }
  finally
  {
    PathOperations.deleteDirRecursive (aDir);
  }

  try
  {
    PathOperations.deleteDir (null);
    fail ();
  }
  catch (final NullPointerException ex)
  {}
}
 
Example 17
@Test
public void testEncodedByeGb18030WithWinLineEndingFileWhenClientCharsetIsMatchUnderServerUnicodeEnabled_UnixClientLineEnding() throws Exception{
    String perforceCharset = "cp936";
    login(perforceCharset);

    File testResourceFile = loadFileFromClassPath("com/perforce/p4java/common/io/gb18030_win_line_endings.txt");
    long originalFileSize = Files.size(testResourceFile.toPath());
    Charset matchCharset = Charset.forName(PerforceCharsets.getJavaCharsetName(perforceCharset));
    long utf8EncodedOriginalFileSize = getUnicodeFileSizeAfterEncodedByUtf8(
            testResourceFile,
            matchCharset);

    testSubmitFile(
            "p4TestUnixLineend",
            testResourceFile,
            "unicode",
            utf8EncodedOriginalFileSize,
            originalFileSize
    );
}
 
Example 18
Project: lucene-solr   File: StandardDirectoryFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Override for more efficient moves.
 * 
 * Intended for use with replication - use
 * carefully - some Directory wrappers will
 * cache files for example.
 * 
 * You should first {@link Directory#sync(java.util.Collection)} any file that will be 
 * moved or avoid cached files through settings.
 * 
 * @throws IOException
 *           If there is a low-level I/O error.
 */
@Override
public void move(Directory fromDir, Directory toDir, String fileName, IOContext ioContext)
    throws IOException {
  
  Directory baseFromDir = getBaseDir(fromDir);
  Directory baseToDir = getBaseDir(toDir);
  
  if (baseFromDir instanceof FSDirectory && baseToDir instanceof FSDirectory) {

    Path path1 = ((FSDirectory) baseFromDir).getDirectory().toAbsolutePath();
    Path path2 = ((FSDirectory) baseToDir).getDirectory().toAbsolutePath();
    
    try {
      Files.move(path1.resolve(fileName), path2.resolve(fileName), StandardCopyOption.ATOMIC_MOVE);
    } catch (AtomicMoveNotSupportedException e) {
      Files.move(path1.resolve(fileName), path2.resolve(fileName));
    }
    return;
  }

  super.move(fromDir, toDir, fileName, ioContext);
}
 
Example 19
Project: buck   File: AppleLibraryIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAppleLibraryWithDefaultsInRuleBuildsSomething() throws IOException {
  assumeTrue(Platform.detect() == Platform.MACOS);
  assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX));

  ProjectWorkspace workspace =
      TestDataHelper.createProjectWorkspaceForScenario(
          this, "apple_library_with_platform_and_type", tmp);
  workspace.setUp();
  ProjectFilesystem filesystem =
      TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath());

  BuildTarget target = BuildTargetFactory.newInstance("//Libraries/TestLibrary:TestLibrary");
  ProcessResult result = workspace.runBuckCommand("build", target.getFullyQualifiedName());
  result.assertSuccess();

  BuildTarget implicitTarget =
      target.withAppendedFlavors(
          InternalFlavor.of("shared"), InternalFlavor.of("iphoneos-arm64"));
  Path outputPath =
      workspace.getPath(BuildTargetPaths.getGenPath(filesystem, implicitTarget, "%s"));
  assertTrue(Files.exists(outputPath));
}
 
Example 20
Project: nifi   File: TestExecuteStreamCommand.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteIngestAndUpdatePutToAttribute() throws IOException {
    File exJar = new File("src/test/resources/ExecuteCommand/TestIngestAndUpdate.jar");
    File dummy = new File("src/test/resources/ExecuteCommand/1000bytes.txt");
    File dummy10MBytes = new File("target/10MB.txt");
    byte[] bytes = Files.readAllBytes(dummy.toPath());
    try (FileOutputStream fos = new FileOutputStream(dummy10MBytes)) {
        for (int i = 0; i < 10000; i++) {
            fos.write(bytes, 0, 1000);
        }
    }
    String jarPath = exJar.getAbsolutePath();
    exJar.setExecutable(true);
    final TestRunner controller = TestRunners.newTestRunner(ExecuteStreamCommand.class);
    controller.enqueue(dummy10MBytes.toPath());
    controller.setProperty(ExecuteStreamCommand.EXECUTION_COMMAND, "java");
    controller.setProperty(ExecuteStreamCommand.EXECUTION_ARGUMENTS, "-jar;" + jarPath);
    controller.setProperty(ExecuteStreamCommand.PUT_OUTPUT_IN_ATTRIBUTE, "outputDest");
    controller.run(1);
    controller.assertTransferCount(ExecuteStreamCommand.ORIGINAL_RELATIONSHIP, 1);
    controller.assertTransferCount(ExecuteStreamCommand.OUTPUT_STREAM_RELATIONSHIP, 0);
    List<MockFlowFile> flowFiles = controller.getFlowFilesForRelationship(ExecuteStreamCommand.ORIGINAL_RELATIONSHIP);
    String result = flowFiles.get(0).getAttribute("outputDest");

    assertTrue(Pattern.compile("nifi-standard-processors:ModifiedResult\r?\n").matcher(result).find());
}
 
Example 21
Project: ambiverse-nlu   File: KnowNERCorpusCheckerIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnSuccessIfCorpusAndConfigurationExist() throws IOException, KnowNERLanguageConfiguratorException {
	Path corpusDir = Files.createDirectories(Paths.get(tempMainDir.toString(),language,
			CorpusConfiguration.CORPUS_DIRECTORY_NAME,
			CorpusConfiguration.DEFAULT_CORPUS_NAME));
	Files.write(Paths.get(corpusDir.toString(), CorpusConfiguration.DEFAULT_FILE_NAME),
			Collections.nCopies(6, "-DOCSTART-"));
	Files.write(Paths.get(corpusDir.toString(), CorpusConfiguration.DEFAULT_CORPUS_CONFIG_NAME),
			("{corpusFormat: DEFAULT, " +
					"rangeMap: {" +
					"TRAIN: [0,1]," +
					"TESTA: [2,3]," +
					"TESTB: [4,5]," +
					"TRAINA: [0,3]}}").getBytes());

	KnowNERCorpusChecker checker = new KnowNERCorpusChecker(tempMainDir.toString(), language, 6);
	assertTrue(checker.check().isSuccess());
}
 
Example 22
Project: carbon-kernel   File: ConversionTest.java    License: Apache License 2.0 6 votes vote down vote up
private boolean isOSGiBundle(Path bundlePath, String bundleSymbolicName) throws IOException, CarbonToolException {
    if (Files.exists(bundlePath)) {
        boolean validSymbolicName, exportPackageAttributeCheck, importPackageAttributeCheck;
        try (FileSystem zipFileSystem = BundleGeneratorUtils.createZipFileSystem(bundlePath, false)) {
            Path manifestPath = zipFileSystem.getPath(Constants.JAR_MANIFEST_FOLDER, Constants.MANIFEST_FILE_NAME);
            Manifest manifest = new Manifest(Files.newInputStream(manifestPath));

            Attributes attributes = manifest.getMainAttributes();
            String actualBundleSymbolicName = attributes.getValue(Constants.BUNDLE_SYMBOLIC_NAME);
            validSymbolicName = ((actualBundleSymbolicName != null) && ((bundleSymbolicName != null)
                    && bundleSymbolicName.equals(actualBundleSymbolicName)));
            exportPackageAttributeCheck = attributes.getValue(Constants.EXPORT_PACKAGE) != null;
            importPackageAttributeCheck = attributes.getValue(Constants.DYNAMIC_IMPORT_PACKAGE) != null;
        }
        return (validSymbolicName && exportPackageAttributeCheck && importPackageAttributeCheck);
    } else {
        return false;
    }
}
 
Example 23
Project: nexus-repository-apt   File: CompressingTempFileStore.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public Writer openOutput(String key) throws UncheckedIOException {
  try {
    if (holdersByKey.containsKey(key)) {
      throw new IllegalStateException("Output already opened");
    }
    FileHolder holder = new FileHolder();
    holdersByKey.put(key, holder);
    return new OutputStreamWriter(new TeeOutputStream(
        new TeeOutputStream(new GZIPOutputStream(Files.newOutputStream(holder.gzTempFile)),
            new BZip2CompressorOutputStream(Files.newOutputStream(holder.bzTempFile))),
        Files.newOutputStream(holder.plainTempFile)), Charsets.UTF_8);
  }
  catch (IOException e) {
    throw new UncheckedIOException(e);
  }
}
 
Example 24
Project: wildfly-core   File: KeyStoresTestCase.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private void addKeyStore(String keyStoreFile, String keyStoreName, String keyStorePassword) throws Exception {
    Path resources = Paths.get(KeyStoresTestCase.class.getResource(".").toURI());
    Files.copy(resources.resolve(keyStoreFile), resources.resolve("test-copy.keystore"), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
    ModelNode operation = new ModelNode();
    operation.get(ClientConstants.OPERATION_HEADERS).get("allow-resource-service-restart").set(Boolean.TRUE);
    operation.get(ClientConstants.OP_ADDR).add("subsystem","elytron").add("key-store", keyStoreName);
    operation.get(ClientConstants.OP).set(ClientConstants.ADD);
    operation.get(ElytronDescriptionConstants.PATH).set(resources + "/test-copy.keystore");
    operation.get(ElytronDescriptionConstants.TYPE).set("JKS");
    operation.get(CredentialReference.CREDENTIAL_REFERENCE).get(CredentialReference.CLEAR_TEXT).set(keyStorePassword);
    assertSuccess(services.executeOperation(operation));
}
 
Example 25
Project: logging-log4j2   File: AbstractLog4j1ConfigurationConverterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws IOException {
    final Path tempFile = Files.createTempFile("log4j2", ".xml");
    try {
        final Log4j1ConfigurationConverter.CommandLineArguments cla = new Log4j1ConfigurationConverter.CommandLineArguments();
        cla.setPathIn(pathIn);
        cla.setPathOut(tempFile);
        Log4j1ConfigurationConverter.run(cla);
    } finally {
        Files.deleteIfExists(tempFile);
    }
}
 
Example 26
Project: open   File: RouteFragmentTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void loadTestGpxTrace() throws IOException {
    byte[] encoded = Files.readAllBytes(Paths.get("src/test/resources/lost.gpx"));
    String contents = new String(encoded, "UTF-8");

    ShadowEnvironment.setExternalStorageState(Environment.MEDIA_MOUNTED);
    File directory = Environment.getExternalStorageDirectory();
    File file = new File(directory, "lost.gpx");
    FileWriter fileWriter = new FileWriter(file, false);
    fileWriter.write(contents);
    fileWriter.close();
}
 
Example 27
Project: buck   File: MostFiles.java    License: Apache License 2.0 5 votes vote down vote up
/** Writes the specified lines to the specified file, encoded as UTF-8. */
public static void writeLinesToFile(Iterable<String> lines, Path file) throws IOException {
  try (BufferedWriter writer = Files.newBufferedWriter(file, Charsets.UTF_8)) {
    for (String line : lines) {
      writer.write(line);
      writer.newLine();
    }
  }
}
 
Example 28
Project: athenz   File: X509CertRequestTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testValidateCertReqPublicKey() throws IOException {
    Path path = Paths.get("src/test/resources/valid.csr");
    String csr = new String(Files.readAllBytes(path));
    
    X509CertRequest certReq = new X509CertRequest(csr);
    assertNotNull(certReq);
    
    final String ztsPublicKey = "-----BEGIN PUBLIC KEY-----\n"
            + "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKrvfvBgXWqWAorw5hYJu3dpOJe0gp3n\n"
            + "TgiiPGT7+jzm6BRcssOBTPFIMkePT2a8Tq+FYSmFnHfbQjwmYw2uMK8CAwEAAQ==\n"
            + "-----END PUBLIC KEY-----";
    
    assertTrue(certReq.validatePublicKeys(ztsPublicKey));
}
 
Example 29
Project: geoportal-server-harvester   File: FolderBroker.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void terminate() {
  if (definition.getCleanup() && !preventCleanup) {
    for (String f: existing) {
      if (Thread.currentThread().isInterrupted()) break;
      try {
        Files.delete(Paths.get(f));
      } catch (IOException ex) {
        LOG.warn(String.format("Error deleting file: %s", f), ex);
      }
    }
    LOG.info(String.format("%d records has been removed during cleanup.", existing.size()));
  }
}
 
Example 30
Project: java-dcp-client   File: HighLevelApi.java    License: Apache License 2.0 5 votes vote down vote up
public void save() throws IOException {
  Path temp = Files.createTempFile(path.getParent(), "stream-offsets-", "-tmp.json");
  Files.write(temp, mapper.writeValueAsBytes(offsets));
  Files.move(temp, path, ATOMIC_MOVE);
  System.out.println("Saved stream offsets to " + path);
  System.out.println("The next time this example runs, it will resume streaming from this point.");
}
 
Example 31
Project: jsr203-hadoop   File: TestPath.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSubpathInvalid() throws IOException, URISyntaxException {
  Path rootPath = Paths.get(clusterUri);

  Files.createDirectories(rootPath.resolve("tmp/testNormalize/dir1/"));

  Path p = rootPath.resolve("tmp/testNormalize/dir1/");

  assertEquals("tmp/testNormalize",
      p.subpath(0, p.getNameCount() - 1).toString());
}
 
Example 32
Project: Openfire   File: XMLProperties.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new XMLPropertiesTest object.
 *
 * @param file the file that properties should be read from and written to.
 * @throws IOException if an error occurs loading the properties.
 */
public XMLProperties(Path file) throws IOException {
    this.file = file;
    if (Files.notExists(file)) {
        // Attempt to recover from this error case by seeing if the
        // tmp file exists. It's possible that the rename of the
        // tmp file failed the last time Jive was running,
        // but that it exists now.
        Path tempFile;
        tempFile = file.getParent().resolve(file.getFileName() + ".tmp");
        if (Files.exists(tempFile)) {
            Log.error("WARNING: " + file.getFileName() + " was not found, but temp file from " +
                    "previous write operation was. Attempting automatic recovery." +
                    " Please check file for data consistency.");
            Files.move(tempFile, file, StandardCopyOption.REPLACE_EXISTING);
        }
        // There isn't a possible way to recover from the file not
        // being there, so throw an error.
        else {
            throw new NoSuchFileException("XML properties file does not exist: "
                    + file.getFileName());
        }
    }
    // Check read and write privs.
    if (!Files.isReadable(file)) {
        throw new IOException("XML properties file must be readable: " + file.getFileName());
    }
    if (!Files.isWritable(file)) {
        throw new IOException("XML properties file must be writable: " + file.getFileName());
    }

    try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
         buildDoc(reader);
    }
}
 
Example 33
Project: qpid-broker-j   File: AuthenticationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException
{
    final byte[] crlBytes = Files.readAllBytes(crlPath);
    response.setStatus(HttpServletResponse.SC_OK);
    try (final OutputStream responseBody = response.getOutputStream())
    {
        responseBody.write(crlBytes);
    }
}
 
Example 34
Project: wildfly-core   File: AddUserTestCase.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private static Properties load(final Path file) throws IOException {
    final Properties result = new Properties();
    try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
        result.load(reader);
    }
    return result;
}
 
Example 35
Project: batfish   File: WorkMgr.java    License: Apache License 2.0 5 votes vote down vote up
public SortedSet<String> listNetworks(String apiKey) {
  Path networksDir = Main.getSettings().getContainersLocation();
  if (!Files.exists(networksDir)) {
    networksDir.toFile().mkdirs();
  }
  SortedSet<String> authorizedNetworks =
      _idManager.listNetworks().stream()
          .filter(network -> Main.getAuthorizer().isAccessibleNetwork(apiKey, network, false))
          .collect(toCollection(TreeSet::new));
  return authorizedNetworks;
}
 
Example 36
Project: lucene-solr   File: FilesystemResourceLoader.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public InputStream openResource(String resource) throws IOException {
  try {
    return Files.newInputStream(baseDirectory.resolve(resource));
  } catch (FileNotFoundException | NoSuchFileException fnfe) {
    return delegate.openResource(resource);
  }
}
 
Example 37
Project: bazel   File: VanillaJavaBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDeferredDiagnostics() throws Exception {
  Path b = temporaryFolder.newFile("B.java").toPath();
  Path a = temporaryFolder.newFile("A.java").toPath();
  Path output = temporaryFolder.newFile("out.jar").toPath();
  Files.write(
      b,
      ImmutableList.of(
          "@Deprecated", //
          "class B {}"),
      UTF_8);
  Files.write(
      a,
      ImmutableList.of(
          "import java.util.*;", //
          "public class A {",
          "  sun.misc.Unsafe theUnsafe;",
          "  B b;",
          "  List l = new ArrayList<>();",
          "}"),
      UTF_8);

  VanillaJavaBuilderResult result =
      run(
          ImmutableList.of(
              "--sources",
              a.toString(),
              b.toString(),
              "--output",
              output.toString(),
              "--bootclasspath",
              Paths.get(System.getProperty("java.home")).resolve("lib/rt.jar").toString(),
              "--tempdir",
              temporaryFolder.newFolder().toString(),
              "--classdir",
              temporaryFolder.newFolder().toString()));

  assertThat(result.output()).isEmpty();
  assertThat(result.ok()).isTrue();
}
 
Example 38
Project: Vert.X-generator   File: IoUtil.java    License: MIT License 5 votes vote down vote up
/**
 * 将字符串存储为文件
 * 
 * @param path
 * @param materi
 * @param codeFormat
 * @throws Exception
 */
public static void StrToFile(Path path, String materi, String codeFormat) throws Exception {
	OutputStream out = Files.newOutputStream(path, StandardOpenOption.CREATE);
	OutputStreamWriter writer = new OutputStreamWriter(out, codeFormat);
	writer.write(materi);
	writer.flush();
	out.close();
	writer.close();
}
 
Example 39
Project: genie   File: CacheGenieFileTransferService.java    License: Apache License 2.0 5 votes vote down vote up
protected Path createDirectories(final String path) throws GenieException {
    try {
        final File pathFile = new File(new URI(path).getPath());
        final Path result = pathFile.toPath();
        if (!Files.exists(result)) {
            Files.createDirectories(result);
        }
        return result;
    } catch (Exception e) {
        throw new GenieServerException("Failed creating the cache location " + path, e);
    }
}
 
Example 40
Project: openjdk-jdk9   File: FactoryFinder.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static Object fromJDKProperties(String factoryId,
                                        String fallbackClassName,
                                        ClassLoader classLoader) {
    Path path = null;
    try {
        String JAVA_HOME = System.getProperty("java.home");
        path = Paths.get(JAVA_HOME, "conf", "jaxws.properties");

        // to ensure backwards compatibility
        if (!Files.exists(path)) {
            path = Paths.get(JAVA_HOME, "lib", "jaxws.properties");
        }

        if (Files.exists(path)) {
            Properties props = new Properties();
            try (InputStream inStream = Files.newInputStream(path)) {
                props.load(inStream);
            }
            String factoryClassName = props.getProperty(factoryId);
            return ServiceLoaderUtil.newInstance(factoryClassName,
                    fallbackClassName, classLoader, EXCEPTION_HANDLER);
        }
    } catch (Exception ignored) {
        logger.log(Level.SEVERE, "Error reading JAX-WS configuration from ["  + path +
                "] file. Check it is accessible and has correct format.", ignored);
    }
    return null;
}