Example usage for java.nio.file Path normalize

List of usage examples for java.nio.file Path normalize

Introduction

In this page you can find the example usage for java.nio.file Path normalize.

Prototype

Path normalize();

Source Link

Document

Returns a path that is this path with redundant name elements eliminated.

Usage

From source file:org.age.console.command.TestCommand.java

private void runConfig(final @NonNull PrintWriter printWriter) {
    log.debug("Running config.");
    final Path path = Paths.get(config);
    if (!Files.exists(path)) {
        printWriter.println("File " + config + " does not exist.");
        return;/* www .ja va 2 s  .  c  o m*/
    }
    topic.publish(WorkerMessage.createBroadcastWithPayload(WorkerMessage.Type.LOAD_CONFIGURATION,
            path.normalize().toString()));
    try {
        TimeUnit.SECONDS.sleep(1L);
    } catch (final InterruptedException e) {
        log.debug("Interrupted.", e);
    }
    topic.publish(WorkerMessage.createBroadcastWithoutPayload(WorkerMessage.Type.START_COMPUTATION));
}

From source file:io.gravitee.maven.plugins.json.schema.generator.mojo.Output.java

/**
 * Create the JSON file associated to the JSON Schema
 *
 * @param schema the JSON schema to write into file
 *//*from  w w  w .  j  av a  2  s.co  m*/
private void createJsonFile(JsonSchema schema) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema);

        // replace all : with _ this is a reserved character in some file systems
        Path outputPath = Paths.get(
                config.getOutputDirectory() + File.separator + schema.getId().replaceAll(":", "_") + ".json");
        Files.write(outputPath, json.getBytes(), StandardOpenOption.WRITE, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING);
        config.getLogger().info("Created JSON Schema: " + outputPath.normalize().toAbsolutePath().toString());
    } catch (JsonProcessingException e) {
        config.getLogger().warn("Unable to display schema " + schema.getId(), e);
    } catch (Exception e) {
        config.getLogger().warn("Unable to write Json file for schema " + schema.getId(), e);
    }
}

From source file:com.eqbridges.vertx.VerticleModuleMojo.java

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    Path to = toPath.resolve(fromPath.relativize(file));
    Files.copy(file, to, copyOption);
    log.info(format("Copied file [%s] -> [%s]", file.getFileName(), to.normalize()));
    return FileVisitResult.CONTINUE;
}

From source file:org.bonitasoft.platform.setup.command.configure.BundleConfigurator.java

void loadProperties() throws PlatformException {
    final Properties properties = new PropertyLoader().loadProperties();

    standardConfiguration = new DatabaseConfiguration("", properties, rootPath);
    bdmConfiguration = new DatabaseConfiguration("bdm.", properties, rootPath);
    try {//  w  w  w  . ja va 2 s  .  co m
        final Path dbFile = Paths.get(this.getClass().getResource("/database.properties").toURI());
        LOGGER.info(getBundleName() + " environment detected with root " + rootPath);
        LOGGER.info("Running auto-configuration using file " + dbFile.normalize());
    } catch (URISyntaxException e) {
        throw new PlatformException("Configuration file 'database.properties' not found");
    }
}

From source file:misc.FileHandler.java

/**
 * Copies the source file with the given options to the target file. The
 * source is first copied to the system's default temporary directory and
 * the temporary copy is then moved to the target file. In order to avoid
 * performance problems, the file is directly copied from the source to a
 * temporary file in the target directory first, if the temporary directory
 * and the target file lie on a different <code>FileStore</code>. The
 * temporary file is also moved to the target file.
 * /*from www  . j a  v a 2s  .co  m*/
 * @param source
 *            the file to copy.
 * @param target
 *            the target location where the file should be stored. Must not
 *            be identical with source. The file might or might not exist.
 *            The parent directory must exist.
 * @param replaceExisting
 *            <code>true</code>, if the target file may be overwritten.
 *            Otherwise, <code>false</code>.
 * @return <code>true</code>, if the file was successfully copied.
 *         Otherwise, <code>false</code>.
 */
public static boolean copyFile(Path source, Path target, boolean replaceExisting) {
    if ((source == null) || !Files.isReadable(source)) {
        throw new IllegalArgumentException("source must exist and be readable!");
    }
    if (target == null) {
        throw new IllegalArgumentException("target may not be null!");
    }
    if (source.toAbsolutePath().normalize().equals(target.toAbsolutePath().normalize())) {
        throw new IllegalArgumentException("source and target must not match!");
    }

    boolean success = false;
    Path tempFile = null;

    target = target.normalize();

    try {
        tempFile = FileHandler.getTempFile(target);

        if (tempFile != null) {
            Files.copy(source, tempFile, StandardCopyOption.COPY_ATTRIBUTES,
                    StandardCopyOption.REPLACE_EXISTING);
            if (replaceExisting) {
                Files.move(tempFile, target, StandardCopyOption.REPLACE_EXISTING);
            } else {
                Files.move(tempFile, target);
            }
            success = true;
        }
    } catch (IOException e) {
        Logger.logError(e);
    } finally {
        if (tempFile != null) {
            try {
                Files.deleteIfExists(tempFile);
            } catch (IOException eDelete) {
                Logger.logError(eDelete);
            }
        }
    }

    return success;
}

