Example usage for java.net URI getQuery

List of usage examples for java.net URI getQuery

Introduction

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

Prototype

public String getQuery() 

Source Link

Document

Returns the decoded query component of this URI.

Usage

From source file:org.apache.hadoop.hive.ql.session.DependencyResolver.java

/**
 *
 * @param uri//from  ww  w.ja  va  2 s . c  o  m
 * @return List of URIs of downloaded jars
 * @throws URISyntaxException
 * @throws IOException
 */
public List<URI> downloadDependencies(URI uri) throws URISyntaxException, IOException {
    Map<String, Object> dependencyMap = new HashMap<String, Object>();
    String authority = uri.getAuthority();
    if (authority == null) {
        throw new URISyntaxException(authority, "Invalid url: Expected 'org:module:version', found null");
    }
    String[] authorityTokens = authority.toLowerCase().split(":");

    if (authorityTokens.length != 3) {
        throw new URISyntaxException(authority,
                "Invalid url: Expected 'org:module:version', found " + authority);
    }

    dependencyMap.put("org", authorityTokens[0]);
    dependencyMap.put("module", authorityTokens[1]);
    dependencyMap.put("version", authorityTokens[2]);
    Map<String, Object> queryMap = parseQueryString(uri.getQuery());
    if (queryMap != null) {
        dependencyMap.putAll(queryMap);
    }
    return grab(dependencyMap);
}

From source file:org.opencms.staticexport.CmsDefaultLinkSubstitutionHandler.java

/**
 * @see org.opencms.staticexport.I_CmsLinkSubstitutionHandler#getRootPath(org.opencms.file.CmsObject, java.lang.String, java.lang.String)
 *//*  w  ww  .  j ava 2s.com*/
