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.twitter.distributedlog.metadata.ZkMetadataResolver.java

@Override
public DLMetadata resolve(URI uri) throws IOException {
    String dlPath = uri.getPath();
    PathUtils.validatePath(dlPath);/*w ww .  j av  a2s  .  c o m*/
    // Normal case the dl metadata is stored in the last segment
    // so lookup last segment first.
    String[] parts = StringUtils.split(dlPath, '/');
    if (null == parts || 0 == parts.length) {
        throw new IOException("Invalid dlPath to resolve dl metadata : " + dlPath);
    }
    for (int i = parts.length; i >= 0; i--) {
        String pathToResolve = String.format("/%s", StringUtils.join(parts, '/', 0, i));
        byte[] data;
        try {
            data = zkc.get().getData(pathToResolve, false, new Stat());
        } catch (KeeperException.NoNodeException nne) {
            continue;
        } catch (KeeperException ke) {
            throw new IOException("Fail to resolve dl path : " + pathToResolve);
        } catch (InterruptedException ie) {
            throw new IOException("Interrupted when resolving dl path : " + pathToResolve);
        }
        if (null == data || data.length == 0) {
            continue;
        }
        try {
            return DLMetadata.deserialize(uri, data);
        } catch (IOException ie) {
        }
    }
    throw new IOException("No bkdl config bound under dl path : " + dlPath);
}

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

/**
 * @param request   a RestRequest object to be encoded as a tunneled POST
 * @param threshold the size of the query params above which the request will be encoded
 *
 * @return an encoded RestRequest/*ww  w.  java2s.  c  o m*/
 */
