Example usage for java.net URI getPath

List of usage examples for java.net URI getPath

Introduction

In this page you can find the example usage for java.net URI getPath.

Prototype

public String getPath() 

Source Link

Document

Returns the decoded path component of this URI.

Usage

From source file:com.cloudera.livy.client.http.LivyConnection.java

LivyConnection(URI uri, final HttpConf config) {
    HttpClientContext ctx = HttpClientContext.create();
    int port = uri.getPort() > 0 ? uri.getPort() : 8998;

    String path = uri.getPath() != null ? uri.getPath() : "";
    this.uriRoot = path + "/clients";

    RequestConfig reqConfig = new RequestConfig() {
        @Override/*from   w ww.  ja v a 2s  .c  o  m*/
        public int getConnectTimeout() {
            return (int) config.getTimeAsMs(CONNETION_TIMEOUT);
        }

        @Override
        public int getSocketTimeout() {
            return (int) config.getTimeAsMs(SOCKET_TIMEOUT);
        }
    };

    HttpClientBuilder builder = HttpClientBuilder.create().disableAutomaticRetries().evictExpiredConnections()
            .evictIdleConnections(config.getTimeAsMs(CONNECTION_IDLE_TIMEOUT), TimeUnit.MILLISECONDS)
            .setConnectionManager(new BasicHttpClientConnectionManager())
            .setConnectionReuseStrategy(new DefaultConnectionReuseStrategy()).setDefaultRequestConfig(reqConfig)
            .setMaxConnTotal(1).setUserAgent("livy-client-http");

    this.server = uri;
    this.client = builder.build();
    this.mapper = new ObjectMapper();
}

From source file:com.mirth.connect.connectors.file.FileConnectorServlet.java

protected ConnectionTestResponse testReadOrWrite(String channelId, String channelName, String host,
        String username, String password, SchemeProperties schemeProperties, FileScheme scheme,
        String timeoutString, boolean secure, boolean passive, boolean read) {
    try {/*  ww w  . j  av  a  2  s.c o m*/
        host = replacer.replaceValues(host, channelId, channelName);
        username = replacer.replaceValues(username, channelId, channelName);
        password = replacer.replaceValues(password, channelId, channelName);

        SftpSchemeProperties sftpProperties = null;
        if (schemeProperties instanceof SftpSchemeProperties) {
            sftpProperties = (SftpSchemeProperties) schemeProperties;

            sftpProperties
                    .setKeyFile(replacer.replaceValues(sftpProperties.getKeyFile(), channelId, channelName));
            sftpProperties.setPassPhrase(
                    replacer.replaceValues(sftpProperties.getPassPhrase(), channelId, channelName));
            sftpProperties.setKnownHostsFile(
                    replacer.replaceValues(sftpProperties.getKnownHostsFile(), channelId, channelName));
            sftpProperties.setConfigurationSettings(
                    replacer.replaceValues(sftpProperties.getConfigurationSettings(), channelId, channelName));
        }

        int timeout = Integer.parseInt(timeoutString);

        URI address = FileConnector.getEndpointURI(host, scheme, secure);
        String addressHost = address.getHost();
        int port = address.getPort();
        String dir = address.getPath();

        String hostDisplayName = "";
        if (!scheme.equals(FileScheme.FILE)) {
            hostDisplayName = scheme.getDisplayName() + "://" + address.getHost();
        }
        hostDisplayName += dir;

        FileSystemConnectionFactory factory = new FileSystemConnectionFactory(scheme,
                new FileSystemConnectionOptions(username, password, sftpProperties), addressHost, port, passive,
                secure, timeout);

        FileSystemConnection connection = null;

        try {
            connection = ((PooledObject<FileSystemConnection>) factory.makeObject()).getObject();

            if (read && connection.canRead(dir) || !read && connection.canWrite(dir)) {
                return new ConnectionTestResponse(ConnectionTestResponse.Type.SUCCESS,
                        "Successfully connected to: " + hostDisplayName);
            } else {
                return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE,
                        "Unable to connect to: " + hostDisplayName);
            }
        } catch (Exception e) {
            return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE,
                    "Unable to connect to: " + hostDisplayName + ", Reason: " + e.getMessage());
        } finally {
            if (connection != null) {
                connection.destroy();
            }
        }
    } catch (Exception e) {
        throw new MirthApiException(e);
    }
}

From source file:com.thoughtworks.go.util.command.UrlArgument.java

