Example usage for java.nio.file Path toAbsolutePath

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

Introduction

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

Prototype

Path toAbsolutePath();

Source Link

Document

Returns a Path object representing the absolute path of this path.

Usage

From source file:org.elasticsearch.test.ESBackcompatTestCase.java

private static Path backwardsCompatibilityPath() {
    String path = System.getProperty(TESTS_BACKWARDS_COMPATIBILITY_PATH);
    if (path == null || path.isEmpty()) {
        throw new IllegalArgumentException(
                "Must specify backwards test path with property " + TESTS_BACKWARDS_COMPATIBILITY_PATH);
    }/*w  w  w  .  ja v  a  2 s  . co  m*/
    String version = System.getProperty(TESTS_BACKWARDS_COMPATIBILITY_VERSION);
    if (version == null || version.isEmpty()) {
        throw new IllegalArgumentException(
                "Must specify backwards test version with property " + TESTS_BACKWARDS_COMPATIBILITY_VERSION);
    }
    if (Version.fromString(version).before(Version.CURRENT.minimumCompatibilityVersion())) {
        throw new IllegalArgumentException(
                "Backcompat elasticsearch version must be same major version as current. " + "backcompat: "
                        + version + ", current: " + Version.CURRENT.toString());
    }
    Path file = PathUtils.get(path, "elasticsearch-" + version);
    if (!Files.exists(file)) {
        throw new IllegalArgumentException("Backwards tests location is missing: " + file.toAbsolutePath());
    }
    if (!Files.isDirectory(file)) {
        throw new IllegalArgumentException(
                "Backwards tests location is not a directory: " + file.toAbsolutePath());
    }
    return file;
}

From source file:org.kie.workbench.common.services.backend.compiler.impl.external339.AFSettingsXmlConfigurationProcessor.java

static Path resolvePath(Path file, String workingDirectory) {
    if (file == null) {
        return null;
    } else if (file.isAbsolute()) {
        return file;
    } else if (file.getFileName().startsWith(File.separator)) {
        return file.toAbsolutePath();
    } else {//  w  w  w  .j a  v a  2  s .c om
        return Paths.get(workingDirectory, file.getFileName().toString());
    }
}

From source file:com.spotify.heroic.HeroicShell.java

static Path parseConfigPath(String config) {
    final Path path = doParseConfigPath(config);

    if (!Files.isRegularFile(path)) {
        throw new IllegalStateException("No such file: " + path.toAbsolutePath());
    }//from   ww  w.j ava2s  .c o m

    return path;
}

From source file:net.kemuri9.sling.filesystemprovider.impl.PersistenceHelper.java

/**
 * Read the binary data indicated by the current value, if applicable.
 * @param path the resource path//ww  w  .jav a  2  s.  co m
 * @param val the value that may be a binary value that requires reading.
 * @param isBinary state of the value being a binary value that requires processing.
 * @return the possibly updated object that underwent binary transformation
 */
private static Object readBinary(String path, Object val, boolean isBinary) {
    if (!isBinary) {
        // there is no handling to perform, so return as-is
        return val;
    }
    if (!(val instanceof String)) {
        log.error("binary property did not have a string value");
    }

    /* if it's a temporary file, then we need to look for it in the
     * temporary folder, otherwise look in the resource folder */
    String filename = (String) val;
    Path folder = (filename.contains(FSPConstants.FILENAME_FRAGMENT_TEMPORARY)) ? Util.getTemporaryDirectory()
            : Paths.get(Util.getAbsPath(path));
    Path file = Paths.get(folder.toAbsolutePath().toString(), filename);

    try {
        return new FileBinary(file);
    } catch (IOException e) {
        log.error("Unable to create Binary representation from {}", file.toAbsolutePath(), e);
        return null;
    }
}

From source file:org.openhab.binding.fems.FEMSCore.java

/**
 * Checks if modbus connection to storage system is working
 * @param ess "dess" or "cess"//www. j  av  a  2 s .  c  o m
 * @return
 */
