Example usage for java.net URL getQuery

List of usage examples for java.net URL getQuery

Introduction

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

Prototype

public String getQuery() 

Source Link

Document

Gets the query part of this URL .

Usage

From source file:UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified protocol.
 * @param u the URL on which to base the returned URL
 * @param newProtocol the new protocol to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified protocol
 * @throws MalformedURLException if there is a problem creating the new URL
 *///from   ww w. j ava 2  s.c o  m
public static URL getUrlWithNewProtocol(final URL u, final String newProtocol) throws MalformedURLException {
    return createNewUrl(newProtocol, u.getHost(), u.getPort(), u.getPath(), u.getRef(), u.getQuery());
}

From source file:org.wso2.carbon.identity.provider.openid.OpenIDUtil.java

/**
 * Generate OpenID for a given user.// w ww .  j a v a  2s  . co  m
 *
 * @param user User
 * @return Generated OpenID
 * @throws IdentityProviderException
 */
public static String generateOpenID(String user) throws IdentityProviderException {

    ServerConfiguration serverConfig = null;
    String openIDUserUrl = null;
    String openID = null;
    URI uri = null;
    URL url = null;
    String encodedUser = null;

    serverConfig = ServerConfiguration.getInstance();
    openIDUserUrl = getOpenIDServerURL();

    encodedUser = normalizeUrlEncoding(user);

    openID = String.format(openIDUserUrl, encodedUser);

    try {
        uri = new URI(openID);
    } catch (URISyntaxException e) {
        log.error("Invalid OpenID URL :" + openID, e);
        throw new IdentityProviderException("Invalid OpenID URL :" + openID, e);
    }

    try {
        url = uri.normalize().toURL();
        if (url.getQuery() != null || url.getRef() != null) {
            log.error("Invalid user name for OpenID :" + openID);
            throw new IdentityProviderException("Invalid user name for OpenID :" + openID);
        }
    } catch (MalformedURLException e) {
        log.error("Malformed OpenID URL :" + openID, e);
        throw new IdentityProviderException("Malformed OpenID URL :" + openID, e);
    }

    openID = url.toString();

    if (log.isDebugEnabled()) {
        log.debug("OpenID generated successfully : " + openID);
    }

    return openID;
}

From source file:org.wso2.carbon.identity.provider.openid.util.OpenIDUtil.java

/**
 * Generate OpenID for a given user./*from w ww. j a v a2  s .  co m*/
 *
 * @param user User
 * @return Generated OpenID
 * @throws IdentityProviderException
 */
public static String generateOpenID(String user, String openIDUserUrl) throws IdentityException {
    String openID = null;
    URI uri = null;
    URL url = null;

    String normalizedUser = normalizeUrlEncoding(user);
    openID = String.format(openIDUserUrl, normalizedUser);

    try {
        uri = new URI(openID);
    } catch (URISyntaxException e) {
        log.error("Invalid OpenID URL :" + openID, e);
        throw new IdentityException("Invalid OpenID URL");
    }

    try {
        url = uri.normalize().toURL();
        if (url.getQuery() != null || url.getRef() != null) {
            log.error("Invalid user name for OpenID :" + openID);
            throw new IdentityException("Invalid user name for OpenID");
        }
    } catch (MalformedURLException e) {
        log.error("Malformed OpenID URL :" + openID, e);
        throw new IdentityException("Malformed OpenID URL");
    }

    openID = url.toString();

    if (log.isDebugEnabled()) {
        log.debug("OpenID generated successfully : " + openID);
    }

    return openID;
}

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

/**
 * Calculates the absolute URI for the "relativeUri" with the given absolute "baseUri" as start. <p> 
 * /*  w w w . jav  a 2s . c  o m*/
 * If "relativeUri" is already absolute, it is returned unchanged.
 * This method also returns "relativeUri" unchanged if it is not well-formed.<p>
 *    
 * @param relativeUri the relative URI to calculate an absolute URI for
 * @param baseUri the base URI, this must be an absolute URI
 * 
 * @return an absolute URI calculated from "relativeUri" and "baseUri"
 */
public static String getAbsoluteUri(String relativeUri, String baseUri) {

    if (isAbsoluteUri(relativeUri)) {
        // URI is null or already absolute
        return relativeUri;
    }
    try {
        URL url = new URL(new URL(m_baseUrl, baseUri), relativeUri);
        StringBuffer result = new StringBuffer(100);
        result.append(url.getPath());
        if (url.getQuery() != null) {
            result.append('?');
            result.append(url.getQuery());
        }
        if (url.getRef() != null) {
            result.append('#');
            result.append(url.getRef());
        }
        return result.toString();
    } catch (MalformedURLException e) {
        return relativeUri;
    }
}

