java.nio.file.Path Java Examples

The following examples show how to use java.nio.file.Path. 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: DefaultProjectSupplierTest.java    From helidon-build-tools with Apache License 2.0 6 votes vote down vote up
@Test
void testUpToDate() throws Exception {
    final Path projectDir = TestFiles.helidonSeProject();
    final TestMonitor monitor = new TestMonitor(1);
    final BuildExecutor executor = new ForkedMavenExecutor(projectDir, monitor, 30);
    final ProjectSupplier supplier = new DefaultProjectSupplier();
    final Project project = supplier.newProject(executor, false, true,0);
    assertThat(project, is(not(nullValue())));
    assertThat(project.isBuildUpToDate(), is(true));
    assertThat(monitor.buildStart(0), is(false));
    assertThat(project, is(not(nullValue())));
    MatcherAssert.assertThat(project.root().directoryType(), Matchers.is(DirectoryType.Project));
    assertThat(project.root().path(), is(projectDir));
    final List<BuildComponent> components = project.components();
    assertThat(components, is(not(nullValue())));
    assertThat(components.size(), is(2));
    assertThat(components.get(0).sourceRoot().path().toString(), endsWith("src/main/java"));
    assertThat(components.get(0).outputRoot().path().toString(), endsWith("target/classes"));
    assertThat(components.get(1).sourceRoot().path().toString(), endsWith("src/main/resources"));
    assertThat(components.get(1).outputRoot().path().toString(), endsWith("target/classes"));
    assertThat(components.get(1).outputRoot(), is(not(components.get(0).outputRoot())));

    assertThat(project.classpath().size(), is(greaterThan(2)));
    assertThat(project.mainClassName(), is("io.helidon.examples.se.Main"));
}
 
Example #2
Source File: SdkInstaller.java    From appengine-plugins-core with Apache License 2.0 6 votes vote down vote up
/**
 * Configure and create a new Installer instance.
 *
 * @param managedSdkDirectory home directory of google cloud java managed cloud SDKs
 * @param version version of the Cloud SDK we want to install
 * @param osInfo target operating system for installation
 * @param userAgentString user agent string for https requests
 * @param usageReporting enable client side usage reporting on gcloud
 * @return a new configured Cloud SDK Installer
 */
public static SdkInstaller newInstaller(
    Path managedSdkDirectory,
    Version version,
    OsInfo osInfo,
    String userAgentString,
    boolean usageReporting) {
  DownloaderFactory downloaderFactory = new DownloaderFactory(userAgentString);
  ExtractorFactory extractorFactory = new ExtractorFactory();

  InstallerFactory installerFactory =
      version == Version.LATEST ? new InstallerFactory(osInfo, usageReporting) : null;

  FileResourceProviderFactory fileResourceProviderFactory =
      new FileResourceProviderFactory(version, osInfo, managedSdkDirectory);

  return new SdkInstaller(
      fileResourceProviderFactory, downloaderFactory, extractorFactory, installerFactory);
}
 
Example #3
Source File: CockpitDataExportJob.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @throws JobExecutionException
 */
private void createMetaFile() throws JobExecutionException {
	java.nio.file.Path metadataFile = ExportPathBuilder.getInstance().getPerJobIdMetadataFile(resourcePath, userProfile, id);

	try {
		String docLabel = documentExportConf.getDocumentLabel();

		ExportMetadata exportMetadata = new ExportMetadata();
		exportMetadata.setId(id);
		exportMetadata.setDataSetName(docLabel);
		exportMetadata.setFileName(docLabel + "." + extension());
		exportMetadata.setMimeType(mime());
		exportMetadata.setStartDate(Calendar.getInstance(locale).getTime());

		ExportMetadata.writeToJsonFile(exportMetadata, metadataFile);
	} catch (Exception e) {

		deleteJobDirectory();

		String msg = String.format("Error creating file \"%s\"!", metadataFile);

		throw new JobExecutionException(msg, e);
	}
}
 
