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:org.coffeebreaks.validators.w3c.W3cMarkupValidator.java

private ValidationResult validateW3cMarkup(String type, String value, boolean get) throws IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpRequestBase method;//www. j av a  2s  .  com
    if (get) {
        List<NameValuePair> qParams = new ArrayList<NameValuePair>();
        qParams.add(new BasicNameValuePair("output", "soap12"));
        qParams.add(new BasicNameValuePair(type, value));

        try {
            URI uri = new URI(baseUrl + (baseUrl.endsWith("/") ? "" : "/") + "check");
            URI uri2 = URIUtils.createURI(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath(),
                    URLEncodedUtils.format(qParams, "UTF-8"), null);
            method = new HttpGet(uri2);
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException("invalid uri. Check your baseUrl " + baseUrl, e);
        }
    } else {
        HttpPost httpPost = new HttpPost(baseUrl + (baseUrl.endsWith("/") ? "" : "/") + "check");
        List<NameValuePair> formParams = new ArrayList<NameValuePair>();
        formParams.add(new BasicNameValuePair("output", "soap12"));
        formParams.add(new BasicNameValuePair(type, value));
        UrlEncodedFormEntity requestEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
        httpPost.setEntity(requestEntity);
        method = httpPost;
    }
    HttpResponse response = httpclient.execute(method);
    HttpEntity responseEntity = response.getEntity();
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode >= HttpStatus.SC_BAD_REQUEST) {
        throw new IllegalStateException(
                "Unexpected HTTP status code: " + statusCode + ". Implementation error ?");
    }
    if (responseEntity == null) {
        throw new IllegalStateException(
                "No entity but HTTP status code: " + statusCode + ". Server side error ?");
    }

    InputStream entityContentInputStream = responseEntity.getContent();
    StringWriter output = new StringWriter();
    IOUtils.copy(entityContentInputStream, output, "UTF-8");
    final String soap = output.toString();

    // we can use the response headers instead of the soap
    // final W3cSoapValidatorSoapOutput soapObject = parseSoapObject(soap);

    String headerValue = getHeaderValue(response, "X-W3C-Validator-Status");
    final boolean indeterminate = headerValue.equals("Abort");
    final int errorCount = Integer.parseInt(getHeaderValue(response, "X-W3C-Validator-Errors"));
    final int warningCount = Integer.parseInt(getHeaderValue(response, "X-W3C-Validator-Warnings"));

    return new ValidationResult() {
        public boolean isResultIndeterminate() {
            return indeterminate;
        }

        public int getErrorCount() {
            return errorCount;
        }

        public int getWarningCount() {
            return warningCount;
        }

        public String getResponseContent() {
            return soap;
        }
    };
}

From source file:io.seldon.external.ExternalItemRecommendationAlgorithm.java