@Override
public String forDisplay() {
    try {//from ww  w  .  ja v  a  2s .c o m
        URI uri = new URI(sanitizeUrl());
        if (uri.getUserInfo() != null) {
            uri = new URI(uri.getScheme(), clean(uri.getScheme(), uri.getUserInfo()), uri.getHost(),
                    uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
        }
        return uri.toString();
    } catch (URISyntaxException e) {
        return url;
    }
}

From source file:org.zlogic.vogon.web.PersistenceConfiguration.java

/**
 * Returns the JPA configuration overrides for database configuration
 *
 * @return the map of JPA configuration variables to override for the
 * database connection//from  ww  w.  ja v a 2 s . co m
 */
protected Map<String, Object> getDatabaseConfiguration() {
    Map<String, Object> jpaProperties = new HashMap<>();
    boolean fallback = true;
    if (serverTypeDetector.getServerType() != ServerTypeDetector.ServerType.WILDFLY)
        jpaProperties.put("hibernate.connection.provider_class",
                "org.hibernate.connection.C3P0ConnectionProvider"); //NOI18N
    if (serverTypeDetector.getDatabaseType() == ServerTypeDetector.DatabaseType.POSTGRESQL) {
        String dbURL = null;
        if (serverTypeDetector.getCloudType() == ServerTypeDetector.CloudType.HEROKU)
            dbURL = System.getenv("DATABASE_URL"); //NOI18N
        else if (serverTypeDetector.getCloudType() == ServerTypeDetector.CloudType.OPENSHIFT)
            dbURL = System.getenv("OPENSHIFT_POSTGRESQL_DB_URL") + "/" + System.getenv("OPENSHIFT_APP_NAME"); //NOI18N
        try {
            URI dbUri = new URI(dbURL);
            String dbConnectionURL = "jdbc:postgresql://" + dbUri.getHost() + ":" + dbUri.getPort()
                    + dbUri.getPath(); //NOI18N //NOI18N
            String[] usernamePassword = dbUri.getUserInfo().split(":", 2); //NOI18N
            jpaProperties.put("javax.persistence.jdbc.url", dbConnectionURL); //NOI18N
            jpaProperties.put("javax.persistence.jdbc.user", usernamePassword[0]); //NOI18N
            jpaProperties.put("javax.persistence.jdbc.password", usernamePassword[1]); //NOI18N
            jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect"); //NOI18N
            jpaProperties.put("hibernate.connection.driver_class", "org.postgresql.Driver"); //NOI18N
            fallback = false;
        } catch (Exception ex) {
            log.error(messages.getString("ERROR_EXTRACTING_DATABASE_CONFIGURATION"), ex);
        }
    }
    if (serverTypeDetector.getDatabaseType() == ServerTypeDetector.DatabaseType.H2 || fallback) {
        String dbConnectionURL = MessageFormat.format("jdbc:h2:{0}/Vogon",
                new Object[] { getH2DatabasePath() }); //NOI18N
        jpaProperties.put("javax.persistence.jdbc.url", dbConnectionURL); //NOI18N
        jpaProperties.put("javax.persistence.jdbc.user", ""); //NOI18N
        jpaProperties.put("javax.persistence.jdbc.password", ""); //NOI18N
        jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); //NOI18N
        jpaProperties.put("hibernate.connection.driver_class", "org.h2.Driver"); //NOI18N
    }
    return jpaProperties;
}

From source file:com.bazaarvoice.seo.sdk.util.BVUtility.java

public static String removeBVParameters(String url) {
    String newUrl = url;//from w ww.  ja  v a 2 s  . c  o m
    if (newUrl.contains("bvstate=")) {
        // Handle usecase with more parameters after bvstate
        newUrl = newUrl.replaceAll(BVConstant.BVSTATE_REGEX_WITH_TRAILING_SEPARATOR, "");

        // Handle usecase where bvstate is the last parameter
        if (newUrl.endsWith("?") | newUrl.endsWith("&")) {
            newUrl = newUrl.substring(0, newUrl.length() - 1);
        }
        if (newUrl.endsWith(BVConstant.ESCAPED_FRAGMENT_MULTIVALUE_SEPARATOR)) {
            newUrl = newUrl.substring(0, newUrl.length() - 3);
        }
    }

    if (hasBVQueryParameters(newUrl)) {
        final URI uri;
        try {
            uri = new URI(newUrl);
        } catch (URISyntaxException e) {
            return newUrl;
        }

        try {
            String newQuery = null;
            if (uri.getQuery() != null && uri.getQuery().length() > 0) {
                List<NameValuePair> newParameters = new ArrayList<NameValuePair>();
                List<NameValuePair> parameters = URLEncodedUtils.parse(uri.getQuery(),
                        Charset.forName("UTF-8"));
                for (NameValuePair parameter : parameters) {
                    if (!bvQueryParameters.contains(parameter.getName())) {
                        newParameters.add(parameter);
                    }
                }
                newQuery = newParameters.size() > 0
                        ? URLEncodedUtils.format(newParameters, Charset.forName("UTF-8"))
                        : null;
            }

            return new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), newQuery, null).toString();
        } catch (URISyntaxException e) {
            return newUrl;
        }
    }
    return newUrl;
}

From source file:io.druid.firehose.s3.StaticS3FirehoseFactory.java