From source file:com.eucalyptus.imaging.manifest.DownloadManifestFactory.java

/**
 * Generates download manifest based on bundle manifest and puts in into
 * system owned bucket/*from w  w  w.  j a  va 2 s.  c  om*/
 * 
 * @param baseManifest
 *          the base manifest
 * @param keyToUse
 *          public key that used for encryption
 * @param manifestName
 *          name for generated manifest file
 * @param expirationHours
 *          expiration policy in hours for pre-signed URLs
 * @param urlForNc
 *          indicates if urs are constructed for NC use
 * @return pre-signed URL that can be used to download generated manifest
 * @throws DownloadManifestException
 */
public static String generateDownloadManifest(final ImageManifestFile baseManifest, final PublicKey keyToUse,
        final String manifestName, int expirationHours, boolean urlForNc) throws DownloadManifestException {
    EucaS3Client s3Client = null;
    try {
        try {
            s3Client = s3ClientsPool.borrowObject();
        } catch (Exception ex) {
            throw new DownloadManifestException("Can't borrow s3Client from the pool");
        }
        // prepare to do pre-signed urls
        if (!urlForNc)
            s3Client.refreshEndpoint(true);
        else
            s3Client.refreshEndpoint();

        Date expiration = new Date();
        long msec = expiration.getTime() + 1000 * 60 * 60 * expirationHours;
        expiration.setTime(msec);

        // check if download-manifest already exists
        if (objectExist(s3Client, DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName)) {
            LOG.debug("Manifest '" + (DOWNLOAD_MANIFEST_PREFIX + manifestName)
                    + "' is already created and has not expired. Skipping creation");
            URL s = s3Client.generatePresignedUrl(DOWNLOAD_MANIFEST_BUCKET_NAME,
                    DOWNLOAD_MANIFEST_PREFIX + manifestName, expiration, HttpMethod.GET);
            return String.format("%s://imaging@%s%s?%s", s.getProtocol(), s.getAuthority(), s.getPath(),
                    s.getQuery());
        } else {
            LOG.debug("Manifest '" + (DOWNLOAD_MANIFEST_PREFIX + manifestName) + "' does not exist");
        }

        UrlValidator urlValidator = new UrlValidator();

        final String manifest = baseManifest.getManifest();
        if (manifest == null) {
            throw new DownloadManifestException("Can't generate download manifest from null base manifest");
        }
        final Document inputSource;
        final XPath xpath;
        Function<String, String> xpathHelper;
        DocumentBuilder builder = XMLParser.getDocBuilder();
        inputSource = builder.parse(new ByteArrayInputStream(manifest.getBytes()));
        if (!"manifest".equals(inputSource.getDocumentElement().getNodeName())) {
            LOG.error("Expected image manifest. Got " + nodeToString(inputSource, false));
            throw new InvalidBaseManifestException("Base manifest does not have manifest element");
        }

        StringBuilder signatureSrc = new StringBuilder();
        Document manifestDoc = builder.newDocument();
        Element root = (Element) manifestDoc.createElement("manifest");
        manifestDoc.appendChild(root);
        Element el = manifestDoc.createElement("version");
        el.appendChild(manifestDoc.createTextNode("2014-01-14"));
        signatureSrc.append(nodeToString(el, false));
        root.appendChild(el);
        el = manifestDoc.createElement("file-format");
        el.appendChild(manifestDoc.createTextNode(baseManifest.getManifestType().getFileType().toString()));
        root.appendChild(el);
        signatureSrc.append(nodeToString(el, false));

        xpath = XPathFactory.newInstance().newXPath();
        xpathHelper = new Function<String, String>() {
            @Override
            public String apply(String input) {
                try {
                    return (String) xpath.evaluate(input, inputSource, XPathConstants.STRING);
                } catch (XPathExpressionException ex) {
                    return null;
                }
            }
        };

        // extract keys
        // TODO: move this?
        if (baseManifest.getManifestType().getFileType() == FileType.BUNDLE) {
            String encryptedKey = xpathHelper.apply("/manifest/image/ec2_encrypted_key");
            String encryptedIV = xpathHelper.apply("/manifest/image/ec2_encrypted_iv");
            String size = xpathHelper.apply("/manifest/image/size");
            EncryptedKey encryptKey = reEncryptKey(new EncryptedKey(encryptedKey, encryptedIV), keyToUse);
            el = manifestDoc.createElement("bundle");
            Element key = manifestDoc.createElement("encrypted-key");
            key.appendChild(manifestDoc.createTextNode(encryptKey.getKey()));
            Element iv = manifestDoc.createElement("encrypted-iv");
            iv.appendChild(manifestDoc.createTextNode(encryptKey.getIV()));
            el.appendChild(key);
            el.appendChild(iv);
            Element sizeEl = manifestDoc.createElement("unbundled-size");
            sizeEl.appendChild(manifestDoc.createTextNode(size));
            el.appendChild(sizeEl);
            root.appendChild(el);
            signatureSrc.append(nodeToString(el, false));
        }

        el = manifestDoc.createElement("image");
        String bundleSize = xpathHelper.apply(baseManifest.getManifestType().getSizePath());
        if (bundleSize == null) {
            throw new InvalidBaseManifestException("Base manifest does not have size element");
        }
        Element size = manifestDoc.createElement("size");
        size.appendChild(manifestDoc.createTextNode(bundleSize));
        el.appendChild(size);

        Element partsEl = manifestDoc.createElement("parts");
        el.appendChild(partsEl);
        // parts
        NodeList parts = (NodeList) xpath.evaluate(baseManifest.getManifestType().getPartsPath(), inputSource,
                XPathConstants.NODESET);
        if (parts == null) {
            throw new InvalidBaseManifestException("Base manifest does not have parts");
        }

        for (int i = 0; i < parts.getLength(); i++) {
            Node part = parts.item(i);
            String partIndex = part.getAttributes().getNamedItem("index").getNodeValue();
            String partKey = ((Node) xpath.evaluate(baseManifest.getManifestType().getPartUrlElement(), part,
                    XPathConstants.NODE)).getTextContent();
            String partDownloadUrl = partKey;
            if (baseManifest.getManifestType().signPartUrl()) {
                GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(
                        baseManifest.getBaseBucket(), partKey, HttpMethod.GET);
                generatePresignedUrlRequest.setExpiration(expiration);
                URL s = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
                partDownloadUrl = s.toString();
            } else {
                // validate url per EUCA-9144
                if (!urlValidator.isEucalyptusUrl(partDownloadUrl))
                    throw new DownloadManifestException(
                            "Some parts in the manifest are not stored in the OS. Its location is outside Eucalyptus:"
                                    + partDownloadUrl);
            }
            Node digestNode = null;
            if (baseManifest.getManifestType().getDigestElement() != null)
                digestNode = ((Node) xpath.evaluate(baseManifest.getManifestType().getDigestElement(), part,
                        XPathConstants.NODE));
            Element aPart = manifestDoc.createElement("part");
            Element getUrl = manifestDoc.createElement("get-url");
            getUrl.appendChild(manifestDoc.createTextNode(partDownloadUrl));
            aPart.setAttribute("index", partIndex);
            aPart.appendChild(getUrl);
            if (digestNode != null) {
                NamedNodeMap nm = digestNode.getAttributes();
                if (nm == null)
                    throw new DownloadManifestException(
                            "Some parts in manifest don't have digest's verification algorithm");
                Element digest = manifestDoc.createElement("digest");
                digest.setAttribute("algorithm", nm.getNamedItem("algorithm").getTextContent());
                digest.appendChild(manifestDoc.createTextNode(digestNode.getTextContent()));
                aPart.appendChild(digest);
            }
            partsEl.appendChild(aPart);
        }
        root.appendChild(el);
        signatureSrc.append(nodeToString(el, false));
        String signatureData = signatureSrc.toString();
        Element signature = manifestDoc.createElement("signature");
        signature.setAttribute("algorithm", "RSA-SHA256");
        signature.appendChild(manifestDoc
                .createTextNode(Signatures.SHA256withRSA.trySign(Eucalyptus.class, signatureData.getBytes())));
        root.appendChild(signature);
        String downloadManifest = nodeToString(manifestDoc, true);
        // TODO: move this ?
        createManifestsBucketIfNeeded(s3Client);
        putManifestData(s3Client, DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName,
                downloadManifest, expiration);
        // generate pre-sign url for download manifest
        URL s = s3Client.generatePresignedUrl(DOWNLOAD_MANIFEST_BUCKET_NAME,
                DOWNLOAD_MANIFEST_PREFIX + manifestName, expiration, HttpMethod.GET);
        return String.format("%s://imaging@%s%s?%s", s.getProtocol(), s.getAuthority(), s.getPath(),
                s.getQuery());
    } catch (Exception ex) {
        LOG.error("Got an error", ex);
        throw new DownloadManifestException("Can't generate download manifest");
    } finally {
        if (s3Client != null)
            try {
                s3ClientsPool.returnObject(s3Client);
            } catch (Exception e) {
                // sad, but let's not break instances run
                LOG.warn("Could not return s3Client to the pool");
            }
    }
}