Example #4
Source File: JimfsFileSystemProvider.java    From jimfs with Apache License 2.0 6 votes vote down vote up
@Override
public FileSystem newFileSystem(Path path, Map<String, ?> env) throws IOException {
  JimfsPath checkedPath = checkPath(path);
  checkNotNull(env);

  URI pathUri = checkedPath.toUri();
  URI jarUri = URI.create("jar:" + pathUri);

  try {
    // pass the new jar:jimfs://... URI to be handled by ZipFileSystemProvider
    return FileSystems.newFileSystem(jarUri, env);
  } catch (Exception e) {
    // if any exception occurred, assume the file wasn't a zip file and that we don't support
    // viewing it as a file system
    throw new UnsupportedOperationException(e);
  }
}
 
Example #5
Source File: FtModel.java    From djl with Apache License 2.0 6 votes vote down vote up
private Path findModelFile(String prefix) {
    Path modelFile = modelDir.resolve(prefix);
    if (Files.notExists(modelFile) || !Files.isRegularFile(modelFile)) {
        if (prefix.endsWith(".ftz") || prefix.endsWith(".bin")) {
            return null;
        }
        modelFile = modelDir.resolve(prefix + ".ftz");
        if (Files.notExists(modelFile) || !Files.isRegularFile(modelFile)) {
            modelFile = modelDir.resolve(prefix + ".bin");
            if (Files.notExists(modelFile) || !Files.isRegularFile(modelFile)) {
                return null;
            }
        }
    }
    return modelFile;
}
 
Example #6
Source File: HistoryTreeSegmentStore.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Create a history tree from an existing file
 *
 * @param treeFile
 *            Filename/location of the history we want to load
 * @param intervalReader
 *            Factory to read history tree objects from the backend
 * @param version
 *            The version number of the reader/writer
 * @return The new history tree
 * @throws IOException
 *             If we can't read the file, if it doesn't exist, is not
 *             recognized, or if the version of the file does not match the
 *             expected providerVersion.
 */
private SegmentHistoryTree<E> createHistoryTree(Path treeFile, IHTIntervalReader<@NonNull E> intervalReader, int version) throws IOException {
    try {
        if (Files.exists(treeFile)) {
            SegmentHistoryTree<E> sht = new SegmentHistoryTree<>(NonNullUtils.checkNotNull(treeFile.toFile()), version, intervalReader);
            fFinishedBuilding = true;
            return sht;
        }
    } catch (IOException e) {
        /**
         * Couldn't create the history tree with this file, just fall back
         * to a new history tree
         */
    }

    return new SegmentHistoryTree<>(NonNullUtils.checkNotNull(treeFile.toFile()),
            BLOCK_SIZE,
            MAX_CHILDREN,
            version,
            0,
            intervalReader);
}
 
Example #7
Source File: DeploymentOperationsTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void cleanUp() {
    ModelNode op = new ModelNode();
    op.get(OP).set(READ_RESOURCE_OPERATION);
    op.get(OP_ADDR).set(DEPLOYMENT, TEST_DEPLOYMENT_NAME);
    ModelNode result = awaitOperationExecutionAndReturnResult(op);
    if (Operations.isSuccessfulOutcome(result)) {
        undeployAndRemoveDeployment(TEST_DEPLOYMENT_NAME);
    }

    String jbossBaseDir = System.getProperty("jboss.home");
    Assert.assertNotNull(jbossBaseDir);
    Path dataDir = new File(jbossBaseDir).toPath().resolve("standalone").resolve("data");
    if (Files.exists(dataDir)) { cleanFile(dataDir.resolve("managed-exploded").toFile()); }
    File archivesDir = new File("target", "archives");
    if (Files.exists(archivesDir.toPath())) { cleanFile(archivesDir); }
}
 