public String getRootPath(CmsObject cms, String targetUri, String basePath) {

    if (cms == null) {
        // required by unit test cases
        return targetUri;
    }

    URI uri;
    String path;
    String fragment;
    String query;
    String suffix;

    // malformed uri
    try {
        uri = new URI(targetUri);
        path = uri.getPath();

        fragment = uri.getFragment();
        if (fragment != null) {
            fragment = "#" + fragment;
        } else {
            fragment = "";
        }

        query = uri.getQuery();
        if (query != null) {
            query = "?" + query;
        } else {
            query = "";
        }
    } catch (Exception e) {
        if (LOG.isWarnEnabled()) {
            LOG.warn(Messages.get().getBundle().key(Messages.LOG_MALFORMED_URI_1, targetUri), e);
        }
        return null;
    }

    // concatenate query and fragment 
    suffix = query.concat(fragment);

    // opaque URI
    if (uri.isOpaque()) {
        return null;
    }

    // absolute URI (i.e. URI has a scheme component like http:// ...)
    if (uri.isAbsolute()) {
        CmsSiteMatcher matcher = new CmsSiteMatcher(targetUri);
        if (OpenCms.getSiteManager().isMatching(matcher)) {
            if (path.startsWith(OpenCms.getSystemInfo().getOpenCmsContext())) {
                path = path.substring(OpenCms.getSystemInfo().getOpenCmsContext().length());
            }
            boolean isWorkplaceServer = OpenCms.getSiteManager().isWorkplaceRequest(matcher);
            if (isWorkplaceServer) {
                String pathForCurrentSite = cms.getRequestContext().addSiteRoot(path);
                String pathForMatchedSite = cms.getRequestContext()
                        .addSiteRoot(OpenCms.getSiteManager().matchSite(matcher).getSiteRoot(), path);
                String originalSiteRoot = cms.getRequestContext().getSiteRoot();
                String selectedPath = pathForCurrentSite;
                try {
                    cms.getRequestContext().setSiteRoot("");
                    // the path for the current site normally is preferred, but if it doesn't exist and the path for the matched site
                    // does exist, then use the path for the matched site 
                    if (!cms.existsResource(pathForCurrentSite, CmsResourceFilter.ALL)
                            && cms.existsResource(pathForMatchedSite, CmsResourceFilter.ALL)) {
                        selectedPath = pathForMatchedSite;
                    }
                } finally {
                    cms.getRequestContext().setSiteRoot(originalSiteRoot);
                }
                return selectedPath + suffix;
            } else {
                // add the site root of the matching site
                return cms.getRequestContext()
                        .addSiteRoot(OpenCms.getSiteManager().matchSite(matcher).getSiteRoot(), path + suffix);
            }
        } else {
            return null;
        }
    }

    // relative URI (i.e. no scheme component, but filename can still start with "/") 
    String context = OpenCms.getSystemInfo().getOpenCmsContext();
    if ((context != null) && path.startsWith(context)) {
        // URI is starting with opencms context
        String siteRoot = null;
        if (basePath != null) {
            siteRoot = OpenCms.getSiteManager().getSiteRoot(basePath);
        }

        // cut context from path
        path = path.substring(context.length());

        if (siteRoot != null) {
            // special case: relative path contains a site root, i.e. we are in the root site                
            if (!path.startsWith(siteRoot)) {
                // path does not already start with the site root, we have to add this path as site prefix
                return cms.getRequestContext().addSiteRoot(siteRoot, path + suffix);
            } else {
                // since path already contains the site root, we just leave it unchanged
                return path + suffix;
            }
        } else {
            // site root is added with standard mechanism
            return cms.getRequestContext().addSiteRoot(path + suffix);
        }
    }

    // URI with relative path is relative to the given relativePath if available and in a site, 
    // otherwise invalid
    if (CmsStringUtil.isNotEmpty(path) && (path.charAt(0) != '/')) {
        if (basePath != null) {
            String absolutePath;
            int pos = path.indexOf("../../galleries/pics/");
            if (pos >= 0) {
                // HACK: mixed up editor path to system gallery image folder
                return CmsWorkplace.VFS_PATH_SYSTEM + path.substring(pos + 6) + suffix;
            }
            absolutePath = CmsLinkManager.getAbsoluteUri(path, cms.getRequestContext().addSiteRoot(basePath));
            if (OpenCms.getSiteManager().getSiteRoot(absolutePath) != null) {
                return absolutePath + suffix;
            }
            // HACK: some editor components (e.g. HtmlArea) mix up the editor URL with the current request URL 
            absolutePath = CmsLinkManager.getAbsoluteUri(path,
                    cms.getRequestContext().getSiteRoot() + CmsWorkplace.VFS_PATH_EDITORS);
            if (OpenCms.getSiteManager().getSiteRoot(absolutePath) != null) {
                return absolutePath + suffix;
            }
            // HACK: same as above, but XmlContent editor has one path element more
            absolutePath = CmsLinkManager.getAbsoluteUri(path,
                    cms.getRequestContext().getSiteRoot() + CmsWorkplace.VFS_PATH_EDITORS + "xmlcontent/");
            if (OpenCms.getSiteManager().getSiteRoot(absolutePath) != null) {
                return absolutePath + suffix;
            }
        }

        return null;
    }

    // relative URI (= VFS path relative to currently selected site root)
    if (CmsStringUtil.isNotEmpty(path)) {
        return cms.getRequestContext().addSiteRoot(path) + suffix;
    }

    // URI without path (typically local link)
    return suffix;
}

From source file:org.portletbridge.portlet.PortletBridgeServlet.java

