java.nio.file.Files Java Examples
The following examples show how to use
java.nio.file.Files.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CompressingTempFileStore.java From nexus-repository-apt with Eclipse Public License 1.0 | 7 votes |
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 #2
Source File: RustBinaryIntegrationTest.java From buck with Apache License 2.0 | 6 votes |
@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
Source File: RegexBasedPartitionedRetrieverTest.java From incubator-gobblin with Apache License 2.0 | 6 votes |
@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
Source File: FileActionLogger.java From LuckPerms with MIT License | 6 votes |
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
Source File: QuteProcessor.java From quarkus with Apache License 2.0 | 6 votes |
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
Source File: FieldSetAccessibleTest.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
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
Source File: MMapOfflineDb.java From ipst with Mozilla Public License 2.0 | 6 votes |
@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
Source File: SerialKillerTest.java From SerialKiller with Apache License 2.0 | 6 votes |
@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
Source File: PackagedProgramTest.java From flink with Apache License 2.0 | 6 votes |
@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
Source File: DumpPlatformClassPath.java From bazel with Apache License 2.0 | 6 votes |
/** 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
Source File: PersistTestModuleBuilderTest.java From che with Eclipse Public License 2.0 | 6 votes |
@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
Source File: TestHostConfigAutomaticDeployment.java From Tomcat8-Source-Read with MIT License | 6 votes |
@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
Source File: SesarSample.java From ET_Redux with Apache License 2.0 | 6 votes |
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
Source File: Font.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
/** * 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
Source File: RevertSamSpark.java From gatk with BSD 3-Clause "New" or "Revised" License | 6 votes |
@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
Source File: PathOperationsTest.java From ph-commons with Apache License 2.0 | 6 votes |
@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
Source File: SubmitAndSyncUnicodeFileTypeOnUnicodeEnabledServerTest.java From p4ic4idea with Apache License 2.0 | 6 votes |
@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
Source File: StandardDirectoryFactory.java From lucene-solr with Apache License 2.0 | 6 votes |
/** * 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
Source File: AppleLibraryIntegrationTest.java From buck with Apache License 2.0 | 6 votes |
@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
Source File: TestExecuteStreamCommand.java From nifi with Apache License 2.0 | 6 votes |
@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
Source File: KnowNERCorpusCheckerIntegrationTest.java From ambiverse-nlu with Apache License 2.0 | 6 votes |
@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
Source File: ConversionTest.java From carbon-kernel with Apache License 2.0 | 6 votes |
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
Source File: KeyStoresTestCase.java From wildfly-core with GNU Lesser General Public License v2.1 | 5 votes |
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 #24
Source File: AbstractLog4j1ConfigurationConverterTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@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 #25
Source File: RouteFragmentTest.java From open with GNU General Public License v3.0 | 5 votes |
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 #26
Source File: MostFiles.java From buck with Apache License 2.0 | 5 votes |
/** 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 #27
Source File: X509CertRequestTest.java From athenz with Apache License 2.0 | 5 votes |
@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 #28
Source File: FolderBroker.java From geoportal-server-harvester with Apache License 2.0 | 5 votes |
@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 #29
Source File: HighLevelApi.java From java-dcp-client with Apache License 2.0 | 5 votes |
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 #30
Source File: TestPath.java From jsr203-hadoop with Apache License 2.0 | 5 votes |
@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()); }