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.security.certificate.keystore.editor.KeystoreEditor.java

@Override
public void addTrustedCertificate(String alias, String keyPassword, String storePassword, String data,
        String type, String fileName) throws KeystoreEditorException {
    LOGGER.info("Adding alias {} to trust store", alias);
    LOGGER.trace("Received data {}", data);
    Path trustStoreFile = Paths.get(SecurityConstants.getTruststorePath());
    if (!trustStoreFile.isAbsolute()) {
        Path ddfHomePath = Paths.get(System.getProperty("ddf.home"));
        trustStoreFile = Paths.get(ddfHomePath.toString(), trustStoreFile.toString());
    }/*w  ww .  ja v a2s.co m*/
    String trustStorePassword = SecurityConstants.getTruststorePassword();
    addToStore(alias, keyPassword, storePassword, data, type, fileName, trustStoreFile.toString(),
            trustStorePassword, trustStore);
}

From source file:com.aimluck.eip.services.storage.impl.ALDefaultStorageHandler.java

protected String getAbsolutePath(String folderPath) {
    try {//from   w w w .  j  a v  a 2  s  . c om
        Path path = Paths.get(folderPath);
        if (path == null) {
            return folderPath;
        }
        if (path.isAbsolute()) {
            return folderPath;
        }
        String root = System.getProperty("catalina.home");
        if (root == null) {
            return folderPath;
        }
        return root + separator() + folderPath;
    } catch (Throwable ignore) {
        //
    }
    return folderPath;
}

From source file:com.github.zhanhb.ckfinder.connector.support.XmlConfigurationParser.java

/**
 * Creates single resource type configuration from XML configuration file
 * (from XML element 'type')./*w  w  w .j  ava  2 s  .  c  o m*/
 *
 * @param typeName name of type.
 * @param childNodes type XML child nodes.
 * @param basePathBuilder base url and path builder
 * @return parsed resource type
 * @throws IOException when IO Exception occurs.
 * @throws ConnectorException when error occurs
 */
@SuppressWarnings("deprecation")
private ResourceType createTypeFromXml(String typeName, NodeList childNodes, BasePathBuilder basePathBuilder,
        ThumbnailProperties thumbnail) throws IOException, ConnectorException {
    ResourceType.Builder builder = ResourceType.builder().name(typeName);
    String path = typeName.toLowerCase();
    String url = typeName.toLowerCase();

    for (int i = 0, j = childNodes.getLength(); i < j; i++) {
        Node childNode = childNodes.item(i);
        switch (childNode.getNodeName()) {
        case "url":
            url = nullNodeToString(childNode);
            break;
        case "directory":
            path = nullNodeToString(childNode);
            break;
        case "maxSize":
            long maxSize = 0;
            try {
                parseMaxSize(nullNodeToString(childNode));
            } catch (NumberFormatException | IndexOutOfBoundsException ex) {
            }
            builder.maxSize(maxSize);
            break;
        case "allowedExtensions":
            builder.allowedExtensions(nullNodeToString(childNode));
            break;
        case "deniedExtensions":
            builder.deniedExtensions(nullNodeToString(childNode));
        }
    }
    url = basePathBuilder.getBaseUrl() + url.replace(Constants.BASE_URL_PLACEHOLDER, "");
    url = PathUtils.normalizeUrl(url);
    path = path.replace(Constants.BASE_DIR_PLACEHOLDER, "");

    Path p = getPath(basePathBuilder.getBasePath(), path);
    if (!p.isAbsolute()) {
        throw new ConnectorException(ErrorCode.FOLDER_NOT_FOUND,
                "Resource directory could not be created using specified path.");
    }
    return builder.url(url).path(Files.createDirectories(p))
            .thumbnailPath(getPath(thumbnail != null ? thumbnail.getPath() : null, path)).build();
}

From source file:org.apache.archiva.repository.maven2.MavenRepositoryProvider.java

