Java 类java.nio.file.Paths 实例源码
项目:RDF2PT
文件:DefaultIRIConverterPortuguese.java
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));
}
项目:flow-platform
文件:LogEventHandler.java
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);
}
项目:openjdk-jdk10
文件:CLICompatibility.java
@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);
}
项目:MantaroRPG
文件:SimpleFileDataManager.java
@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("//"));
}
项目:jpeek
文件:ResultsTest.java
@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")
);
}
项目:IO
文件:AdvancedOptions.java
/**
* 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;
}
项目:rebazer
文件:BitbucketServiceTest.java
@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 );
}
项目:web3j-maven-plugin
文件:IssueITest.java
@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"));
}
项目:Java-9-Programming-Blueprints
文件:FileFinder.java
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);
}
}
项目:litiengine
文件:EditorScreen.java
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);
}
}
}
项目:openjdk-jdk10
文件:WrongLNTForLambdaTest.java
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);
}
项目:uroborosql
文件:AuditLogSqlFilterTest.java
@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)));
}
项目:APCSAB
文件:AreaFill_shell.java
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;
}
}
项目:displaydirect
文件:PlanningLoader.java
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()));
}
项目:openjdk-jdk10
文件:CLICompatibility.java
@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);
}
项目:web3j-maven-plugin
文件:JavaClassGeneratorITest.java
@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());
}
项目:pdf-converter
文件:ZipCreator.java
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);
}
});
}
}
项目:smart-testing
文件:ClassDependenciesGraphTest.java
@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");
}
项目:openjdk-jdk10
文件:GraalDebugHandlersFactoryTest.java
@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);
}
}
项目:TechComparisonProject
文件:Server.java
/**
* 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() );
}
}
}
项目:jdk8u-jdk
文件:FinalizeOverride.java
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);
}
项目:openjdk-jdk10
文件:Correctness.java
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;
}
}
项目:openjdk-jdk10
文件:GetResourceAsStream.java
/**
* 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);
}
项目:oscm
文件:EclipseProjectReader.java
/**
* 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;
}
项目:RollenspielAlexaSkill
文件:SimpleDBConnectionFactory.java
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;
}
项目:CloudNet
文件:MasterTemplateLoader.java
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;
}
项目:S3Mock
文件:FileStoreTest.java
@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));
}
项目:openjdk-jdk10
文件:AnnotatedExtendsTest.java
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);
}
项目:log4j2-elasticsearch
文件:IndexTemplate.java
private String loadFileSystemResource() {
try {
return new String(Files.readAllBytes(Paths.get(path)));
} catch (IOException e){
throw new ConfigurationException(e.getMessage(), e);
}
}
项目:jdk8u-jdk
文件:CopyClassFile.java
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);
}
}
项目:GuildBot
文件:GuildBot.java
@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);
}
项目:personium-core
文件:CellImportResource.java
/**
* 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();
}
项目:S3Mock
文件:FileStoreTest.java
@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));
}
项目:jfrog-idea-plugin
文件:NpmScanManager.java
/**
* 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);
};
}
项目:openjdk-jdk10
文件:JAXPTestUtilities.java
/**
* 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;
}
项目:openjdk-jdk10
文件:PatchSystemModules.java
@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(), ".");
}
项目:openjdk-jdk10
文件:FailOverDirectExecutionControlTest.java
@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));
}
项目:junit-extensions
文件:TemporaryFolderExtensionFieldTest.java
@AfterAll
public static void allTemporaryFilesAreDeleted() {
List<String> existingFiles =
temporaryFilePaths
.stream()
.filter(temporaryFilePath -> Files.exists(Paths.get(temporaryFilePath)))
.collect(Collectors.toList());
assertThat(existingFiles, empty());
}
项目:Cognizant-Intelligent-Test-Scripter
文件:AppResourcePath.java
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;
}
项目:jdk8u-jdk
文件:LogGeneratedClassesTest.java
@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");
}