/**
 * url pattern should be: http://host:port/context/servlet/id
 *//*from   ww  w  .j a  v  a 2  s . c  o  m*/
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    // get the id
    final String id = portletBridgeService.getIdFromRequestUri(request.getContextPath(),
            request.getRequestURI());
    // look up the data associated with that id from the session
    HttpSession session = request.getSession();
    if (session == null) {
        throw new ServletException(
                resourceBundle.getString("error.nosession") + ", URL=" + request.getRequestURI());
    }
    final PortletBridgeMemento memento = (PortletBridgeMemento) session.getAttribute(mementoSessionKey);
    if (memento == null) {
        throw new ServletException(
                resourceBundle.getString("error.nomemento") + ", URL=" + request.getRequestURI());
    }
    BridgeRequest bridgeRequest = memento.getBridgeRequest(id);
    if (bridgeRequest == null) {
        throw new ServletException(
                resourceBundle.getString("error.nobridgerequest") + ", URL=" + request.getRequestURI());
    }
    final PerPortletMemento perPortletMemento = memento.getPerPortletMemento(bridgeRequest.getPortletId());
    if (perPortletMemento == null) {
        throw new ServletException(
                resourceBundle.getString("error.noperportletmemento") + ", URL=" + request.getRequestURI());
    }

    // go and fetch the data from the backend as appropriate
    URI url = bridgeRequest.getUrl();

    // TODO: if there is a query string, we should create a new bridge request with that query string added
    // TODO: need to clean up how we create bridge requests (i.e. get rid of the pseudorenderresponse)
    if (request.getQueryString() != null && request.getQueryString().trim().length() > 0) {
        try {
            // TODO: may have to change encoding
            // if the url already has a query string add an & instead
            String urlAsString = url.toString();
            url = new URI(urlAsString + ((url.getQuery() != null) ? '&' : '?') + request.getQueryString());
            PseudoRenderResponse renderResponse = createRenderResponse(bridgeRequest);
            bridgeRequest = memento.createBridgeRequest(renderResponse, new DefaultIdGenerator().nextId(), url);
        } catch (URISyntaxException e) {
            throw new ServletException(e.getMessage() + ", doGet(): URL=" + url + ", id=" + id
                    + ", request URI=" + request.getRequestURI(), e);
        }
    }

    log.debug("doGet(): URL=" + url + ", id=" + id + ", request URI=" + request.getRequestURI());

    fetch(request, response, bridgeRequest, memento, perPortletMemento, url);

}

From source file:com.collaborne.jsonschema.validator.plugin.ValidateMojo.java

@VisibleForTesting
protected URITranslatorConfigurationBuilder addSchemaMappings(URITranslatorConfigurationBuilder builder)
        throws MojoExecutionException {
    for (DirectoryURIMapping schemaMapping : schemaMappings) {
        URI uri = schemaMapping.uri;
        if (uri.getFragment() != null) {
            throw new MojoExecutionException("URI " + uri + " must not contain a fragment");
        }/* w w w. j a va2s .  co m*/
        if (!uri.isAbsolute()) {
            throw new MojoExecutionException("URI " + uri + " must be absolute");
        }
        // Check the path (and fix it up for the obvious issues)
        String path = uri.getPath();
        if (path == null) {
            path = "/";
        }
        if (!path.endsWith("/")) {
            getLog().warn("URI " + uri + " does not end with '/'");
            path += "/";
            try {
                uri = new URI(uri.getScheme(), uri.getAuthority(), path, uri.getQuery(), uri.getFragment());
            } catch (URISyntaxException e) {
                // Basically impossible: it was (syntactically) valid before that.
                throw new MojoExecutionException("Cannot construct fixed URI", e);
            }
        }
        getLog().debug("Mapping " + schemaMapping.directory + " to " + uri);
        builder.addPathRedirect(uri, schemaMapping.directory.toURI());
    }
    return builder;
}

From source file:it.infn.ct.futuregateway.apiserver.inframanager.SessionBuilder.java

/**
 * Read the proxy certificate from a remote location.
 * The location is retrieved from the parameters.
 *
 * @return A string representation of the proxy
 * @throws InfrastructureException If the proxy for the infrastructure
 * cannot be retrieved for problems with the parameters
 *///from  ww  w .  j av  a 2  s  .  c om