Example #8
Source File: FileSystemStorageService.java    From tensorflow-java-examples-spring with Do What The F*ck You Want To Public License 6 votes vote down vote up
@Override
public Resource loadAsResource(String filename) {
    try {
        Path file = load(filename);
        Resource resource = new UrlResource(file.toUri());
        if (resource.exists() || resource.isReadable()) {
            return resource;
        }
        else {
            throw new StorageFileNotFoundException(
                    "Could not read file: " + filename);

        }
    }
    catch (MalformedURLException e) {
        throw new StorageFileNotFoundException("Could not read file: " + filename, e);
    }
}
 
Example #9
Source File: DesugarTask.java    From javafxmobile-plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void processSingle(
        @NonNull Path input, @NonNull Path output, @NonNull Set<? super QualifiedContent.Scope> scopes)
        throws Exception {
    waitableExecutor.execute(
            () -> {
                if (output.toString().endsWith(SdkConstants.DOT_JAR)) {
                    Files.createDirectories(output.getParent());
                } else {
                    Files.createDirectories(output);
                }

                FileCache cacheToUse;
                if (Files.isRegularFile(input)
                        && Objects.equals(
                        scopes, Collections.singleton(QualifiedContent.Scope.EXTERNAL_LIBRARIES))) {
                    cacheToUse = userCache;
                } else {
                    cacheToUse = null;
                }

                processUsingCache(input, output, cacheToUse);
                return null;
            });
}
 
Example #10
Source File: FileSystemTestUtil.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
/**
 * Creates a file system tree in a temporary directory.
 * @param entriesToCreate a list of paths to create. If path ends with '/', it will become a directory; otherwise it
 *                        will become a file
 * @return a path to the root of the file system tree.
 */
public static Path createTempFileSystem(String... entriesToCreate) throws IOException {
    Path rootDirectory = Files.createTempDirectory("azuredevopstest");
    for (String relativePath : entriesToCreate) {
        Path resultingPath = rootDirectory.resolve(relativePath);
        Path directoryPath = resultingPath.getParent();

        Files.createDirectories(directoryPath);
        if (relativePath.endsWith("/")) {
            Files.createDirectories(resultingPath);
        } else {
            //noinspection ResultOfMethodCallIgnored
            resultingPath.toFile().createNewFile();
        }
    }

    return rootDirectory;
}
 
Example #11
Source File: RoutingConfigLoader.java    From curiostack with MIT License 6 votes vote down vote up
Map<Route, WebClient> load(Path configPath) {
  final RoutingConfig config;
  try {
    config = OBJECT_MAPPER.readValue(configPath.toFile(), RoutingConfig.class);
  } catch (IOException e) {
    throw new UncheckedIOException("Could not read routing config.", e);
  }

  Map<String, WebClient> clients =
      config.getTargets().stream()
          .collect(
              toImmutableMap(
                  Target::getName,
                  t ->
                      clientBuilderFactory
                          .create(t.getName(), addSerializationFormat(t.getUrl()))
                          .build(WebClient.class)));

  return config.getRules().stream()
      .collect(
          toImmutableMap(
              r -> Route.builder().path(r.getPathPattern()).build(),
              r -> clients.get(r.getTarget())));
}
 
Example #12
Source File: UstDebugInfoSymbolProviderPreferencePage.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Grey out the relevant controls if the checkbox is unchecked, and vice
 * versa. Also verify if the current settings are valid, and update the
 * window error message if needed.
 */
private void updateContents() {
    boolean useCustomDirEnabled = getCurrentCheckBoxState();
    checkNotNull(fCustomDirectoryPath).setEnabled(useCustomDirEnabled);
    checkNotNull(fBrowseButton).setEnabled(useCustomDirEnabled);
    checkNotNull(fClearButton).setEnabled(useCustomDirEnabled);

    String errorMessage = null;

    if (useCustomDirEnabled) {
        String pathPrefix = getCurrentPathPrefix();
        Path path = Paths.get(pathPrefix);
        if (pathPrefix.equals("") || !Files.isDirectory(path)) { //$NON-NLS-1$
            errorMessage = Messages.PreferencePage_ErrorDirectoryDoesNotExists;
        }
    }
    setErrorMessage(errorMessage);
    setValid(errorMessage == null);
}
 
