Example usage for java.nio.file Path isAbsolute

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

Introduction

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

Prototype

boolean isAbsolute();

Source Link

Document

Tells whether or not this path is absolute.

Usage

From source file:org.codice.ddf.cxf.client.impl.SecureCxfClientFactoryImpl.java

@SuppressWarnings("squid:S3776")
private void configureConduit(ClientConfiguration clientConfig) {
    HTTPConduit httpConduit = clientConfig.getHttpConduit();
    if (httpConduit == null) {
        LOGGER.info("HTTPConduit was null for {}. Unable to configure security.", this);
        return;//from   w  w w  . j  ava2s .  co  m
    }

    if (allowRedirects) {
        HTTPClientPolicy clientPolicy = httpConduit.getClient();
        if (clientPolicy != null) {
            clientPolicy.setAutoRedirect(true);
            Bus bus = clientConfig.getBus();
            if (bus != null) {
                bus.getProperties().put(AUTO_REDIRECT_ALLOW_REL_URI, true);
                bus.getProperties().put(AUTO_REDIRECT_MAX_SAME_URI_COUNT, getSameUriRedirectMax());
            }
        }
    }

    TLSClientParameters tlsParams = httpConduit.getTlsClientParameters();
    if (tlsParams == null) {
        tlsParams = new TLSClientParameters();
    }

    tlsParams.setDisableCNCheck(disableCnCheck);

    tlsParams.setUseHttpsURLConnectionDefaultHostnameVerifier(!disableCnCheck);
    String cipherSuites = System.getProperty("https.cipherSuites");
    if (cipherSuites != null) {
        tlsParams.setCipherSuites(Arrays.asList(cipherSuites.split(",")));
    }

    KeyStore keyStore = null;
    KeyStore trustStore = null;
    try {
        keyStore = SecurityConstants.newKeystore();
        trustStore = SecurityConstants.newTruststore();
    } catch (KeyStoreException e) {
        LOGGER.debug("Unable to create keystore instance of type {}",
                System.getProperty(SecurityConstants.KEYSTORE_TYPE), e);
    }
    Path keyStoreFile;
    if (keyInfo != null && StringUtils.isNotBlank(keyInfo.getKeystorePath())) {
        keyStoreFile = Paths.get(keyInfo.getKeystorePath());
    } else {
        keyStoreFile = Paths.get(SecurityConstants.getKeystorePath());
    }

    Path trustStoreFile = Paths.get(SecurityConstants.getTruststorePath());
    String ddfHome = System.getProperty("ddf.home");
    if (ddfHome != null) {
        Path ddfHomePath = Paths.get(ddfHome);
        if (!keyStoreFile.isAbsolute()) {
            keyStoreFile = Paths.get(ddfHomePath.toString(), keyStoreFile.toString());
        }
        if (!trustStoreFile.isAbsolute()) {
            trustStoreFile = Paths.get(ddfHomePath.toString(), trustStoreFile.toString());
        }
    }
    String keyStorePassword = SecurityConstants.getKeystorePassword();
    String trustStorePassword = SecurityConstants.getTruststorePassword();
    if (!Files.isReadable(keyStoreFile) || !Files.isReadable(trustStoreFile)) {
        LOGGER.debug("Unable to read system key/trust store files: [ {} ] [ {} ]", keyStoreFile,
                trustStoreFile);
        return;
    }
    try (InputStream kfis = Files.newInputStream(keyStoreFile)) {
        if (keyStore != null) {
            keyStore.load(kfis, keyStorePassword.toCharArray());
        }
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        LOGGER.debug("Unable to load system key file.", e);
    }
    try (InputStream tfis = Files.newInputStream(trustStoreFile)) {
        if (trustStore != null) {
            trustStore.load(tfis, trustStorePassword.toCharArray());
        }
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        LOGGER.debug("Unable to load system trust file.", e);
    }

    KeyManager[] keyManagers = null;
    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
        keyManagers = keyManagerFactory.getKeyManagers();
        tlsParams.setKeyManagers(keyManagers);
    } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException e) {
        LOGGER.debug("Unable to initialize KeyManagerFactory.", e);
    }

    TrustManager[] trustManagers = null;
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        trustManagers = trustManagerFactory.getTrustManagers();
        tlsParams.setTrustManagers(trustManagers);
    } catch (NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.debug("Unable to initialize TrustManagerFactory.", e);
    }

    if (keyInfo != null) {
        LOGGER.trace("Using keystore file: {}, alias: {}", keyStoreFile, keyInfo.getAlias());
        tlsParams.setUseHttpsURLConnectionDefaultSslSocketFactory(false);
        tlsParams.setCertAlias(keyInfo.getAlias());
        try {
            if (keyManagers == null) {
                throw new KeyManagementException("keyManagers was null");
            }

            boolean validProtocolFound = false;
            String validProtocolsStr = System.getProperty("jdk.tls.client.protocols");
            if (StringUtils.isNotBlank(validProtocolsStr)) {
                String[] validProtocols = validProtocolsStr.split(",");
                for (String validProtocol : validProtocols) {
                    if (validProtocol.equals(sslProtocol)) {
                        validProtocolFound = true;
                        break;
                    }
                }
                if (!validProtocolFound) {
                    LOGGER.error("{} is not in list of valid SSL protocols {}", sslProtocol, validProtocolsStr);
                }

            } else {
                validProtocolFound = true;
            }
            if (validProtocolFound) {
                tlsParams.setSSLSocketFactory(
                        getSSLSocketFactory(sslProtocol, keyInfo.getAlias(), keyManagers, trustManagers));
            }
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            LOGGER.debug("Unable to override default SSL Socket Factory", e);
        }
    } else {
        tlsParams.setUseHttpsURLConnectionDefaultSslSocketFactory(true);
        tlsParams.setCertAlias(SystemBaseUrl.INTERNAL.getHost());
    }

    httpConduit.setTlsClientParameters(tlsParams);
}