@Override
public ItemRecommendationResultSet recommend(String client, Long user, Set<Integer> dimensions,
        int maxRecsCount, RecommendationContext ctxt, List<Long> recentItemInteractions) {
    long timeNow = System.currentTimeMillis();
    String recommenderName = ctxt.getOptsHolder().getStringOption(ALG_NAME_PROPERTY_NAME);
    String baseUrl = ctxt.getOptsHolder().getStringOption(URL_PROPERTY_NAME);
    if (ctxt.getInclusionKeys().isEmpty()) {
        logger.warn("Cannot get external recommendations are no includers were used. Returning 0 results");
        return new ItemRecommendationResultSet(recommenderName);
    }/*from   w w  w .  j  a va  2  s .  c om*/
    URI uri = URI.create(baseUrl);
    try {
        URIBuilder builder = new URIBuilder().setScheme("http").setHost(uri.getHost()).setPort(uri.getPort())
                .setPath(uri.getPath()).setParameter("client", client).setParameter("user_id", user.toString())
                .setParameter("recent_interactions", StringUtils.join(recentItemInteractions, ","))
                .setParameter("dimensions", StringUtils.join(dimensions, ","))
                .setParameter("exclusion_items", StringUtils.join(ctxt.getExclusionItems(), ","))
                .setParameter("data_key", StringUtils.join(ctxt.getInclusionKeys(), ","))
                .setParameter("limit", String.valueOf(maxRecsCount));
        if (ctxt.getCurrentItem() != null)
            builder.setParameter("item_id", ctxt.getCurrentItem().toString());
        uri = builder.build();
    } catch (URISyntaxException e) {
        logger.error("Couldn't create URI for external recommender with name " + recommenderName, e);
        return new ItemRecommendationResultSet(recommenderName);
    }
    HttpContext context = HttpClientContext.create();
    HttpGet httpGet = new HttpGet(uri);
    try {
        if (logger.isDebugEnabled())
            logger.debug("Requesting " + httpGet.getURI().toString());
        CloseableHttpResponse resp = httpClient.execute(httpGet, context);
        try {
            if (resp.getStatusLine().getStatusCode() == 200) {
                ConsumerBean c = new ConsumerBean(client);
                ObjectReader reader = mapper.reader(AlgsResult.class);
                AlgsResult recs = reader.readValue(resp.getEntity().getContent());
                List<ItemRecommendationResultSet.ItemRecommendationResult> results = new ArrayList<>(
                        recs.recommended.size());
                for (AlgResult rec : recs.recommended) {
                    Map<String, Integer> attrDimsCandidate = itemService.getDimensionIdsForItem(c, rec.item);
                    if (CollectionUtils.containsAny(dimensions, attrDimsCandidate.values())
                            || dimensions.contains(Constants.DEFAULT_DIMENSION)) {
                        if (logger.isDebugEnabled())
                            logger.debug("Adding item " + rec.item);
                        results.add(
                                new ItemRecommendationResultSet.ItemRecommendationResult(rec.item, rec.score));
                    } else {
                        if (logger.isDebugEnabled())
                            logger.debug("Rejecting item " + rec.item + " as not in dimensions " + dimensions);
                    }
                }
                if (logger.isDebugEnabled())
                    logger.debug("External recommender took " + (System.currentTimeMillis() - timeNow) + "ms");
                return new ItemRecommendationResultSet(results, recommenderName);
            } else {
                logger.error(
                        "Couldn't retrieve recommendations from external recommender -- bad http return code: "
                                + resp.getStatusLine().getStatusCode());
            }
        } finally {
            if (resp != null)
                resp.close();
        }
    } catch (IOException e) {
        logger.error("Couldn't retrieve recommendations from external recommender - ", e);
    } catch (Exception e) {
        logger.error("Couldn't retrieve recommendations from external recommender - ", e);
    }
    return new ItemRecommendationResultSet(recommenderName);
}

From source file:com.linkedin.r2.message.rest.QueryTunnelUtil.java

/**
 * @param request   a RestRequest object to be encoded as a tunneled POST
 * @param requestContext a RequestContext object associated with the request
 * @param threshold the size of the query params above which the request will be encoded
 *
 * @return an encoded RestRequest//from   www  . jav a 2s .co m
 */