Example #13
Source File: FileCollector.java    From javageci with Apache License 2.0 6 votes vote down vote up
/**
     * <p>Collect the source files from the {@code dir} directory, create {@link javax0.geci.api.Source Source} objects
     * that encapsulate the file and add the new object to the set of sources.</p>
     *
     * @param onlySet   only the files are processed that match some element of this set unless this set is empty. In
     *                  this case the set is not consulted.
     * @param ignoreSet
     * @param dir
     * @throws IOException
     */
    private void collectInputDirectory(final Set<Predicate<Path>> onlySet,
                                       final Set<Predicate<Path>> ignoreSet,
                                       final String dir
    ) throws IOException {
        getAllRegularFiles(dir)
                .peek(s -> Tracer.push("File", "'" + s + "' was found"))
//
                .peek(s -> Tracer.push("Only", "Checking predicates"))
                .filter(path -> pathIsMatchingOnlySet(onlySet, path))
                .peek(s -> Tracer.pop())
//
                .peek(s -> Tracer.push("Ignore", "Checking predicates"))
                .filter(path -> pathIsNotIgnored(ignoreSet, path))
                .peek(s -> Tracer.pop())
//
                .peek(s -> Tracer.pop())
                .forEach(path -> sources.add(new Source(this, dir, path)));
    }
 
