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:org.bungeni.ext.integration.bungeniportal.BungeniServiceAccess.java

private String getTargetTransitionId(String transitionURL) throws MalformedURLException {
    URL url = new URL(transitionURL);
    String sUrlQuery = url.getQuery();
    Map<String, String> urlMap = getQueryMap(sUrlQuery);
    String sTransition = urlMap.get("transition_id");
    String[] arrTrans = sTransition.split("-");
    // the second element in the array has the transition id 
    String targetTransitionId = arrTrans[1];
    return targetTransitionId;
}

From source file:net.ychron.unirestinst.http.HttpClientHelper.java

private HttpRequestBase prepareRequest(HttpRequest request, boolean async) {

    Object defaultHeaders = options.getOption(Option.DEFAULT_HEADERS);
    if (defaultHeaders != null) {
        @SuppressWarnings("unchecked")
        Set<Entry<String, String>> entrySet = ((Map<String, String>) defaultHeaders).entrySet();
        for (Entry<String, String> entry : entrySet) {
            request.header(entry.getKey(), entry.getValue());
        }/*www. j av a  2s  .  c  om*/
    }

    if (!request.getHeaders().containsKey(USER_AGENT_HEADER)) {
        request.header(USER_AGENT_HEADER, USER_AGENT);
    }
    if (!request.getHeaders().containsKey(ACCEPT_ENCODING_HEADER)) {
        request.header(ACCEPT_ENCODING_HEADER, "gzip");
    }

    HttpRequestBase reqObj = null;

    String urlToRequest = null;
    try {
        URL url = new URL(request.getUrl());
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(),
                URLDecoder.decode(url.getPath(), "UTF-8"), "", url.getRef());
        urlToRequest = uri.toURL().toString();
        if (url.getQuery() != null && !url.getQuery().trim().equals("")) {
            if (!urlToRequest.substring(urlToRequest.length() - 1).equals("?")) {
                urlToRequest += "?";
            }
            urlToRequest += url.getQuery();
        } else if (urlToRequest.substring(urlToRequest.length() - 1).equals("?")) {
            urlToRequest = urlToRequest.substring(0, urlToRequest.length() - 1);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    switch (request.getHttpMethod()) {
    case GET:
        reqObj = new HttpGet(urlToRequest);
        break;
    case POST:
        reqObj = new HttpPost(urlToRequest);
        break;
    case PUT:
        reqObj = new HttpPut(urlToRequest);
        break;
    case DELETE:
        reqObj = new HttpDeleteWithBody(urlToRequest);
        break;
    case PATCH:
        reqObj = new HttpPatchWithBody(urlToRequest);
        break;
    case OPTIONS:
        reqObj = new HttpOptions(urlToRequest);
        break;
    case HEAD:
        reqObj = new HttpHead(urlToRequest);
        break;
    }

    Set<Entry<String, List<String>>> entrySet = request.getHeaders().entrySet();
    for (Entry<String, List<String>> entry : entrySet) {
        List<String> values = entry.getValue();
        if (values != null) {
            for (String value : values) {
                reqObj.addHeader(entry.getKey(), value);
            }
        }
    }

    // Set body
    if (!(request.getHttpMethod() == HttpMethod.GET || request.getHttpMethod() == HttpMethod.HEAD)) {
        if (request.getBody() != null) {
            HttpEntity entity = request.getBody().getEntity();
            if (async) {
                if (reqObj.getHeaders(CONTENT_TYPE) == null || reqObj.getHeaders(CONTENT_TYPE).length == 0) {
                    reqObj.setHeader(entity.getContentType());
                }
                try {
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    entity.writeTo(output);
                    NByteArrayEntity en = new NByteArrayEntity(output.toByteArray());
                    ((HttpEntityEnclosingRequestBase) reqObj).setEntity(en);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else {
                ((HttpEntityEnclosingRequestBase) reqObj).setEntity(entity);
            }
        }
    }

    return reqObj;
}

From source file:eionet.util.Util.java

/**
 *
 * @param url/*from  ww  w .j  a va 2s.  com*/
 * @return
 * @throws MalformedURLException
 */
public static String getUrlPathAndQuery(String urlString) throws MalformedURLException {

    java.net.URL url = new java.net.URL(urlString);
    StringBuffer buf = new StringBuffer(url.getPath());
    if (url.getQuery() != null) {
        buf.append("?").append(url.getQuery());
    }

    return buf.toString();
}

From source file:de.betterform.connector.smtp.SMTPSubmissionHandler.java

private void send(String uri, byte[] data, String encoding, String mediatype) throws Exception {
    URL url = new URL(uri);
    String recipient = url.getPath();

    String server = null;/* w  w  w .  j ava2  s .  c  o  m*/
    String port = null;
    String sender = null;
    String subject = null;
    String username = null;
    String password = null;

    StringTokenizer headers = new StringTokenizer(url.getQuery(), "&");

    while (headers.hasMoreTokens()) {
        String token = headers.nextToken();

        if (token.startsWith("server=")) {
            server = URLDecoder.decode(token.substring("server=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("port=")) {
            port = URLDecoder.decode(token.substring("port=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("sender=")) {
            sender = URLDecoder.decode(token.substring("sender=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("subject=")) {
            subject = URLDecoder.decode(token.substring("subject=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("username=")) {
            username = URLDecoder.decode(token.substring("username=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("password=")) {
            password = URLDecoder.decode(token.substring("password=".length()), "UTF-8");

            continue;
        }
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("smtp server '" + server + "'");

        if (username != null) {
            LOGGER.debug("smtp-auth username '" + username + "'");
        }

        LOGGER.debug("mail sender '" + sender + "'");
        LOGGER.debug("subject line '" + subject + "'");
    }

    Properties properties = System.getProperties();
    properties.put("mail.debug", String.valueOf(LOGGER.isDebugEnabled()));
    properties.put("mail.smtp.from", sender);
    properties.put("mail.smtp.host", server);

    if (port != null) {
        properties.put("mail.smtp.port", port);
    }

    if (username != null) {
        properties.put("mail.smtp.auth", String.valueOf(true));
        properties.put("mail.smtp.user", username);
    }

    Session session = Session.getInstance(properties, new SMTPAuthenticator(username, password));

    MimeMessage message = null;
    if (mediatype.startsWith("multipart/")) {
        message = new MimeMessage(session, new ByteArrayInputStream(data));
    } else {
        message = new MimeMessage(session);
        if (mediatype.toLowerCase().indexOf("charset=") == -1) {
            mediatype += "; charset=\"" + encoding + "\"";
        }
        message.setText(new String(data, encoding), encoding);
        message.setHeader("Content-Type", mediatype);
    }

    message.setRecipient(RecipientType.TO, new InternetAddress(recipient));
    message.setSubject(subject);
    message.setSentDate(new Date());

    Transport.send(message);
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.AuthorizationRequestManager.java

/**
 * Processes redirect response from authorization endpoint.
 *
 * @param response Response from the server.
 *///from w w w . ja  va  2s .  c  o m
private void processRedirectResponse(Response response)
        throws RuntimeException, JSONException, MalformedURLException {
    // a valid redirect response must contain the Location header.
    ResponseImpl responseImpl = (ResponseImpl) response;
    List<String> locationHeaders = responseImpl.getHeader(LOCATION_HEADER_NAME);

    String location = (locationHeaders != null && locationHeaders.size() > 0) ? locationHeaders.get(0) : null;

    if (location == null) {
        throw new RuntimeException("Redirect response does not contain 'Location' header.");
    }

    // the redirect location url should contain "wl_result" value in query parameters.
    URL url = new URL(location);
    String query = url.getQuery();

    if (query.contains(WL_RESULT)) {
        String result = Utils.getParameterValueFromQuery(query, WL_RESULT);
        JSONObject jsonResult = new JSONObject(result);

        // process failures if any
        JSONObject jsonFailures = jsonResult.optJSONObject(AUTH_FAILURE_VALUE_NAME);

        if (jsonFailures != null) {
            processFailures(jsonFailures);
            listener.onFailure(response, null, null);
            return;
        }

        // process successes if any
        JSONObject jsonSuccesses = jsonResult.optJSONObject(AUTH_SUCCESS_VALUE_NAME);

        if (jsonSuccesses != null) {
            processSuccesses(jsonSuccesses);
        }
    }

    // the rest is handles by the caller
    listener.onSuccess(response);
}

From source file:org.lockss.repository.LockssRepositoryImpl.java

/**
 * mapUrlToFileLocation() is the method used to resolve urls into file names.
 * This maps a given url to a file location, using the au top directory as
 * the base.  It creates directories which mirror the html string, so
 * 'http://www.journal.org/issue1/index.html' would be cached in the file:
 * <rootLocation>/www.journal.org/http/issue1/index.html
 * @param rootLocation the top directory for ArchivalUnit this URL is in
 * @param urlStr the url to translate/*w w w . jav  a 2 s  . c o  m*/
 * @return the url file location
 * @throws java.net.MalformedURLException
 */
public static String mapUrlToFileLocation(String rootLocation, String urlStr) throws MalformedURLException {
    int totalLength = rootLocation.length() + urlStr.length();
    URL url = new URL(urlStr);
    StringBuilder buffer = new StringBuilder(totalLength);
    buffer.append(rootLocation);
    if (!rootLocation.endsWith(File.separator)) {
        buffer.append(File.separator);
    }
    buffer.append(url.getHost().toLowerCase());
    int port = url.getPort();
    if (port != -1) {
        buffer.append(PORT_SEPARATOR);
        buffer.append(port);
    }
    buffer.append(File.separator);
    buffer.append(url.getProtocol());
    if (RepositoryManager.isEnableLongComponents()) {
        String escapedPath = escapePath(
                StringUtil.replaceString(url.getPath(), UrlUtil.URL_PATH_SEPARATOR, File.separator));
        String query = url.getQuery();
        if (query != null) {
            escapedPath = escapedPath + "?" + escapeQuery(query);
        }
        String encodedPath = RepositoryNodeImpl.encodeUrl(escapedPath);
        // encodeUrl strips leading / from path
        buffer.append(File.separator);
        buffer.append(encodedPath);
    } else {
        buffer.append(escapePath(
                StringUtil.replaceString(url.getPath(), UrlUtil.URL_PATH_SEPARATOR, File.separator)));
        String query = url.getQuery();
        if (query != null) {
            buffer.append("?");
            buffer.append(escapeQuery(query));
        }
    }
    return buffer.toString();
}

From source file:org.jppf.example.webcrawler.CrawlerTask.java

/**
 * Crawl to find all links in the current page.
 * @throws Exception if an error occurs.
 *//*from w w  w. j av  a2  s  . co m*/
private void crawl() throws Exception {
    URL u = new URL(url);
    String server = u.getProtocol() + "://" + u.getHost();
    while (server.endsWith("/"))
        server = server.substring(0, server.length() - 1);
    if (u.getPort() >= 0)
        server += ":" + u.getPort();
    String start = u.getPath() == null ? "" : u.getPath();
    while (start.startsWith("/"))
        start = start.substring(1);
    start = "/" + start;
    if (u.getQuery() != null)
        start += "?" + u.getQuery();

    int depth = 1;

    Crawler crawler = new Crawler();
    ILinkFilter filter = new ServerFilter(server);
    ILinkFilter filter2 = new FileExtensionFilter(
            new String[] { ".png", ".jpg", ".gif", ".pdf", ".mpg", ".avi", ".wmv", ".swf", });
    filter2 = LinkFilterUtil.not(filter2);
    filter = LinkFilterUtil.and(filter, filter2);
    crawler.setLinkFilter(filter);
    crawler.setModel(new MaxDepthModel(depth));
    crawler.addParserListener(new IParserEventListener() {
        @Override
        public void parse(final ParserEvent event) {
            String url = event.getLink().getURI();
            if (!toVisit.contains(url))
                toVisit.add(url);
        }
    });

    crawler.start(server, start);
}

From source file:org.tuckey.web.filters.urlrewrite.RequestProxy.java

private static HttpMethod setupProxyRequest(final HttpServletRequest hsRequest, final URL targetUrl)
        throws IOException {
    final String methodName = hsRequest.getMethod();
    final HttpMethod method;
    if ("POST".equalsIgnoreCase(methodName)) {
        PostMethod postMethod = new PostMethod();
        InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(
                hsRequest.getInputStream());
        postMethod.setRequestEntity(inputStreamRequestEntity);
        method = postMethod;/*  w  ww . ja va  2s.c o  m*/
    } else if ("GET".equalsIgnoreCase(methodName)) {
        method = new GetMethod();
    } else if ("PUT".equalsIgnoreCase(methodName)) {
        PutMethod putMethod = new PutMethod();
        InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(
                hsRequest.getInputStream());
        putMethod.setRequestEntity(inputStreamRequestEntity);
        method = putMethod;
    } else if ("DELETE".equalsIgnoreCase(methodName)) {
        method = new DeleteMethod();
    } else {
        log.warn("Unsupported HTTP method requested: " + hsRequest.getMethod());
        return null;
    }

    method.setFollowRedirects(false);
    method.setPath(targetUrl.getPath());
    method.setQueryString(targetUrl.getQuery());

    Enumeration e = hsRequest.getHeaderNames();
    if (e != null) {
        while (e.hasMoreElements()) {
            String headerName = (String) e.nextElement();
            if ("host".equalsIgnoreCase(headerName)) {
                //the host value is set by the http client
                continue;
            } else if ("content-length".equalsIgnoreCase(headerName)) {
                //the content-length is managed by the http client
                continue;
            } else if ("accept-encoding".equalsIgnoreCase(headerName)) {
                //the accepted encoding should only be those accepted by the http client.
                //The response stream should (afaik) be deflated. If our http client does not support
                //gzip then the response can not be unzipped and is delivered wrong.
                continue;
            } else if (headerName.toLowerCase().startsWith("cookie")) {
                //fixme : don't set any cookies in the proxied request, this needs a cleaner solution
                continue;
            }

            Enumeration values = hsRequest.getHeaders(headerName);
            while (values.hasMoreElements()) {
                String headerValue = (String) values.nextElement();
                log.info("setting proxy request parameter:" + headerName + ", value: " + headerValue);
                method.addRequestHeader(headerName, headerValue);
            }
        }
    }

    if (log.isInfoEnabled())
        log.info("proxy query string " + method.getQueryString());
    return method;
}

From source file:com.gargoylesoftware.htmlunit.WebRequestSettings.java

/**
 * Sets the target URL. The URL may be simplified if needed (for instance eliminating
 * irrelevant path portions like "/./").
 * @param url the target URL// w  w  w.  j  a  va  2s  . c  o  m
 */
public void setUrl(URL url) {
    if (url != null) {
        final String path = url.getPath();
        if (path.length() == 0) {
            url = buildUrlWithNewFile(url, "/" + url.getFile());
        } else if (path.contains("./")) {
            final String query = (url.getQuery() != null) ? "?" + url.getQuery() : "";
            url = buildUrlWithNewFile(url, removeDots(path) + query);
        }
        url_ = url.toExternalForm();
    } else {
        url_ = null;
    }
}

From source file:com.cladonia.xngreditor.URLUtilities.java

/**
 * Decrypts the string and creates a URL.
 * /*ww  w.ja va 2 s .c om*/
 * @param url the url.
 * 
 * @return the decrypted url or null if the url could not be constructed.
 */
public static URL decrypt(String string) {
    try {
        URL url = new URL(string);

        String password = getPassword(url);
        String username = getUsername(url);

        if (password != null) {
            password = StringUtilities.decrypt(password);
        }

        //         System.out.println( "URLUtilities.decrypt( "+string+") ["+password+"]");

        return createURL(url.getProtocol(), username, password, url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
    } catch (MalformedURLException e) {
        // ignore
    }

    return null;
}