public static RestRequest encode(final RestRequest request, RequestContext requestContext, int threshold)
        throws URISyntaxException, MessagingException, IOException {
    URI uri = request.getURI();

    // Check to see if we should tunnel this request by testing the length of the query
    // if the query is NULL, we won't bother to encode.
    // 0 length is a special case that could occur with a url like http://www.foo.com?
    // which we don't want to encode, because we'll lose the "?" in the process
    // Otherwise only encode queries whose length is greater than or equal to the
    // threshold value.

    String query = uri.getRawQuery();

    boolean forceQueryTunnel = requestContext.getLocalAttr(R2Constants.FORCE_QUERY_TUNNEL) != null
            && (Boolean) requestContext.getLocalAttr(R2Constants.FORCE_QUERY_TUNNEL);

    if (query == null || query.length() == 0 || (query.length() < threshold && !forceQueryTunnel)) {
        return request;
    }

    RestRequestBuilder requestBuilder = new RestRequestBuilder(request);

    // reconstruct URI without query
    uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), null,
            uri.getFragment());

    // If there's no existing body, just pass the request as x-www-form-urlencoded
    ByteString entity = request.getEntity();
    if (entity == null || entity.length() == 0) {
        requestBuilder.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED);
        requestBuilder.setEntity(ByteString.copyString(query, Data.UTF_8_CHARSET));
    } else {
        // If we have a body, we must preserve it, so use multipart/mixed encoding

        MimeMultipart multi = createMultiPartEntity(entity, request.getHeader(HEADER_CONTENT_TYPE), query);
        requestBuilder.setHeader(HEADER_CONTENT_TYPE, multi.getContentType());
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        multi.writeTo(os);
        requestBuilder.setEntity(ByteString.copy(os.toByteArray()));
    }

    // Set the base uri, supply the original method in the override header, and change method to POST
    requestBuilder.setURI(uri);
    requestBuilder.setHeader(HEADER_METHOD_OVERRIDE, requestBuilder.getMethod());
    requestBuilder.setMethod(RestMethod.POST);

    return requestBuilder.build();
}

From source file:io.syndesis.runtime.credential.CredentialITCase.java

@Test
public void shouldInitiateCredentialFlow() throws UnsupportedEncodingException {
    final ResponseEntity<AcquisitionResponse> acquisitionResponse = post(
            "/api/v1/connectors/test-provider/credentials", Collections.singletonMap("returnUrl", "/ui#state"),
            AcquisitionResponse.class, tokenRule.validToken(), HttpStatus.ACCEPTED);

    assertThat(acquisitionResponse.hasBody()).as("Should present a acquisition response in the HTTP body")
            .isTrue();//from www.ja va2  s  .c  om

    final AcquisitionResponse response = acquisitionResponse.getBody();
    assertThat(response.getType()).isEqualTo(Type.OAUTH2);

    final String redirectUrl = response.getRedirectUrl();
    assertThat(redirectUrl).as("Should redirect to Salesforce and containthe correct callback URL")
            .startsWith("https://test/oauth2/authorize?client_id=testClientId&response_type=code&redirect_uri=")
            .contains(encode("/api/v1/credentials/callback", "ASCII"));

    final MultiValueMap<String, String> params = UriComponentsBuilder.fromHttpUrl(redirectUrl).build()
            .getQueryParams();

    final String state = params.getFirst("state");

    assertThat(state).as("state parameter should be set").isNotEmpty();

    final State responseStateInstruction = response.state();
    assertThat(responseStateInstruction).as("acquisition response should contain the state instruction")
            .isNotNull();
    assertThat(responseStateInstruction.persist()).isEqualByComparingTo(State.Persist.COOKIE);
    assertThat(responseStateInstruction.spec()).isNotEmpty();

    final CredentialFlowState credentialFlowState = clientSideState
            .restoreFrom(Cookie.valueOf(responseStateInstruction.spec()), CredentialFlowState.class);

    final CredentialFlowState expected = new OAuth2CredentialFlowState.Builder().key("test-state")
            .providerId("test-provider").build();

    assertThat(credentialFlowState).as("The flow state should be as expected")
            .isEqualToIgnoringGivenFields(expected, "returnUrl");
    final URI returnUrl = credentialFlowState.getReturnUrl();
    assertThat(returnUrl).isNotNull();
    assertThat(returnUrl.isAbsolute()).isTrue();
    assertThat(returnUrl.getPath()).isEqualTo("/ui");
    assertThat(returnUrl.getFragment()).isEqualTo("state");
}

From source file:com.sixsq.slipstream.DeploymentController.java