Example #14
Source File: DependencyResolver.java    From streamsx.topology with Apache License 2.0 6 votes vote down vote up
public void addJarDependency(BOperatorInvocation op, Class<?> clazz) {

        CodeSource thisCodeSource = this.getClass().getProtectionDomain()
                .getCodeSource();

        CodeSource source = clazz.getProtectionDomain().getCodeSource();
        if (null == source || thisCodeSource.equals(source)) {
            return;
        }
        
        Path absolutePath = null;
        try {
            absolutePath = Paths.get(source.getLocation().toURI()).toAbsolutePath();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        
        if (operatorToJarDependencies.containsKey(op)) {
            operatorToJarDependencies.get(op).add(absolutePath);
        } else {
            operatorToJarDependencies.put(op, new HashSet<Path>());
            operatorToJarDependencies.get(op).add(absolutePath);
        }
    }
 
Example #15
Source File: IjSourceRootSimplifier.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * Walks the trie of paths attempting to merge all of the children of the current path into
 * itself.
 *
 * <p>If a parent folder is present then the merge happens only for children folders that can be
 * merged into a parent folder. Otherwise a parent folder is created and matching children
 * folders are merged into it.
 *
 * @param currentPath current path
 * @return Optional.of(a successfully merged folder) or absent if merging did not succeed.
 */
private Optional<IjFolder> walk(Path currentPath) {
  ImmutableList<Optional<IjFolder>> children =
      StreamSupport.stream(tree.getOutgoingNodesFor(currentPath).spliterator(), false)
          .map(this::walk)
          .collect(ImmutableList.toImmutableList());

  ImmutableList<IjFolder> presentChildren =
      children.stream()
          .filter(Optional::isPresent)
          .map(Optional::get)
          .collect(ImmutableList.toImmutableList());

  IjFolder currentFolder = mergePathsMap.get(currentPath);
  if (presentChildren.isEmpty()) {
    return Optional.ofNullable(currentFolder);
  }

  boolean hasNonPresentChildren = presentChildren.size() != children.size();

  return tryMergingParentAndChildren(
      currentPath, currentFolder, presentChildren, hasNonPresentChildren);
}
 
Example #16
Source File: MavenConfigTestCase.java    From galleon with Apache License 2.0 6 votes vote down vote up
@Test
public void testSettingsFile() throws Exception {
    MavenConfig config = cli.getSession().getPmConfiguration().getMavenConfig();
    Path p = cli.newDir("foo", true);
    Path settings = p.resolve("settings.xml");
    Files.createFile(settings);
    Path existingSettings = config.getSettings();
    Assert.assertNull(existingSettings);
    cli.execute("maven set-settings-file " + settings.toFile().getAbsolutePath());
    Assert.assertEquals(settings, config.getSettings());
    Assert.assertEquals(settings, Configuration.parse().getMavenConfig().getSettings());

    cli.execute("maven get-info");
    Assert.assertTrue(cli.getOutput().contains(settings.toFile().getAbsolutePath()));

    cli.execute("maven reset-settings-file");
    Assert.assertNull(config.getSettings());
    Assert.assertNull(Configuration.parse().getMavenConfig().getSettings());
}
 
Example #17
Source File: FileObjSymlinkTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testReadSymbolicLinkRelative() throws IOException {
    if (!checkSymlinksSupported()) {
        return;
    }
    File dir = getWorkDir();
    File folder = new File(dir, "folder");
    File link = new File(dir, "link");
    folder.mkdir();
    Path lp = Files.createSymbolicLink(link.toPath(), Paths.get("folder"));
    assertNotNull(lp);
    FileObject linkFO = FileUtil.toFileObject(link);
    assertNotNull(linkFO);
    FileObject dataFO = linkFO.readSymbolicLink();
    assertNotSame(linkFO, dataFO);
    assertNotNull(dataFO);
    assertEquals("folder", dataFO.getNameExt());
}
 
Example #18
Source File: TestServerRule.java    From nomulus with Apache License 2.0 6 votes vote down vote up
private TestServerRule(
    ImmutableMap<String, Path> runfiles,
    ImmutableList<Route> routes,
    ImmutableList<Class<? extends Filter>> filters,
    ImmutableList<Fixture> fixtures,
    String email,
    Optional<String> gaeUserId) {
  this.runfiles = runfiles;
  this.routes = routes;
  this.filters = filters;
  this.fixtures = fixtures;
  // We create an GAE-Admin user, and then use AuthenticatedRegistrarAccessor.bypassAdminCheck to
  // choose whether the user is an admin or not.
  this.appEngineRule =
      AppEngineRule.builder()
          .withDatastoreAndCloudSql()
          .withLocalModules()
          .withUrlFetch()
          .withTaskQueue()
          .withUserService(
              UserInfo.createAdmin(email, gaeUserId.orElse(THE_REGISTRAR_GAE_USER_ID)))
          .build();
}
 
Example #19
Source File: Resources.java    From es6draft with MIT License 5 votes vote down vote up
public boolean matches(Path file) {
    if (!matches(excludeMatchers, file) && matches(includeMatchers, file)) {
        if (!matches(excludeFiles, file.getFileName())
                && (includeDirs.isEmpty()
                        || (file.getParent() != null && matches(includeDirs, file.getParent())))
                && (includeFiles.isEmpty() || matches(includeFiles, file.getFileName()))) {
            return true;
        }
    }
    return false;
}
 
Example #20
Source File: WriteActionTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void setsFileExecutable() throws ActionCreationException, IOException, EvalException {
  Artifact output1 = runner.declareArtifact(Paths.get("foo").resolve("bar1"));
  Artifact output2 = runner.declareArtifact(Paths.get("foo").resolve("bar2"));
  ImmutableSortedSet<OutputArtifact> outputs =
      ImmutableSortedSet.of(output1.asOutputArtifact(), output2.asOutputArtifact());

  TestActionExecutionRunner.ExecutionDetails<WriteAction> result =
      runner.runAction(
          new WriteAction(
              runner.getRegistry(), ImmutableSortedSet.of(), outputs, "foobar", true));

  Path outputPath1 =
      Objects.requireNonNull(output1.asBound().asBuildArtifact())
          .getSourcePath()
          .getResolvedPath();
  Path outputPath2 =
      Objects.requireNonNull(output2.asBound().asBuildArtifact())
          .getSourcePath()
          .getResolvedPath();

  assertTrue(result.getResult().isSuccess());
  assertEquals(
      Optional.of("foobar"),
      projectFilesystem.readFileIfItExists(projectFilesystem.resolve(outputPath1)));
  assertEquals(
      Optional.of("foobar"),
      projectFilesystem.readFileIfItExists(projectFilesystem.resolve(outputPath2)));
  assertTrue(outputPath1.endsWith(Paths.get("foo", "bar1")));
  assertTrue(outputPath2.endsWith(Paths.get("foo", "bar2")));
  assertTrue(projectFilesystem.isExecutable(outputPath1));
  assertTrue(projectFilesystem.isExecutable(outputPath2));
}
 
Example #21
Source File: ResourceLocatorTest.java    From flink-statefun with Apache License 2.0 5 votes vote down vote up
@Test
public void absolutePathExample() throws IOException {
  Path modulePath = createDirectoryWithAFile("some-module", "module.yaml").resolve("module.yaml");

  URL url = ResourceLocator.findNamedResource(modulePath.toUri().toString());

  assertThat(url, is(url(modulePath)));
}
 
Example #22
Source File: OutputDirTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testError(Path base) throws Exception {
    String log = new JavacTask(tb)
            .options("-XDrawDiagnostics",
                    "--module-source-path", src.toString())
            .files(findJavaFiles(src))
            .run(Task.Expect.FAIL)
            .writeAll()
            .getOutput(Task.OutputKind.DIRECT);

    if (!log.contains("- compiler.err.no.output.dir"))
        throw new Exception("expected output not found");
}
 
Example #23
Source File: DependenciesTest.java    From turbine with Apache License 2.0 5 votes vote down vote up
void writeDeps(Path path, ImmutableMap<String, DepsProto.Dependency.Kind> deps)
    throws IOException {
  DepsProto.Dependencies.Builder builder =
      DepsProto.Dependencies.newBuilder().setSuccess(true).setRuleLabel("//test");
  for (Map.Entry<String, DepsProto.Dependency.Kind> e : deps.entrySet()) {
    builder.addDependency(
        DepsProto.Dependency.newBuilder().setPath(e.getKey()).setKind(e.getValue()));
  }
  try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(path))) {
    builder.build().writeTo(os);
  }
}
 