From source file:com.bytelightning.opensource.pokerface.ScriptHelperImpl.java

/**
 * Normalization code courtesy of 'Mike Houston' http://stackoverflow.com/questions/2993649/how-to-normalize-a-url-in-java
 *///from w  w w .  ja va 2 s.  c  o  m
public static String NormalizeURL(final String taintedURL) throws MalformedURLException {
    final URL url;
    try {
        url = new URI(taintedURL).normalize().toURL();
    } catch (URISyntaxException e) {
        throw new MalformedURLException(e.getMessage());
    }

    final String path = url.getPath().replace("/$", "");
    final SortedMap<String, String> params = CreateParameterMap(url.getQuery());
    final int port = url.getPort();
    final String queryString;

    if (params != null) {
        // Some params are only relevant for user tracking, so remove the most commons ones.
        for (Iterator<String> i = params.keySet().iterator(); i.hasNext();) {
            final String key = i.next();
            if (key.startsWith("utm_") || key.contains("session"))
                i.remove();
        }
        queryString = "?" + Canonicalize(params);
    } else
        queryString = "";

    return url.getProtocol() + "://" + url.getHost() + (port != -1 && port != 80 ? ":" + port : "") + path
            + queryString;
}

From source file:com.adito.core.RequestParameterMap.java