From source file:com.liferay.blade.cli.command.CreateCommand.java

@Override
public void execute() throws Exception {
    CreateArgs createArgs = getArgs();//www .j a  va  2  s . com
    BladeCLI bladeCLI = getBladeCLI();

    if (createArgs.isListTemplates()) {
        _printTemplates();

        return;
    }

    String template = createArgs.getTemplate();

    if (template == null) {
        bladeCLI.error("The following option is required: [-t | --template]\n\n");
        bladeCLI.error("Availble project templates:\n\n");

        _printTemplates();

        return;
    } else if (template.equals("service")) {
        if (createArgs.getService() == null) {
            StringBuilder sb = new StringBuilder();

            sb.append("\"-t service <FQCN>\" parameter missing.");
            sb.append(System.lineSeparator());
            sb.append("Usage: blade create -t service -s <FQCN> <project name>");
            sb.append(System.lineSeparator());

            bladeCLI.error(sb.toString());

            return;
        }
    } else if (template.equals("fragment")) {
        boolean hasHostBundleBSN = false;

        if (createArgs.getHostBundleBSN() != null) {
            hasHostBundleBSN = true;
        }

        boolean hasHostBundleVersion = false;

        if (createArgs.getHostBundleVersion() != null) {
            hasHostBundleVersion = true;
        }

        if (!hasHostBundleBSN || !hasHostBundleVersion) {
            StringBuilder sb = new StringBuilder("\"-t fragment\" options missing:" + System.lineSeparator());

            if (!hasHostBundleBSN) {
                sb.append("Host Bundle BSN (\"-h\", \"--host-bundle-bsn\") is required.");
                sb.append(System.lineSeparator());
            }

            if (!hasHostBundleVersion) {
                sb.append("Host Bundle Version (\"-H\", \"--host-bundle-version\") is required.");
                sb.append(System.lineSeparator());
            }

            bladeCLI.printUsage("create", sb.toString());

            return;
        }
    } else if (template.equals("modules-ext")) {
        if ("maven".equals(createArgs.getProfileName())) {
            bladeCLI.error(
                    "Modules Ext projects are not supported with Maven build. Please use Gradle build instead.");

            return;
        }

        boolean hasOriginalModuleName = false;

        if (createArgs.getOriginalModuleName() != null) {
            hasOriginalModuleName = true;
        }

        if (!hasOriginalModuleName) {
            StringBuilder sb = new StringBuilder();

            sb.append("modules-ext options missing:");
            sb.append(System.lineSeparator());
            sb.append("\"-m\", \"--original-module-name\") is required.");
            sb.append(System.lineSeparator());
            sb.append(
                    "\"-M\", \"--original-module-version\") is required unless you have enabled target platform.");
            sb.append(System.lineSeparator());
            sb.append(System.lineSeparator());

            bladeCLI.printUsage("create", sb.toString());

            return;
        }
    }

    String name = createArgs.getName();

    if (BladeUtil.isEmpty(name)) {
        _addError("Create", "SYNOPSIS\n\t create [options] <[name]>");

        return;
    }

    if (!_isExistingTemplate(template)) {
        _addError("Create", "The template " + template + " is not in the list");

        return;
    }

    File dir;

    File argsDir = createArgs.getDir();

    if (argsDir != null) {
        dir = new File(argsDir.getAbsolutePath());
    } else if (template.startsWith("war") || template.equals("theme") || template.equals("layout-template")
            || template.equals("spring-mvc-portlet")) {

        dir = _getDefaultWarsDir();
    } else if (template.startsWith("modules-ext")) {
        dir = _getDefaultExtDir();
    } else {
        dir = _getDefaultModulesDir();
    }

    final File checkDir = new File(dir, name);

    if (!_checkDir(checkDir)) {
        _addError("Create", name + " is not empty or it is a file. Please clean or delete it then run again");

        return;
    }

    ProjectTemplatesArgs projectTemplatesArgs = getProjectTemplateArgs(createArgs, bladeCLI, template, name,
            dir);

    List<File> archetypesDirs = projectTemplatesArgs.getArchetypesDirs();

    Path customTemplatesPath = bladeCLI.getExtensionsPath();

    archetypesDirs.add(customTemplatesPath.toFile());

    execute(projectTemplatesArgs);

    Path path = dir.toPath();

    Path absolutePath = path.toAbsolutePath();

    absolutePath = absolutePath.normalize();

    bladeCLI.out("Successfully created project " + projectTemplatesArgs.getName() + " in " + absolutePath);
}