private ManagedRepositoryConfiguration getStageRepoConfig(ManagedRepositoryConfiguration repository) {
    ManagedRepositoryConfiguration stagingRepository = new ManagedRepositoryConfiguration();
    stagingRepository.setId(repository.getId() + StagingRepositoryFeature.STAGING_REPO_POSTFIX);
    stagingRepository.setLayout(repository.getLayout());
    stagingRepository.setName(repository.getName() + StagingRepositoryFeature.STAGING_REPO_POSTFIX);
    stagingRepository.setBlockRedeployments(repository.isBlockRedeployments());
    stagingRepository.setRetentionPeriod(repository.getRetentionPeriod());
    stagingRepository.setDeleteReleasedSnapshots(repository.isDeleteReleasedSnapshots());
    stagingRepository.setStageRepoNeeded(false);

    String path = repository.getLocation();
    int lastIndex = path.replace('\\', '/').lastIndexOf('/');
    stagingRepository.setLocation(path.substring(0, lastIndex) + "/" + stagingRepository.getId());

    if (StringUtils.isNotBlank(repository.getIndexDir())) {
        Path indexDir = null;
        try {//  ww  w. j  a  va 2s .  c  om
            indexDir = Paths
                    .get(new URI(repository.getIndexDir().startsWith("file://") ? repository.getIndexDir()
                            : "file://" + repository.getIndexDir()));
            if (indexDir.isAbsolute()) {
                Path newDir = indexDir.getParent()
                        .resolve(indexDir.getFileName() + StagingRepositoryFeature.STAGING_REPO_POSTFIX);
                log.debug("Changing index directory {} -> {}", indexDir, newDir);
                stagingRepository.setIndexDir(newDir.toString());
            } else {
                log.debug("Keeping index directory {}", repository.getIndexDir());
                stagingRepository.setIndexDir(repository.getIndexDir());
            }
        } catch (URISyntaxException e) {
            log.error("Could not parse index path as uri {}", repository.getIndexDir());
            stagingRepository.setIndexDir("");
        }
        // in case of absolute dir do not use the same
    }
    if (StringUtils.isNotBlank(repository.getPackedIndexDir())) {
        Path packedIndexDir = null;
        try {
            packedIndexDir = Paths.get(new URI(
                    repository.getPackedIndexDir().startsWith("file://") ? repository.getPackedIndexDir()
                            : "file://" + repository.getPackedIndexDir()));
            if (packedIndexDir.isAbsolute()) {
                Path newDir = packedIndexDir.getParent()
                        .resolve(packedIndexDir.getFileName() + StagingRepositoryFeature.STAGING_REPO_POSTFIX);
                log.debug("Changing index directory {} -> {}", packedIndexDir, newDir);
                stagingRepository.setPackedIndexDir(newDir.toString());
            } else {
                log.debug("Keeping index directory {}", repository.getPackedIndexDir());
                stagingRepository.setPackedIndexDir(repository.getPackedIndexDir());
            }
        } catch (URISyntaxException e) {
            log.error("Could not parse index path as uri {}", repository.getPackedIndexDir());
            stagingRepository.setPackedIndexDir("");
        }
        // in case of absolute dir do not use the same
    }
    stagingRepository.setRefreshCronExpression(repository.getRefreshCronExpression());
    stagingRepository.setReleases(repository.isReleases());
    stagingRepository.setRetentionCount(repository.getRetentionCount());
    stagingRepository.setScanned(repository.isScanned());
    stagingRepository.setSnapshots(repository.isSnapshots());
    stagingRepository.setSkipPackedIndexCreation(repository.isSkipPackedIndexCreation());
    // do not duplicate description
    //stagingRepository.getDescription("")
    return stagingRepository;
}

From source file:io.cloudslang.content.ssh.services.impl.SSHServiceImpl.java

/**
 * Open SSH session./*from  w ww .  j ava2s . c  o m*/
 *
 * @param details                     The connection details.
 * @param identityKey                 The private key file or string.
 * @param knownHostsFile              The known_hosts file and policy.
 * @param connectTimeout              The open SSH session timeout.
 * @param keepContextForExpectCommand Use the same channel for the expect command.
 * @param proxyHTTP                   The proxy settings, parse it as null if no proxy settings required
 * @param allowedCiphers              The list of allowed ciphers. If not empty, it will be used to overwrite the default list.
 */
public SSHServiceImpl(ConnectionDetails details, IdentityKey identityKey, KnownHostsFile knownHostsFile,
        int connectTimeout, boolean keepContextForExpectCommand, ProxyHTTP proxyHTTP, String allowedCiphers)
        throws SSHException {
    JSch jsch = new JSch();
    String finalListOfAllowedCiphers = StringUtilities.isNotBlank(allowedCiphers) ? allowedCiphers
            : ALLOWED_CIPHERS;
    JSch.setConfig("cipher.s2c", finalListOfAllowedCiphers);
    JSch.setConfig("cipher.c2s", finalListOfAllowedCiphers);
    JSch.setConfig("PreferredAuthentications", "publickey,password,keyboard-interactive");

    try {
        session = jsch.getSession(details.getUsername(), details.getHost(), details.getPort());
    } catch (JSchException e) {
        throw new SSHException(e);
    }

    try {
        String policy = knownHostsFile.getPolicy();
        Path knownHostsFilePath = knownHostsFile.getPath();
        switch (policy.toLowerCase(Locale.ENGLISH)) {
        case KNOWN_HOSTS_ALLOW:
            session.setConfig("StrictHostKeyChecking", "no");
            break;
        case KNOWN_HOSTS_STRICT:
            jsch.setKnownHosts(knownHostsFilePath.toString());
            session.setConfig("StrictHostKeyChecking", "yes");
            break;
        case KNOWN_HOSTS_ADD:
            if (!knownHostsFilePath.isAbsolute()) {
                throw new SSHException("The known_hosts file path should be absolute.");
            }
            if (!Files.exists(knownHostsFilePath)) {
                Path parent = knownHostsFilePath.getParent();
                if (parent != null) {
                    Files.createDirectories(parent);
                }
                Files.createFile(knownHostsFilePath);
            }
            jsch.setKnownHosts(knownHostsFilePath.toString());
            session.setConfig("StrictHostKeyChecking", "no");
            break;
        default:
            throw new SSHException("Unknown known_hosts file policy.");
        }
    } catch (JSchException e) {
        throw new SSHException("The known_hosts file couldn't be set.", e);
    } catch (IOException e) {
        throw new SSHException("The known_hosts file couldn't be created.", e);
    }

    if (identityKey == null) {
        // use the password
        session.setPassword(details.getPassword());
    } else {
        // or use the OpenSSH private key file or string
        IdentityKeyUtils.setIdentity(jsch, identityKey);
    }

    if (proxyHTTP != null) {
        session.setProxy(proxyHTTP);
    }

    try {
        session.connect(connectTimeout);

        if (keepContextForExpectCommand) {
            // create exec channel
            execChannel = session.openChannel(EXEC_CHANNEL);

            // connect to the channel and run the command(s)
            execChannel.connect(connectTimeout);
        }
    } catch (JSchException e) {
        throw new SSHException(e);
    }
}