public File downloadFile(URI uri, File dir) throws MojoExecutionException {

    String path = uri.getPath();
    Pattern pattern = Pattern.compile(".*/(.*)");
    Matcher matcher = pattern.matcher(path);
    String filename = "";
    if (matcher.matches()) {
        filename = matcher.group(1);/*from w  w w.java 2s  .  c  o m*/
    }

    File file = new File(dir, filename);

    InputStream is = null;
    FileOutputStream out = null;

    try {

        HttpGet httpget = new HttpGet(uri);
        HttpResponse response = client.execute(httpget);
        HttpEntity entity = response.getEntity();

        is = entity.getContent();
        out = new FileOutputStream(file);

        byte[] buffer = new byte[BUFFER_SIZE];
        int count = -1;
        while ((count = is.read(buffer)) != -1) {
            out.write(buffer, 0, count);
        }
        out.flush();
        out.close();
    } catch (IOException e) {
        String msg = "error writing file " + uri.toString();
        throw new MojoExecutionException(msg, e);
    } finally {
        closeReliably(is);
        closeReliably(out);
    }

    return file;
}

From source file:net.ostis.scpdev.wizards.ExistingRepositoryGroup.java

/**
 * Return the path on the location field.
 *//*from   w  w w . j a v  a2  s.  c  o m*/
private String getPathFromLocationField() {
    URI fieldURI;
    try {
        fieldURI = new URI(locationPathField.getText());
    } catch (URISyntaxException e) {
        return locationPathField.getText();
    }
    return fieldURI.getPath();
}

From source file:com.jgoetsch.eventtrader.source.SocketIOWebSocketMsgSource.java

protected String getTokenUrl() throws IOException, URISyntaxException {
    URI base = new URI(getUrl());
    BufferedReader tokenReader = new BufferedReader(
            new InputStreamReader(new URI("http", base.getUserInfo(), base.getHost(), base.getPort(),
                    base.getPath(), base.getQuery(), base.getFragment()).toURL().openStream()));
    String token = tokenReader.readLine();
    tokenReader.close();// ww w.ja  v a2 s  .  c  o  m

    String r[] = token.split(":");
    String comp[] = getUrl().split("\\?");
    if (!comp[0].endsWith("/"))
        comp[0] += '/';
    return comp[0] + "websocket/" + r[0] + (comp.length > 0 ? "?" + comp[1] : "");
}

From source file:com.buaa.cfs.utils.NetUtils.java

/**
 * Resolve the uri's hostname and add the default port if not in the uri
 *
 * @param uri         to resolve//from  w  w w. ja  v a2 s. c  o m
 * @param defaultPort if none is given
 *
 * @return URI
 */