Example #24
Source File: XcodeNativeTargetGenerator.java    From buck with Apache License 2.0 5 votes vote down vote up
private ImmutableList<BuildTarget> generateAppleBinaryTarget(
    ImmutableXCodeNativeTargetAttributes.Builder nativeTargetBuilder,
    ImmutableSet.Builder<BuildTarget> requiredBuildTargetsBuilder,
    ImmutableSet.Builder<Path> xcconfigPathsBuilder,
    ImmutableSet.Builder<String> targetConfigNamesBuilder,
    HeaderSearchPathAttributes headerSearchPathAttributes,
    TargetNode<AppleNativeTargetDescriptionArg> targetNode)
    throws IOException {
  ImmutableList<BuildTarget> result =
      generateBinaryTarget(
          nativeTargetBuilder,
          requiredBuildTargetsBuilder,
          xcconfigPathsBuilder,
          targetConfigNamesBuilder,
          headerSearchPathAttributes,
          Optional.empty(),
          targetNode,
          "%s",
          Optional.empty(),
          /* includeFrameworks */ true,
          AppleResources.collectDirectResources(targetGraph, targetNode),
          AppleBuildRules.collectDirectAssetCatalogs(targetGraph, targetNode),
          ImmutableSet.of(),
          ImmutableSet.of(),
          Optional.empty());

  LOG.debug(
      "Generated Apple binary target %s", targetNode.getBuildTarget().getFullyQualifiedName());
  return result;
}
 
Example #25
Source File: ToolPath.java    From protools with Apache License 2.0 5 votes vote down vote up
public static String getContentType(Path path) throws IOException {
    String type;
    URL u = path.toUri().toURL();
    URLConnection uc = u.openConnection();
    type = uc.getContentType();
    return type;
}
 