protected final String readRemoteProxy() throws InfrastructureException {
    URL proxy;
    if (params.getProperty("proxyurl") == null && params.getProperty("etokenserverurl") == null) {
        throw new InfrastructureException(
                "No proxy location in " + "configuration parameters for " + infrastructure.getId());
    }
    if (params.getProperty("proxyurl") != null) {
        try {
            proxy = new URL(params.getProperty("proxyurl"));
        } catch (MalformedURLException mue) {
            throw new InfrastructureException("URL for the proxy is not " + "valid, infrastructure "
                    + infrastructure.getId() + " is not accessible");
        }
    } else {
        try {
            URI etokenurl = new URI(params.getProperty("etokenserverurl"));
            StringBuilder queryURI = new StringBuilder();
            StringBuilder pathURI = new StringBuilder();
            String oldPath = etokenurl.getPath();
            if (oldPath != null) {
                pathURI.append(oldPath);
                if (!oldPath.endsWith("/")) {
                    pathURI.append('/');
                }
                pathURI.append(params.getProperty("etokenid", ""));
            } else {
                pathURI.append('/').append(params.getProperty("etokenid", ""));
            }
            String oldQuery = etokenurl.getQuery();
            if (oldQuery != null) {
                queryURI.append(oldQuery).append('&');
            }
            queryURI.append("voms=").append(params.getProperty("vo", "")).append(':')
                    .append(params.getProperty("voroles", "")).append('&');
            queryURI.append("proxy-renewal=").append(params.getProperty("proxyrenewal", Defaults.PROXYRENEWAL))
                    .append('&');
            queryURI.append("disable-voms-proxy=")
                    .append(params.getProperty("disablevomsproxy", Defaults.DISABLEVOMSPROXY)).append('&');
            queryURI.append("rfc-proxy=").append(params.getProperty("rfcproxy", Defaults.RFCPROXY)).append('&');
            queryURI.append("cn-label=");
            if (user != null) {
                queryURI.append("eToken:").append(user);
            }
            etokenurl = new URI(etokenurl.getScheme(), etokenurl.getUserInfo(), etokenurl.getHost(),
                    etokenurl.getPort(), pathURI.toString(), queryURI.toString(), etokenurl.getFragment());
            proxy = etokenurl.toURL();
        } catch (MalformedURLException | URISyntaxException use) {
            throw new InfrastructureException("etokenserverurl not " + "properly configured for infrastructure "
                    + getInfrastructure().getId());
        }
    }
    StringBuilder strProxy = new StringBuilder();
    log.debug("Accessing the proxy " + proxy.toString());
    try {
        String lnProxy;
        BufferedReader fileProxy = new BufferedReader(new InputStreamReader(proxy.openStream()));
        while ((lnProxy = fileProxy.readLine()) != null) {
            strProxy.append(lnProxy);
            strProxy.append("\n");
        }
    } catch (IOException ioer) {
        log.error("Impossible to retrieve the remote proxy certificate from" + ": " + proxy.toString());
    }
    log.debug("Proxy:\n\n" + strProxy.toString() + "\n\n");
    return strProxy.toString();
}

From source file:org.wso2.carbon.identity.webfinger.builders.DefaultWebFingerRequestBuilder.java