public static boolean isModbusWorking(Log log, String ess) {
    // remove old lock file
    try {
        if (Files.deleteIfExists(Paths.get("/var/lock/LCK..ttyUSB0"))) {
            log.info("Deleted old lock file");
        }
    } catch (IOException e) {
        log.error("Error deleting old lock file: " + e.getMessage());
        e.printStackTrace();
    }

    // find first matching device
    String modbusDevice = "ttyUSB*";
    String portName = "/dev/ttyUSB0"; // if no file found: use default
    try (DirectoryStream<Path> files = Files.newDirectoryStream(Paths.get("/dev"), modbusDevice)) {
        for (Path file : files) {
            portName = file.toAbsolutePath().toString();
            log.info("Set modbus portname: " + portName);
        }
    } catch (Exception e) {
        log.info("Error trying to find " + modbusDevice + ": " + e.getMessage());
        e.printStackTrace();
    }

    // default: DESS 
    int baudRate = 9600;
    int socAddress = 10143;
    int unit = 4;
    if (ess.compareTo("cess") == 0) {
        baudRate = 19200;
        socAddress = 0x1402;
        unit = 100;
    }
    SerialParameters params = new SerialParameters();
    params.setPortName(portName);
    params.setBaudRate(baudRate);
    params.setDatabits(8);
    params.setParity("None");
    params.setStopbits(1);
    params.setEncoding(Modbus.SERIAL_ENCODING_RTU);
    params.setEcho(false);
    params.setReceiveTimeout(Constants.MODBUS_TIMEOUT);
    SerialConnection serialConnection = new SerialConnection(params);
    try {
        serialConnection.open();
    } catch (Exception e) {
        log.error("Modbus connection error: " + e.getMessage());
        serialConnection.close();
        return false;
    }
    ModbusSerialTransaction modbusSerialTransaction = null;
    ReadMultipleRegistersRequest req = new ReadMultipleRegistersRequest(socAddress, 1);
    req.setUnitID(unit);
    req.setHeadless();
    modbusSerialTransaction = new ModbusSerialTransaction(serialConnection);
    modbusSerialTransaction.setRequest(req);
    modbusSerialTransaction.setRetries(1);
    try {
        modbusSerialTransaction.execute();
    } catch (ModbusException e) {
        log.error("Modbus execution error: " + e.getMessage());
        serialConnection.close();
        return false;
    }
    ModbusResponse res = modbusSerialTransaction.getResponse();
    serialConnection.close();

    if (res instanceof ReadMultipleRegistersResponse) {
        return true;
    } else if (res instanceof ExceptionResponse) {
        log.error("Modbus read error: " + ((ExceptionResponse) res).getExceptionCode());
    } else {
        log.error("Modbus read undefined response");
    }
    return false;
}

From source file:org.midonet.benchmarks.mpi.MPIBenchApp.java

protected static Path getCfgFilePath(String[] args) throws ConfigException {
    Option cfgOpt = OptionBuilder.isRequired(true).hasArg(true).withLongOpt(CFGFILE_OPTION)
            .withDescription("configuration file").create();
    Options options = new Options();
    options.addOption(cfgOpt);/*  ww w.j  a v a2s  . com*/

    CommandLineParser parser = new PosixParser();
    CommandLine cl;
    try {
        cl = parser.parse(options, args);
    } catch (Exception e) {
        throw new ConfigException(e);
    }
    Path cfgPath = Paths.get(cl.getOptionValue(CFGFILE_OPTION));
    if (!Files.exists(cfgPath)) {
        throw new ConfigException("config file does not exist: " + cfgPath.toString());
    }
    return cfgPath.toAbsolutePath();
}

From source file:org.ballerinalang.langserver.compiler.format.TextDocumentFormatUtil.java

/**
 * Get the AST for the current text document's content.
 *
 * @param file            File path as a URI
 * @param lsCompiler      Language server compiler
 * @param documentManager Workspace document manager instance
 * @param context         Document formatting context
 * @return {@link JsonObject}   AST as a Json Object
 * @throws JSONGenerationException when AST build fails
 * @throws LSCompilerException     when compilation fails
 *//*from   w w w  .  j  a v a  2 s  .co m*/