From source file:com.qspin.qtaste.testsuite.impl.JythonTestScript.java

private void dumpScriptPythonStackDetails(TestResult result, Throwable error) {
    StringBuilder stackTrace = new StringBuilder();

    // get stacktrace from PyException traceback, because easier and line number is not always correct in Java stack trace
    if (error instanceof PyException) {
        List<PyFrame> stacktrace = new ArrayList<>();
        PyTraceback previousTraceback = null;
        PyTraceback traceback = ((PyException) error).traceback;
        while (traceback != null && traceback != previousTraceback) {
            PyFrame frame = traceback.tb_frame;
            String fileName;//w w w.j  a va 2  s .  c  o  m
            String function;

            if (frame != null && frame.f_code != null && (fileName = frame.f_code.co_filename) != null
                    && (function = frame.f_code.co_name) != null) {
                // skip execfile() call in the embedded jython, doStep() and doSteps() functions,
                // private __invokexxx() methods of the __TestAPIWrapper class,
                // private __checkPresent() method of a test API wrapper class,
                // user_line() method of the __ScriptDebugger class and a function of the debugger
                if ((!fileName.equals("embedded_jython") || (!function.equals("<module>")
                        && !function.equals("doStep") && !function.equals("doSteps")
                        && !function.startsWith("_TestAPIWrapper__invoke")
                        && !function.endsWith("__checkPresent") && !function.equals("user_line")))
                        && !fileName.endsWith(File.separator + "bdb.py")) {
                    stacktrace.add(frame);
                }
            }

            previousTraceback = traceback;
            traceback = (PyTraceback) traceback.tb_next;
        }

        // extract all necessary details from stacktrace from last frame to first one
        boolean stackLastDataExtracted = false;
        ListIterator<PyFrame> frameIterator = stacktrace.listIterator(stacktrace.size());
        while (frameIterator.hasPrevious()) {
            PyFrame frame = frameIterator.previous();
            String fileName = frame.f_code.co_filename;
            String function = frame.f_code.co_name;
            int lineNumber = frame.f_lineno;

            // convert absolute path to relative path
            Path filePath = Paths.get(fileName);
            if (filePath.isAbsolute()) {
                filePath = Paths.get("").toAbsolutePath().relativize(filePath);
            }
            // normalize path
            fileName = filePath.normalize().toString();

            if (function.equals("<module>")) {
                stackTrace.append("at file ").append(fileName).append(" line ").append(lineNumber).append('\n');
            } else if (!function.equals("importTestScript")) {
                stackTrace.append("function ").append(function);
                if (!fileName.equals("embedded_jython") && !fileName.equals("JythonTestScript.java")) {
                    stackTrace.append(" at file ").append(fileName).append(" line ").append(lineNumber);
                }
                stackTrace.append('\n');
            }
            if (!stackLastDataExtracted && !fileName.equals("embedded_jython")
                    && !fileName.equals("JythonTestScript.java")) {
                stackLastDataExtracted = true;
                result.setFailedLineNumber(lineNumber);
                result.setFailedFunctionId(function);
            }
            result.addStackTraceElement(new StackTraceElement("", function, fileName, lineNumber));
        }
    }

    result.setStackTrace(stackTrace.toString().trim());
}

From source file:org.wso2.carbon.appmgt.impl.utils.AppManagerUtil.java

/**
 * Resolve file path avoiding Potential Path Traversals
 *
 * @param baseDirPath base directory file path
 * @param fileName    filename//from   w ww.j  ava2s  .  c  om
 * @return
 */
public static String resolvePath(String baseDirPath, String fileName) {
    final Path basePath = Paths.get(baseDirPath);
    final Path filePath = Paths.get(fileName);
    if (!basePath.isAbsolute()) {
        throw new IllegalArgumentException("Base directory path '" + baseDirPath + "' must be absolute");
    }
    if (filePath.isAbsolute()) {
        throw new IllegalArgumentException(
                "Invalid file name '" + fileName + "' with an absolute file path is provided");
    }
    // Join the two paths together, then normalize so that any ".." elements
    final Path resolvedPath = basePath.resolve(filePath).normalize();

    // Make sure the resulting path is still within the required directory.
    if (!resolvedPath.startsWith(basePath.normalize())) {
        throw new IllegalArgumentException("File '" + fileName + "' is not within the required directory.");
    }

    return String.valueOf(resolvedPath);
}