From source file:de.codecentric.elasticsearch.plugin.kerberosrealm.AbstractUnitTest.java

private Path getAbsoluteFilePathFromClassPath(final String fileNameFromClasspath) {
    Path path = null;
    final URL fileUrl = PropertyUtil.class.getClassLoader().getResource(fileNameFromClasspath);
    if (fileUrl != null) {
        try {//w w w  .  j a  v a 2  s .  c  o m
            path = Paths.get(fileUrl.toURI());
            if (!Files.isReadable(path) && !Files.isDirectory(path)) {
                log.error("Cannot read from {}, file does not exist or is not readable", path.toString());
                return null;
            }

            if (!path.isAbsolute()) {
                log.warn("{} is not absolute", path.toString());
            }
            return path;
        } catch (final URISyntaxException e) {
            //ignore
        }
    } else {
        log.error("Failed to load " + fileNameFromClasspath);
    }
    return null;
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

private void init() {
    try {/* ww  w .  j a  va  2  s  .  com*/
        keyStore = SecurityConstants.newKeystore();
        trustStore = SecurityConstants.newTruststore();
    } catch (KeyStoreException e) {
        LOGGER.error("Unable to create keystore instance of type {}",
                System.getProperty(SecurityConstants.KEYSTORE_TYPE), e);
    }
    Path keyStoreFile = Paths.get(SecurityConstants.getKeystorePath());
    Path trustStoreFile = Paths.get(SecurityConstants.getTruststorePath());
    Path ddfHomePath = Paths.get(System.getProperty("ddf.home"));
    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.error("Unable to read system key/trust store files: [ {} ] [ {} ]", keyStoreFile,
                trustStoreFile);
        return;
    }
    try (InputStream kfis = Files.newInputStream(keyStoreFile)) {
        keyStore.load(kfis, keyStorePassword.toCharArray());
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        LOGGER.error("Unable to load system key file.", e);
        try {
            keyStore.load(null, null);
        } catch (NoSuchAlgorithmException | CertificateException | IOException ignore) {
        }
    }
    try (InputStream tfis = Files.newInputStream(trustStoreFile)) {
        trustStore.load(tfis, trustStorePassword.toCharArray());
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        LOGGER.error("Unable to load system trust file.", e);
        try {
            trustStore.load(null, null);
        } catch (NoSuchAlgorithmException | CertificateException | IOException ignore) {
        }
    }
}

From source file:org.apache.archiva.admin.mock.ArchivaIndexManagerMock.java

private Path getIndexPath(Repository repo) throws IOException {
    IndexCreationFeature icf = repo.getFeature(IndexCreationFeature.class).get();
    Path repoDir = repo.getLocalPath();
    URI indexDir = icf.getIndexPath();
    Path indexDirectory = null;
    if (!StringUtils.isEmpty(indexDir.toString())) {

        indexDirectory = PathUtil.getPathFromUri(indexDir);
        // not absolute so create it in repository directory
        if (!indexDirectory.isAbsolute()) {
            indexDirectory = repoDir.resolve(indexDirectory);
        }/*from   w  w w .j  a v a2 s  . com*/
    } else {
        indexDirectory = repoDir.resolve(".index");
    }

    if (!Files.exists(indexDirectory)) {
        Files.createDirectories(indexDirectory);
    }
    return indexDirectory;
}

From source file:org.apache.archiva.indexer.maven.MavenIndexManager.java

private Path getPackedIndexPath(Repository repo) throws IOException {
    IndexCreationFeature icf = repo.getFeature(IndexCreationFeature.class).get();
    Path repoDir = repo.getLocalPath();
    URI indexDir = icf.getPackedIndexPath();
    Path indexDirectory = null;
    if (!StringUtils.isEmpty(indexDir.toString())) {

        indexDirectory = PathUtil.getPathFromUri(indexDir);
        // not absolute so create it in repository directory
        if (!indexDirectory.isAbsolute()) {
            indexDirectory = repoDir.resolve(indexDirectory);
        }//from   w  ww  .j  a v a2 s . c o m
    } else {
        indexDirectory = repoDir.resolve(DEFAULT_PACKED_INDEX_DIR);
    }

    if (!Files.exists(indexDirectory)) {
        Files.createDirectories(indexDirectory);
    }
    return indexDirectory;
}