下面列出了org.junit.runners.Parameterized.Parameters#java.nio.file.Files 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
}
/**
* 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();
}
@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")));
}
@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;
}
});
}
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();
}
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);
}
}
}
}
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();
}
@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;
}
@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());
}
}
@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()));
}
/** 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);
}
});
}
}
@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));
}
@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);
}
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;
}
/**
* 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;
}
@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;
}
@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)
{}
}
@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
);
}
/**
* 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);
}
@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));
}
@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());
}
@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());
}
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;
}
}
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));
}
@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);
}
}
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();
}
/** 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();
}
}
}
@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));
}
@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()));
}
}
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.");
}