@Override
public WebFingerRequest buildRequest(HttpServletRequest request) throws WebFingerEndpointException {
    WebFingerRequest webFingerRequest = new WebFingerRequest();
    List<String> parameters = Collections.list(request.getParameterNames());
    if (parameters.size() != 2 || !parameters.contains(WebFingerConstants.REL)
            || !parameters.contains(WebFingerConstants.RESOURCE)) {
        throw new WebFingerEndpointException(WebFingerConstants.ERROR_CODE_INVALID_REQUEST,
                "Bad Web " + "Finger request.");
    }/* w w w. j a  va 2  s .  c o m*/
    webFingerRequest.setServletRequest(request);
    String resource = request.getParameter(WebFingerConstants.RESOURCE);
    webFingerRequest.setRel(request.getParameter(WebFingerConstants.REL));
    webFingerRequest.setResource(resource);

    if (StringUtils.isBlank(resource)) {
        log.warn("Can't normalize null or empty URI: " + resource);
        throw new WebFingerEndpointException(WebFingerConstants.ERROR_CODE_INVALID_RESOURCE,
                "Null or empty URI.");

    } else {
        URI resourceURI = URI.create(resource);
        if (StringUtils.isBlank(resourceURI.getScheme())) {
            throw new WebFingerEndpointException("Scheme of the resource cannot be empty");
        }
        String userInfo;
        if (WebFingerConstants.ACCT_SCHEME.equals(resourceURI.getScheme())) {
            //acct scheme
            userInfo = resourceURI.getSchemeSpecificPart();
            userInfo = userInfo.substring(0, userInfo.lastIndexOf('@'));
        } else {
            //https scheme
            userInfo = resourceURI.getUserInfo();
            webFingerRequest.setScheme(resourceURI.getScheme());
            webFingerRequest.setHost(resourceURI.getHost());
            webFingerRequest.setPort(resourceURI.getPort());
            webFingerRequest.setPath(resourceURI.getPath());
            webFingerRequest.setQuery(resourceURI.getQuery());
        }

        String tenant;
        if (StringUtils.isNotBlank(userInfo)) {
            try {
                userInfo = URLDecoder.decode(userInfo, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new WebFingerEndpointException("Cannot decode the userinfo");
            }
            tenant = MultitenantUtils.getTenantDomain(userInfo);
            webFingerRequest.setUserInfo(resourceURI.getUserInfo());
        } else {
            tenant = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }
        validateTenant(tenant);
        webFingerRequest.setTenant(tenant);
    }

    return webFingerRequest;
}

From source file:org.ardverk.daap.DaapRequest.java

/**
 * Sets and parses the URI. Note: if URIException is thrown then is this
 * Request in an inconsistent state!// w w  w.  j  a v a2 s.  co m
 * 
 * @param uri
 * @throws URIException
 */
private void setURI(URI uri) throws URISyntaxException {

    this.uri = uri;

    if (uri != null) {

        String path = uri.getPath();

        this.queryMap = DaapUtil.parseQuery(uri.getQuery());

        if (path.equals("/server-info")) {
            requestType = SERVER_INFO;
        } else if (path.equals("/content-codes")) {
            requestType = CONTENT_CODES;
        } else if (path.equals("/login")) {
            requestType = LOGIN;
        } else if (path.equals("/logout")) {
            requestType = LOGOUT;
        } else if (path.equals("/update")) {
            requestType = UPDATE;
        } else if (path.equals("/resolve")) {
            requestType = RESOLVE;
        }

        if (queryMap.containsKey("session-id")) {
            sessionId = SessionId.parseSessionId(queryMap.get("session-id"));
        }

        if (!SessionId.INVALID.equals(sessionId)) {

            if (queryMap.containsKey("revision-number")) {
                revisionNumber = Integer.parseInt(queryMap.get("revision-number"));
            }

            if (queryMap.containsKey("delta")) {
                delta = Integer.parseInt(queryMap.get("delta"));
            }

            if (delta > revisionNumber) {
                throw new URISyntaxException(uri.toASCIIString(),
                        "Delta must be less or equal to revision-number: " + delta + "/" + revisionNumber);
            }

            if (queryMap.containsKey("meta")) {
                metaString = queryMap.get("meta");
            }

            isUpdateType = (delta != DaapUtil.NULL) && (delta < revisionNumber);

            // "/databases/id/items" 3 tokens
            // "/databases/id/containers" 3 tokens
            // "/databases/id/items/id.format" 4 tokens
            // "/databases/id/containers/id/items" 5 tokens
            if (path.equals("/databases")) {
                requestType = DATABASES;

            } else if (path.startsWith("/databases")) {

                StringTokenizer tok = new StringTokenizer(path, "/");
                int count = tok.countTokens();

                if (count >= 3) {
                    String token = tok.nextToken();

                    if (token.equals("databases") == false) {
                        throw new URISyntaxException(uri.toASCIIString(),
                                "Unknown token in path: " + path + " [" + token + "]@1");
                    }

                    databaseId = DaapUtil.parseUInt(tok.nextToken());
                    token = tok.nextToken();

                    if (token.equals("items")) {
                        requestType = DATABASE_SONGS;
                    } else if (token.equals("containers")) {
                        requestType = DATABASE_PLAYLISTS;
                    } else {
                        throw new URISyntaxException(uri.toASCIIString(),
                                "Unknown token in path: " + path + " [" + token + "]@2");
                    }

                    if (count == 3) {
                        // do nothing...

                    } else if (count == 4) {

                        token = tok.nextToken();

                        StringTokenizer fileTokenizer = new StringTokenizer(token, ".");

                        if (fileTokenizer.countTokens() == 2) {
                            itemId = DaapUtil.parseUInt(fileTokenizer.nextToken());
                            requestType = SONG;

                        } else {
                            throw new URISyntaxException(uri.toASCIIString(),
                                    "Unknown token in path: " + path + " [" + token + "]@3");
                        }

                    } else if (count == 5) {
                        containerId = DaapUtil.parseUInt(tok.nextToken());
                        token = tok.nextToken();

                        if (token.equals("items")) {
                            requestType = PLAYLIST_SONGS;

                        } else {
                            throw new URISyntaxException(uri.toASCIIString(),
                                    "Unknown token in path: " + path + " [" + token + "@4");
                        }

                    } else {
                        throw new URISyntaxException(uri.toASCIIString(),
                                "Unknown token in path: " + path + " [" + token + "]@5");
                    }
                } else {
                    throw new URISyntaxException(uri.toASCIIString(), "Unknown token in path: " + path);
                }
            }
        }

    } else {

        queryMap = null;
        metaString = null;
        isUpdateType = false;

        requestType = DaapUtil.NULL;
        databaseId = DaapUtil.NULL;
        containerId = DaapUtil.NULL;
        itemId = DaapUtil.NULL;

        sessionId = SessionId.INVALID;
        revisionNumber = DaapUtil.NULL;
        delta = DaapUtil.NULL;
    }
}

From source file:org.soyatec.windowsazure.blob.internal.Blob.java

protected BlobProperties downloadData(String blobName, BlobStream stream, String eTagIfNoneMatch,
        String eTagIfMatch, long offset, long length, NameValueCollection nvc,
        OutParameter<Boolean> localModified) throws StorageException {
    String containerName = getContainerName();
    ResourceUriComponents uriComponents = new ResourceUriComponents(container.getAccountName(), containerName,
            blobName);/*www . j a v  a  2 s .c o m*/

    URI blobUri = HttpUtilities.createRequestUri(container.getBaseUri(), container.isUsePathStyleUris(),
            container.getAccountName(), containerName, blobName, container.getTimeout(), nvc, uriComponents,
            container.getCredentials());

    if (SSLProperties.isSSL()) {
        try {
            URI newBlobUri = new URI("https", null, blobUri.getHost(), 443, blobUri.getPath(),
                    blobUri.getQuery(), blobUri.getFragment());
            blobUri = newBlobUri;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    String httpMethod = (stream == null ? HttpMethod.Head : HttpMethod.Get);
    HttpRequest request = createHttpRequestForGetBlob(blobUri, httpMethod, eTagIfNoneMatch, eTagIfMatch);

    if (offset != 0 || length != 0) {
        // Use the blob storage custom header for range since the standard
        // HttpWebRequest.
        // AddRange accepts only 32 bit integers and so does not work for
        // large blobs.
        String rangeHeaderValue = MessageFormat.format(HeaderValues.RangeHeaderFormat, offset,
                offset + length - 1);
        request.addHeader(HeaderNames.StorageRange, rangeHeaderValue);
    }
    request.addHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2009_09_19);
    container.getCredentials().signRequest(request, uriComponents);
    BlobProperties blobProperties;

    try {
        HttpWebResponse response = null;
        if (SSLProperties.isSSL()) {
            SSLSocketFactory factory = SslUtil.createSSLSocketFactory(SSLProperties.getKeyStore(),
                    SSLProperties.getKeyStorePasswd(), SSLProperties.getTrustStore(),
                    SSLProperties.getTrustStorePasswd(), SSLProperties.getKeyAlias());
            response = HttpUtilities.getSSLReponse((HttpUriRequest) request, factory);
        } else {
            response = HttpUtilities.getResponse(request);
        }
        if (response.getStatusCode() == HttpStatus.SC_OK
                || response.getStatusCode() == HttpStatus.SC_PARTIAL_CONTENT) {

            blobProperties = blobPropertiesFromResponse(blobName, blobUri, response);
            if (stream != null) {
                InputStream responseStream = response.getStream();
                long byteCopied = Utilities.copyStream(responseStream, stream);
                response.close();
                if (blobProperties.getContentLength() > 0 && byteCopied < blobProperties.getContentLength()) {
                    throw new StorageServerException(StorageErrorCode.ServiceTimeout,
                            "Unable to read complete data from server", HttpStatus.SC_REQUEST_TIMEOUT, null);
                }
            } else {
                response.close();
            }
        } else if (response.getStatusCode() == HttpStatus.SC_PRECONDITION_FAILED
                || response.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {

            if (eTagIfMatch != null)
                localModified.setValue(true);
            else if (eTagIfNoneMatch != null)
                localModified.setValue(false);
            HttpUtilities.processUnexpectedStatusCode(response);
            return null;
        } else if (response.getStatusCode() == HttpStatus.SC_NOT_FOUND && stream == null) {
            return null; // check blob exist
        } else {
            HttpUtilities.processUnexpectedStatusCode(response);
            return null;
        }
        return blobProperties;
    } catch (Exception we) {
        throw HttpUtilities.translateWebException(we);
    }
}

From source file:org.opendatakit.api.filter.ProxyUrlSetFilter.java

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    String forwardedPort = requestContext.getHeaderString("x-forwarded-port");
    String forwardedProto = requestContext.getHeaderString("x-forwarded-proto");
    String host = requestContext.getHeaderString("host");

    UriInfo uriInfo = requestContext.getUriInfo();
    URI requestUri = uriInfo.getRequestUri();
    URI baseUri = uriInfo.getBaseUri();
    int forwardedPortInt = uriInfo.getRequestUri().getPort();

    if (StringUtils.isNotEmpty(forwardedPort) || StringUtils.isNotEmpty(forwardedProto)) {
        if (StringUtils.isNotEmpty(forwardedPort)) {
            try {
                forwardedPortInt = Integer.parseInt(forwardedPort);
            } catch (NumberFormatException e) {
                logger.error("Unable to parse x-forwarded-port number " + forwardedPort
                        + " Generated URLs in JSON responses may be wrong.");
                // Life goes on. Non-fatal.
            }/*from   w ww  .jav a  2 s .  c o  m*/
        }
        if (StringUtils.isEmpty(forwardedProto)) {
            forwardedProto = uriInfo.getRequestUri().getScheme();
        }
        try {
            URI newRequestUri = new URI(forwardedProto, requestUri.getUserInfo(), host, forwardedPortInt,
                    requestUri.getPath(), requestUri.getQuery(), requestUri.getFragment());

            URI newBaseUri = new URI(forwardedProto, baseUri.getUserInfo(), host, forwardedPortInt,
                    baseUri.getPath(), baseUri.getQuery(), baseUri.getFragment());

            requestContext.setRequestUri(newBaseUri, newRequestUri);
        } catch (URISyntaxException e) {
            logger.error("Unable to update requestUri. Generated URLs in JSON responses may be wrong.");
            // Life goes on. Non-fatal.
        }

    }
}

From source file:com.cisco.oss.foundation.http.AbstractHttpClient.java

protected S updateRequestUri(S request, InternalServerProxy serverProxy) {

    URI origUri = request.getUri();
    String host = serverProxy.getHost();
    String scheme = origUri.getScheme() == null ? (request.isHttpsEnabled() ? "https" : "http")
            : origUri.getScheme();//ww  w . j  av a2 s.c o  m

    int port = serverProxy.getPort();

    String urlPath = "";
    if (origUri.getRawPath() != null && origUri.getRawPath().startsWith("/")) {
        urlPath = origUri.getRawPath();
    } else {
        urlPath = "/" + origUri.getRawPath();
    }

    URI newURI = null;
    try {
        if (autoEncodeUri) {
            String query = origUri.getQuery();
            newURI = new URI(scheme, origUri.getUserInfo(), host, port, urlPath, query, origUri.getFragment());
        } else {
            String query = origUri.getRawQuery();
            if (query != null) {
                newURI = new URI(scheme + "://" + host + ":" + port + urlPath + "?" + query);
            } else {
                newURI = new URI(scheme + "://" + host + ":" + port + urlPath);
            }

        }
    } catch (URISyntaxException e) {
        throw new ClientException(e.toString());
    }

    S req = (S) request.replaceUri(newURI);
    //        try {
    //            req = (S) this.clone();
    //        } catch (CloneNotSupportedException e) {
    //            throw new IllegalArgumentException(e);
    //        }
    //        req.uri = newURI;
    return req;
}