public static RestRequest encode(final RestRequest request, 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();

    if (query == null || query.length() == 0 || query.length() < threshold) {
        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:com.microsoft.tfs.core.util.URIUtils.java

/**
 * <p>//from   w ww  .  j ava  2 s.c  om
 * Ensures that all the components of the {@link URI} are in lower-case.
 * </p>
 *
 * <p>
 * If the specified {@link URI} is opaque, it is returned. Otherwise, a new
 * {@link URI} is returned that is identical to the specified {@link URI}
 * except that the components (scheme, hostname, path) are converted to
 * their lower case equivalents (in a generic locale.)
 * </p>
 *
 * @param uri
 *        a {@link URI} to check (must not be <code>null</code>)
 * @return a {@link URI} as described above (never <code>null</code>)
 */
public static URI toLowerCase(final URI uri) {
    Check.notNull(uri, "uri"); //$NON-NLS-1$

    if (uri.isOpaque()) {
        return uri;
    }

    final String scheme = uri.getScheme() != null ? uri.getScheme().toLowerCase(LocaleUtil.ROOT) : null;
    final String authority = uri.getAuthority() != null ? uri.getAuthority().toLowerCase(LocaleUtil.ROOT)
            : null;
    final String path = uri.getPath() != null ? uri.getPath().toLowerCase(LocaleUtil.ROOT) : null;
    final String query = uri.getQuery() != null ? uri.getQuery().toLowerCase(LocaleUtil.ROOT) : null;
    final String fragment = uri.getFragment() != null ? uri.getFragment().toLowerCase(LocaleUtil.ROOT) : null;

    return newURI(scheme, authority, path, query, fragment);
}

From source file:com.legstar.codegen.tasks.SourceToXsdCobolTask.java

/**
 * Converts a URI into a package name. We assume a hierarchical,
 * server-based URI with the following syntax:
 * [scheme:][//host[:port]][path][?query][#fragment]
 * The package name is derived from host, path and fragment.
 * /*from  w w  w  .  ja  v a  2s.  co  m*/
 * @param namespaceURI the input namespace URI
 * @return the result package name
 */
public static String packageFromURI(final URI namespaceURI) {

    StringBuilder result = new StringBuilder();
    URI nURI = namespaceURI.normalize();
    boolean firstToken = true;

    /*
     * First part of package name is built from host with tokens in
     * reverse order.
     */
    if (nURI.getHost() != null && nURI.getHost().length() != 0) {
        Vector<String> v = new Vector<String>();
        StringTokenizer t = new StringTokenizer(nURI.getHost(), ".");
        while (t.hasMoreTokens()) {
            v.addElement(t.nextToken());
        }

        for (int i = v.size(); i > 0; i--) {
            if (!firstToken) {
                result.append('.');
            } else {
                firstToken = false;
            }
            result.append(v.get(i - 1));
        }
    }

    /* Next part of package is built from the path tokens */
    if (nURI.getPath() != null && nURI.getPath().length() != 0) {
        Vector<String> v = new Vector<String>();
        StringTokenizer t = new StringTokenizer(nURI.getPath(), "/");
        while (t.hasMoreTokens()) {
            v.addElement(t.nextToken());
        }

        for (int i = 0; i < v.size(); i++) {
            String token = v.get(i);
            /* ignore situations such as /./../ */
            if (token.equals(".") || token.equals("..")) {
                continue;
            }
            if (!firstToken) {
                result.append('.');
            } else {
                firstToken = false;
            }
            result.append(v.get(i));
        }
    }

    /* Finally append any fragment */
    if (nURI.getFragment() != null && nURI.getFragment().length() != 0) {
        if (!firstToken) {
            result.append('.');
        } else {
            firstToken = false;
        }
        result.append(nURI.getFragment());
    }

    /*
     * By convention, namespaces are lowercase and should not contain
     * invalid Java identifiers
     */
    String s = result.toString().toLowerCase();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
        Character c = s.charAt(i);
        if (Character.isJavaIdentifierPart(c) || c.equals('.')) {
            sb.append(c);
        } else {
            sb.append("_");
        }
    }
    return sb.toString();
}

From source file:com.yoho.core.trace.instrument.web.client.AbstractTraceHttpRequestInterceptor.java

/**
 * Enriches the request with proper headers and publishes
 * the client sent event//from  w w  w.  ja va 2  s  .co m
 */
protected void publishStartEvent(HttpRequest request) {
    URI uri = request.getURI();
    String spanName = uriScheme(uri) + ":" + uri.getPath();
    Span newSpan = this.tracer.createSpan(spanName);
    this.spanInjector.inject(newSpan, request);
    newSpan.logEvent(Span.CLIENT_SEND);
}

From source file:org.broadleafcommerce.core.catalog.service.CatalogURLServiceImpl.java

protected String getLastFragment(String url) {
    URI uri = URI.create(url);
    String path = Optional.fromNullable(uri.getPath()).or("/");
    return path.substring(path.lastIndexOf('/') + 1);
}

From source file:com.ge.predix.acs.commons.web.ResponseEntityBuilderTest.java

@Test
public void testCreatedWithLocation() {
    ResponseEntity<Object> created = ResponseEntityBuilder.created("/report/1", Boolean.FALSE);

    Assert.assertNotNull(created);//from   w  w  w . j a va  2 s.com
    Assert.assertNull(created.getBody());
    Assert.assertEquals(created.getStatusCode(), HttpStatus.CREATED);

    Assert.assertNotNull(created.getHeaders());
    URI location = created.getHeaders().getLocation();
    Assert.assertEquals(location.getPath(), "/report/1");
}

From source file:com.ge.predix.acs.commons.web.ResponseEntityBuilderTest.java

@Test
public void testUpdatedWithLocation() {
    ResponseEntity<Object> created = ResponseEntityBuilder.created("/report/1", Boolean.TRUE);

    Assert.assertNotNull(created);/*from   www . j av a  2 s . co  m*/
    Assert.assertNull(created.getBody());
    Assert.assertEquals(created.getStatusCode(), HttpStatus.NO_CONTENT);

    Assert.assertNotNull(created.getHeaders());
    URI location = created.getHeaders().getLocation();
    Assert.assertEquals(location.getPath(), "/report/1");
}

From source file:com.github.brandtg.pantopod.crawler.FileBasedCrawlingEventHandler.java

@Override
protected boolean shouldExplore(URI url) {
    File outputRoot = new File(outputDir, url.getHost() + File.separator + url.getPath());
    File errFile = new File(outputRoot, ERR_FILE);
    return !outputRoot.exists() && !errFile.exists();
}