@Override
public Firehose connect(StringInputRowParser firehoseParser) throws IOException {
    Preconditions.checkNotNull(s3Client, "null s3Client");

    final LinkedList<URI> objectQueue = Lists.newLinkedList(uris);

    return new FileIteratingFirehose(new Iterator<LineIterator>() {
        @Override/*  www  . j a  v a2  s .co  m*/
        public boolean hasNext() {
            return !objectQueue.isEmpty();
        }

        @Override
        public LineIterator next() {
            final URI nextURI = objectQueue.poll();

            final String s3Bucket = nextURI.getAuthority();
            final S3Object s3Object = new S3Object(
                    nextURI.getPath().startsWith("/") ? nextURI.getPath().substring(1) : nextURI.getPath());

            log.info("Reading from bucket[%s] object[%s] (%s)", s3Bucket, s3Object.getKey(), nextURI);

            try {
                final InputStream innerInputStream = s3Client
                        .getObject(new S3Bucket(s3Bucket), s3Object.getKey()).getDataInputStream();

                final InputStream outerInputStream = s3Object.getKey().endsWith(".gz")
                        ? CompressionUtils.gzipInputStream(innerInputStream)
                        : innerInputStream;

                return IOUtils.lineIterator(
                        new BufferedReader(new InputStreamReader(outerInputStream, Charsets.UTF_8)));
            } catch (Exception e) {
                log.error(e, "Exception reading from bucket[%s] object[%s]", s3Bucket, s3Object.getKey());

                throw Throwables.propagate(e);
            }
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }, firehoseParser);
}

From source file:com.ecsteam.cloudlaunch.services.jenkins.JenkinsService.java

public QueuedBuildResponse triggerBuild() {
    String urlTemplate = "{baseUrl}/job/{jobName}/build";

    RestTemplate template = new RestTemplate();
    ResponseEntity<Object> response = template.exchange(urlTemplate, HttpMethod.POST, getAuthorizationEntity(),
            Object.class, baseUrl, jobName);

    if (HttpStatus.CREATED.equals(response.getStatusCode())) {
        HttpHeaders headers = response.getHeaders();
        URI queueUri = headers.getLocation();

        String last = null;/*  ww  w.  j a va2  s  .  c  o  m*/
        String current = null;
        String next = null;

        String[] parts = queueUri.getPath().split("/");

        QueuedBuildResponse responseObject = new QueuedBuildResponse();
        for (int i = parts.length - 1; i >= 0; --i) {
            last = parts[i];
            current = parts[i - 1];
            next = parts[i - 2];

            if ("queue".equals(next) && "item".equals(current)) {
                responseObject = new QueuedBuildResponse();
                responseObject.setMonitorUri(String.format("/services/builds/queue/%s", last));

                return responseObject;
            }
        }
    }
    return null;
}

From source file:org.openscore.lang.cli.utils.CompilerHelperTest.java

@Test
public void testLoadInputsFromFile() throws Exception {
    Map<String, Serializable> expected = new HashMap<>();
    expected.put("host", "localhost");
    expected.put("port", "22");
    URI inputsFromFile = getClass().getResource("/inputs/inputs.yaml").toURI();
    Map<String, ? extends Serializable> result = compilerHelper
            .loadInputsFromFile(Arrays.asList(inputsFromFile.getPath()));
    Assert.assertNotNull(result);//from w w  w .j  av a 2s . com
    Assert.assertEquals(expected, result);
}

From source file:org.ow2.chameleon.fuchsia.importer.push.SubscriptionImporter.java

@Override
protected void useImportDeclaration(ImportDeclaration importDeclaration) throws BinderException {

    LOG.info("adding import declaration {}", importDeclaration);

    try {//from  w ww.j  a  v a  2  s.com

        Map<String, Object> data = importDeclaration.getMetadata();

        String hub = data.get("push.hub.url").toString();
        String hubTopic = data.get("push.hub.topic").toString();
        String callback = data.get("push.subscriber.callback").toString();

        URI callbackURI = new URI(callback);

        httpService.registerServlet(callbackURI.getPath(),
                new CallbackServlet(eventAdmin, importDeclaration, this), null, null);

        int statusCode = subscribe(hub, hubTopic, callback, null, null);

        if (statusCode == HttpStatus.SC_NO_CONTENT) {
            LOG.info(
                    "the status code of the subscription is 204: the request was verified and that the subscription is active");
        } else if (statusCode == HttpStatus.SC_ACCEPTED) {
            LOG.info(
                    "the status code of the subscription is 202: the subscription has yet to be verified (asynchronous verification)");
        } else {
            LOG.info("the status code of the subscription is {}", statusCode);
        }

        callbacksRegistered.add(callback);

        super.handleImportDeclaration(importDeclaration);
    } catch (Exception e) {
        LOG.error("failed to import declaration, with the message: " + e.getMessage(), e);
    }

}

From source file:com.cloud.utils.rest.BasicRestClient.java

private void logRequestExecution(final HttpUriRequest request) {
    final URI uri = request.getURI();
    String query = uri.getQuery();
    query = query != null ? "?" + query : "";
    s_logger.debug("Executig " + request.getMethod() + " request on " + clientContext.getTargetHost()
            + uri.getPath() + query);
}