private static URL parseProxiedURL(String location, MultiMap map) {
    try {// ww w.j  a v  a2  s  .  co m
        URL proxiedURL = new URL(location);
        URL proxiedURLBase = proxiedURL;

        // Extract parameters from the proxied URL
        String query = proxiedURL.getQuery();
        if (query != null) {
            proxiedURLBase = new URL(proxiedURL.getProtocol(), proxiedURL.getHost(),
                    proxiedURL.getPort() < 1 ? -1 : proxiedURL.getPort(), proxiedURL.getPath());
            parseQuery(map, query);
        }
        return proxiedURLBase;
    } catch (MalformedURLException murle) {
        log.error("Invalid proxied URL '" + location + "'");
    }
    return null;
}

From source file:com.adguard.commons.web.UrlUtils.java

/**
 * Adds parameter to a query string//from  w ww. ja  v  a  2s.  c  o  m
 *
 * @param url            url
 * @param parameterName  parameter name
 * @param parameterValue parameter value
 */
@SuppressWarnings("UnusedDeclaration")
public static String addParameter(String url, String parameterName, String parameterValue) {
    try {
        if (url == null) {
            return null;
        }

        StringBuilder targetUrl = new StringBuilder();
        targetUrl.append(url);

        URL testURL = new URL(url);
        if (testURL.getQuery() != null) {
            targetUrl.append("&");
        } else if ("".equals(testURL.getPath())) {
            targetUrl.append("/?");
        } else {
            targetUrl.append("?");
        }

        targetUrl.append(parameterName);
        targetUrl.append("=");
        targetUrl.append(parameterValue);

        return targetUrl.toString();
    } catch (MalformedURLException ex) {
        return url;
    }
}

From source file:com.adguard.commons.web.UrlUtils.java

/**
 * Extracts path and query from the url/*from  w  w w .  j  ava 2 s.co  m*/
 *
 * @param url Url
 * @return path and query
 */
public static String getPathAndQuery(URL url) {

    String path = url.getPath();
    String query = url.getQuery();

    if (StringUtils.isNotEmpty(query)) {
        return path + "?" + query;
    }

    return path;
}

From source file:com.hp.mercury.ci.jenkins.plugins.OOBuildStep.java

public static URI URI(String urlString) {

    try {//  w  w w  . j a  v a 2 s  . co  m
        final URL url = new URL(urlString);

        return new URI(url.getProtocol(), null, url.getHost(), url.getPort(), url.getPath(), url.getQuery(),
                null);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}