Example #26
Source File: AnnotationsAreNotCopiedToBridgeMethodsTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
void checkClassFile(final Path cfilePath) throws Exception {
    ClassFile classFile = ClassFile.read(
            new BufferedInputStream(Files.newInputStream(cfilePath)));
    for (Method method : classFile.methods) {
        if (method.access_flags.is(AccessFlags.ACC_BRIDGE)) {
            checkForAttr(method.attributes,
                    "Annotations hasn't been copied to bridge method",
                    Attribute.RuntimeVisibleAnnotations,
                    Attribute.RuntimeVisibleParameterAnnotations);
        }
    }
}
 
Example #27
Source File: SecretsPropertySourceLocator.java    From spring-cloud-kubernetes with Apache License 2.0 5 votes vote down vote up
private void putAll(Path path, CompositePropertySource composite) {
	try {

		Files.walk(path).filter(Files::isRegularFile)
				.forEach(p -> readFile(p, composite));
	}
	catch (IOException e) {
		LOG.warn("Error walking properties files", e);
	}
}
 
Example #28
Source File: JarUploadHandlerTest.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Test
public void testRejectNonJarFiles() throws Exception {
	final Path uploadedFile = Files.createFile(jarDir.resolve("katrin.png"));
	final HandlerRequest<EmptyRequestBody, EmptyMessageParameters> request = createRequest(uploadedFile);

	try {
		jarUploadHandler.handleRequest(request, mockDispatcherGateway).get();
		fail("Expected exception not thrown.");
	} catch (final ExecutionException e) {
		final Throwable throwable = ExceptionUtils.stripCompletionException(e.getCause());
		assertThat(throwable, instanceOf(RestHandlerException.class));
		final RestHandlerException restHandlerException = (RestHandlerException) throwable;
		assertThat(restHandlerException.getHttpResponseStatus(), equalTo(HttpResponseStatus.BAD_REQUEST));
	}
}
 
Example #29
Source File: JavaClassGeneratorMojo.java    From web3j-maven-plugin with Apache License 2.0 5 votes vote down vote up
private void generatedBin(Map<String, String> contractResult, String contractName) {
    if (!StringUtils.containsIgnoreCase(outputFormat, "bin")) {
        return;
    }

    String binJson = contractResult.get(SolidityCompiler.Options.BIN.getName());
    try {
        String filename = contractName + ".bin";
        Path path = createPath(StringUtils.defaultString(outputDirectory.getBin(), sourceDestination));

        Files.write(Paths.get(path.toString(), filename), binJson.getBytes());
    } catch (IOException e) {
        getLog().error("Could not build bin file for contract '" + contractName + "'", e);
    }
}
 
Example #30
Source File: StaticLambdaClassesFinder.java    From Concurnas with MIT License 5 votes vote down vote up
private void buildGraphAndGetDirectStaticLambdas(Path mod, String fname, int idx, StaticLambdaAndGraphBuilder graphBuilder) throws IOException {
	List<Path> entires = Files.walk(mod).filter(a -> !Files.isDirectory(a) ).collect(Collectors.toList());
	
	String shortname = mod.getFileName().toString();
	PctDoer tracker = new PctDoer(pt, entires.size(), 2, shortname + " - ", idx);
	
	Map<String, String> env = new HashMap<>(); 
       env.put("create", "true");
       
       String jarInit = "jar:file:";
       if(!this.toDirectory.startsWith("/")) {
       	jarInit += "/";
       }
       
       URI uri = URI.create((jarInit + this.toDirectory + File.separator + fname).replace('\\',  '/'));
	
	try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
		for(Path thing : entires) {
			String tfname = thing.getFileName().toString();
			if(tfname.endsWith(".class")) {
				byte[] code = Files.readAllBytes(thing);
				if(graphBuilder.hasStaticLambda(code, rTJarEtcLoader)) {
					classesWithAffectedClinit.add(ClassNameFinder.getClassName(code));
				}
			}
			
			tracker.entryDone();
		}
       }
	

	
}