public static JsonObject getAST(Path file, LSCompiler lsCompiler, WorkspaceDocumentManager documentManager,
        LSContext context) throws JSONGenerationException, LSCompilerException {
    String path = file.toAbsolutePath().toString();
    String sourceRoot = LSCompilerUtil.getSourceRoot(file);
    String packageName = LSCompilerUtil.getPackageNameForGivenFile(sourceRoot, path);
    String[] breakFromPackage = path.split(Pattern.quote(packageName + File.separator));
    String relativePath = breakFromPackage[breakFromPackage.length - 1];

    final BLangPackage bLangPackage = lsCompiler.getBLangPackage(context, documentManager, true,
            LSCustomErrorStrategy.class, false);
    final List<Diagnostic> diagnostics = new ArrayList<>();
    JsonArray errors = new JsonArray();
    JsonObject result = new JsonObject();
    result.add("errors", errors);

    Gson gson = new Gson();
    JsonElement diagnosticsJson = gson.toJsonTree(diagnostics);
    result.add("diagnostics", diagnosticsJson);
    BLangCompilationUnit compilationUnit;

    // If package is testable package process as tests
    // else process normally
    if (isTestablePackage(relativePath)) {
        compilationUnit = bLangPackage.getTestablePkg().getCompilationUnits().stream()
                .filter(compUnit -> (relativePath).equals(compUnit.getName())).findFirst().orElse(null);
    } else {
        compilationUnit = bLangPackage.getCompilationUnits().stream()
                .filter(compUnit -> relativePath.equals(compUnit.getName())).findFirst().orElse(null);
    }

    JsonElement modelElement = generateJSON(compilationUnit, new HashMap<>(), new HashMap<>());
    result.add("model", modelElement);
    return result;
}

From source file:io.github.robwin.diff.DiffAssert.java

private static void writeHtmlReport(Path reportPath, LinkedList<DiffMatchPatch.Diff> diffs) {
    DiffMatchPatch differ = new DiffMatchPatch();
    try {/*w w  w  .  ja  v  a  2  s  . co m*/
        Files.createDirectories(reportPath.getParent());
        try (BufferedWriter writer = Files.newBufferedWriter(reportPath, Charset.forName("UTF-8"))) {
            writer.write(differ.diff_prettyHtml(diffs));
        }
    } catch (IOException e) {
        throw new RuntimeException(String.format("Failed to write report %s", reportPath.toAbsolutePath()), e);
    }
}

From source file:org.apache.openaz.xacml.rest.XACMLPdpLoader.java

public static synchronized Path getPDPPolicyCache() throws PAPException {
    Path config = getPDPConfig();
    Path policyProperties = Paths.get(config.toAbsolutePath().toString(), "xacml.policy.properties");
    if (Files.notExists(policyProperties)) {
        logger.warn(policyProperties.toAbsolutePath().toString() + " does NOT exist.");
        ///*w  w  w .ja  va 2  s .  c o m*/
        // Try to create the file
        //
        try {
            Files.createFile(policyProperties);
        } catch (IOException e) {
            logger.error(
                    "Failed to create policy properties file: " + policyProperties.toAbsolutePath().toString());
            throw new PAPException(
                    "Failed to create policy properties file: " + policyProperties.toAbsolutePath().toString());
        }
    }
    return policyProperties;
}

From source file:org.apache.openaz.xacml.rest.XACMLPdpLoader.java

public static synchronized Path getPIPConfig() throws PAPException {
    Path config = getPDPConfig();
    Path pipConfigProperties = Paths.get(config.toAbsolutePath().toString(), "xacml.pip.properties");
    if (Files.notExists(pipConfigProperties)) {
        logger.warn(pipConfigProperties.toAbsolutePath().toString() + " does NOT exist.");
        ///*from www .ja v  a  2  s  .com*/
        // Try to create the file
        //
        try {
            Files.createFile(pipConfigProperties);
        } catch (IOException e) {
            logger.error(
                    "Failed to create pip properties file: " + pipConfigProperties.toAbsolutePath().toString());
            throw new PAPException(
                    "Failed to create pip properties file: " + pipConfigProperties.toAbsolutePath().toString());
        }
    }
    return pipConfigProperties;
}