public static URI getCanonicalUri(URI uri, int defaultPort) {
    // skip if there is no authority, ie. "file" scheme or relative uri
    String host = uri.getHost();
    if (host == null) {
        return uri;
    }
    String fqHost = canonicalizeHost(host);
    int port = uri.getPort();
    // short out if already canonical with a port
    if (host.equals(fqHost) && port != -1) {
        return uri;
    }
    // reconstruct the uri with the canonical host and port
    try {
        uri = new URI(uri.getScheme(), uri.getUserInfo(), fqHost, (port == -1) ? defaultPort : port,
                uri.getPath(), uri.getQuery(), uri.getFragment());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
    return uri;
}

From source file:io.cloudslang.lang.cli.utils.CompilerHelperTest.java

@Test
public void testDependenciesFileParentFolder() throws Exception {
    URI flowPath = getClass().getResource("/executables/dir3/flow.sl").toURI();
    URI opPath = getClass().getResource("/executables/dir3/dir3_1/test_op.sl").toURI();
    compilerHelper.compile(flowPath.getPath(), null);
    Mockito.verify(slang).compile(SlangSource.fromFile(flowPath),
            Sets.newHashSet(SlangSource.fromFile(opPath), SlangSource.fromFile(flowPath)));
}

From source file:org.opencastproject.distribution.download.DownloadDistributionServiceImplTest.java

@Before
public void setUp() throws Exception {
    final File mediaPackageRoot = new File(getClass().getResource("/mediapackage.xml").toURI()).getParentFile();
    MediaPackageBuilder builder = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder();
    builder.setSerializer(new DefaultMediaPackageSerializerImpl(mediaPackageRoot));
    InputStream is = null;/*from w w  w  .  ja v a 2s.  c  om*/
    try {
        is = getClass().getResourceAsStream("/mediapackage.xml");
        mp = builder.loadFromXml(is);
    } finally {
        IOUtils.closeQuietly(is);
    }

    distributionRoot = new File(mediaPackageRoot, "static");
    service = new DownloadDistributionServiceImpl();

    StatusLine statusLine = EasyMock.createNiceMock(StatusLine.class);
    EasyMock.expect(statusLine.getStatusCode()).andReturn(HttpServletResponse.SC_OK).anyTimes();
    EasyMock.replay(statusLine);

    HttpResponse response = EasyMock.createNiceMock(HttpResponse.class);
    EasyMock.expect(response.getStatusLine()).andReturn(statusLine).anyTimes();
    EasyMock.replay(response);

    TrustedHttpClient httpClient = EasyMock.createNiceMock(TrustedHttpClient.class);
    EasyMock.expect(httpClient.execute((HttpUriRequest) EasyMock.anyObject())).andReturn(response).anyTimes();
    EasyMock.replay(httpClient);

    User anonymous = new User("anonymous", DefaultOrganization.DEFAULT_ORGANIZATION_ID,
            new String[] { DefaultOrganization.DEFAULT_ORGANIZATION_ANONYMOUS });
    UserDirectoryService userDirectoryService = EasyMock.createMock(UserDirectoryService.class);
    EasyMock.expect(userDirectoryService.loadUser((String) EasyMock.anyObject())).andReturn(anonymous)
            .anyTimes();
    EasyMock.replay(userDirectoryService);
    service.setUserDirectoryService(userDirectoryService);

    Organization organization = new DefaultOrganization();
    OrganizationDirectoryService organizationDirectoryService = EasyMock
            .createMock(OrganizationDirectoryService.class);
    EasyMock.expect(organizationDirectoryService.getOrganization((String) EasyMock.anyObject()))
            .andReturn(organization).anyTimes();
    EasyMock.replay(organizationDirectoryService);
    service.setOrganizationDirectoryService(organizationDirectoryService);

    SecurityService securityService = EasyMock.createNiceMock(SecurityService.class);
    EasyMock.expect(securityService.getUser()).andReturn(anonymous).anyTimes();
    EasyMock.expect(securityService.getOrganization()).andReturn(organization).anyTimes();
    EasyMock.replay(securityService);
    service.setSecurityService(securityService);

    serviceRegistry = new ServiceRegistryInMemoryImpl(service, securityService, userDirectoryService,
            organizationDirectoryService);
    service.setServiceRegistry(serviceRegistry);
    service.setTrustedHttpClient(httpClient);
    service.distributionDirectory = distributionRoot;
    service.serviceUrl = UrlSupport.DEFAULT_BASE_URL;

    final Workspace workspace = EasyMock.createNiceMock(Workspace.class);
    service.setWorkspace(workspace);

    EasyMock.expect(workspace.get((URI) EasyMock.anyObject())).andAnswer(new IAnswer<File>() {
        @Override
        public File answer() throws Throwable {
            final URI uri = (URI) EasyMock.getCurrentArguments()[0];
            final String[] pathElems = uri.getPath().split("/");
            final String file = pathElems[pathElems.length - 1];
            return new File(mediaPackageRoot, file);
        }
    }).anyTimes();
    EasyMock.replay(workspace);
}