From source file:edu.usc.goffish.gofs.tools.deploy.SCPPartitionDistributer.java

public SCPPartitionDistributer(Path scpBinaryPath, String[] extraSCPOptions, ISliceSerializer serializer,
        int instancesGroupingSize, int numSubgraphBins) {
    if (scpBinaryPath == null) {
        throw new IllegalArgumentException();
    }//from  ww w  .j  a  v  a2 s.  c  om
    if (serializer == null) {
        throw new IllegalArgumentException();
    }
    if (instancesGroupingSize < 1) {
        throw new IllegalArgumentException();
    }
    if (numSubgraphBins < 1 && numSubgraphBins != -1) {
        throw new IllegalArgumentException();
    }

    _scpBinaryPath = scpBinaryPath.normalize();
    _extraSCPOptions = extraSCPOptions;
    _serializer = serializer;
    _instancesGroupingSize = instancesGroupingSize;
    _numSubgraphBins = numSubgraphBins;
}

From source file:com.simiacryptus.util.io.MarkdownNotebookOutput.java

/**
 * Code file string.//from   w  ww  .  j  a v a2 s . c  o m
 *
 * @param file the file
 * @return the string
 * @throws IOException the io exception
 */
public String codeFile(@javax.annotation.Nonnull File file) throws IOException {
    Path path = pathToCodeFile(file);
    if (null != getAbsoluteUrl()) {
        try {
            return new URI(getAbsoluteUrl()).resolve(path.normalize().toString().replaceAll("\\\\", "/"))
                    .normalize().toString();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    } else {
        return path.normalize().toString().replaceAll("\\\\", "/");
    }
}

From source file:platform.tooling.support.Runner.java

Result run() throws Exception {
    // sanity check
    if (!Files.isDirectory(projects)) {
        var cwd = Paths.get(".").normalize().toAbsolutePath();
        throw new IllegalStateException("Directory " + projects + " not found in: " + cwd);
    }/*  w  ww.ja v  a 2  s .co  m*/

    Files.createDirectories(toolPath);
    Files.createDirectories(workPath);

    var result = new Result();
    result.request = request;

    // prepare workspace
    var project = projects.resolve(request.getProject());
    if (!Files.isDirectory(project)) {
        throw new IllegalStateException("Directory " + project + " not found!");
    }
    var workspace = result.workspace = workPath.resolve(request.getWorkspace());
    result.out = workspace.resolve(request.getLogfileOut());
    result.err = workspace.resolve(request.getLogfileErr());

    FileUtils.deleteQuietly(workspace.toFile());
    FileUtils.copyDirectory(project.toFile(), workspace.toFile(),
            request.getCopyProjectToWorkspaceFileFilter());

    Path executable;
    switch (tool.getKind()) {
    case JDK:
        return runJdkFoundationTool(result);
    case LOCAL:
        executable = tool.computeExecutablePath();
        break;
    case REMOTE:
        executable = installRemoteTool(result).getToolExecutable();
        break;
    default:
        throw new UnsupportedOperationException(tool.getKind() + " is not yet supported");
    }

    var command = new ArrayList<String>();
    command.add(executable.normalize().toAbsolutePath().toString());
    command.addAll(request.getArguments());
    var builder = new ProcessBuilder(command) //
            .directory(workspace.toFile()) //
            .redirectOutput(result.out.toFile()) //
            .redirectError(result.err.toFile());
    // ensure we stay in our Java execution environment
    builder.environment().put("JAVA_HOME", getCurrentJdkHome().toString());
    if (tool.getKind().equals(Tool.Kind.REMOTE)) {
        builder.environment().put(tool.name() + "_HOME", result.getToolHome().toString());
    }
    builder.environment().putAll(request.getEnvironment());
    var process = builder.start();
    result.status = process.waitFor();
    var encoding = workspace.resolve("file.encoding.txt");
    if (Files.exists(encoding)) {
        result.charset = Charset.forName(new String(Files.readAllBytes(encoding)));
    }
    return result;
}

From source file:nextflow.fs.dx.DxFileSystemProvider.java

@Override
public boolean isSameFile(Path path, Path path2) throws IOException {
    return path.normalize().compareTo(path2.normalize()) == 0;
}