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.fao.geonet.csw.common.requests.CatalogRequest.java

/**
 * Set request URL host, port, address and path.
 * If URL contains query string parameters, those parameters are
 * preserved (and {@link CatalogRequest#excludedParameters} are
 * excluded). A complete GetCapabilities URL may be used for initialization.
 *//*w  w  w . j av  a  2  s  . c o m*/
public void setUrl(URL url) {
    this.host = url.getHost();
    this.port = url.getPort();
    this.protocol = url.getProtocol();
    this.address = url.toString();
    this.path = url.getPath();

    alSetupGetParams = new ArrayList<NameValuePair>();
    String query = url.getQuery();

    if (StringUtils.isNotEmpty(query)) {
        String[] params = query.split("&");
        for (String param : params) {
            String[] kvp = param.split("=");
            if (!excludedParameters.contains(kvp[0].toLowerCase())) {
                this.alSetupGetParams.add(new NameValuePair(kvp[0], kvp[1]));
            }
        }
    }

    if (this.port == -1) {
        this.port = url.getDefaultPort();
    }
}

From source file:org.jasig.cas.client.authentication.AuthenticationFilterTests.java

@Test
public void testIgnorePatternsWithExactMatching() throws Exception {
    final AuthenticationFilter f = new AuthenticationFilter();
    final MockServletContext context = new MockServletContext();
    context.addInitParameter("casServerLoginUrl", CAS_LOGIN_URL);

    final URL url = new URL(CAS_SERVICE_URL + "?param=valueToIgnore");

    context.addInitParameter("ignorePattern", url.toExternalForm());
    context.addInitParameter("ignoreUrlPatternType", "EXACT");
    context.addInitParameter("service", CAS_SERVICE_URL);
    f.init(new MockFilterConfig(context));

    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setScheme(url.getProtocol());
    request.setServerName(url.getHost());
    request.setServerPort(url.getPort());
    request.setQueryString(url.getQuery());
    request.setRequestURI(url.getPath());

    final MockHttpSession session = new MockHttpSession();
    request.setSession(session);//from  w  w  w  .  ja  v  a2 s.c  o  m

    final MockHttpServletResponse response = new MockHttpServletResponse();

    final FilterChain filterChain = new FilterChain() {
        public void doFilter(ServletRequest request, ServletResponse response)
                throws IOException, ServletException {
        }
    };

    f.doFilter(request, response, filterChain);
    assertNull(response.getRedirectedUrl());
}

From source file:com.piusvelte.webcaster.MainActivity.java

@Override
public void openMedium(int parent, int child) {
    Medium m = getMediaAt(parent).get(child);
    final ContentMetadata contentMetadata = new ContentMetadata();
    contentMetadata.setTitle(m.getFile().substring(m.getFile().lastIndexOf(File.separator) + 1));

    if (mediaProtocolMessageStream != null) {
        String urlStr = String.format("http://%s/%s", mediaHost, m.getFile());

        try {/*from w  w  w  . j  av  a2  s. c  om*/
            URL url = new URL(urlStr);
            URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                    url.getQuery(), url.getRef());
            url = uri.toURL();
            MediaProtocolCommand cmd = mediaProtocolMessageStream.loadMedia(url.toString(), contentMetadata,
                    true);
            cmd.setListener(new MediaProtocolCommand.Listener() {
                @Override
                public void onCompleted(MediaProtocolCommand mPCommand) {
                    btnPlay.setText(getString(R.string.pause) + " " + contentMetadata.getTitle());
                    onSetVolume(0.5);
                }

                @Override
                public void onCancelled(MediaProtocolCommand mPCommand) {
                    btnPlay.setText(getString(R.string.play) + " " + contentMetadata.getTitle());
                }
            });
        } catch (IllegalStateException e) {
            Log.e(TAG, "Problem occurred with MediaProtocolCommand during loading", e);
        } catch (IOException e) {
            Log.e(TAG, "Problem opening MediaProtocolCommand during loading", e);
        } catch (URISyntaxException e) {
            Log.e(TAG, "Problem encoding URI: " + urlStr, e);
        }
    } else {
        Toast.makeText(this, "No message stream", Toast.LENGTH_SHORT).show();
    }
}

From source file:org.onecmdb.core.utils.transform.excel.ExcelDataSource.java

public synchronized List<String[]> load() throws IOException {
    if (loaded) {
        return (lines);
    }/*w w w . j a  v  a  2s  .c om*/
    int lineIndex = 0;
    for (URL url : urls) {
        // Remove Options.
        String spec = url.toExternalForm();
        int index = spec.indexOf("?");
        if (index > 0) {
            spec = spec.substring(0, index);
        }
        URL nUrl = new URL(spec);
        if (rootPath != null) {
            nUrl = new URL(nUrl.getProtocol(), nUrl.getHost(), nUrl.getPort(), rootPath + "/" + nUrl.getFile());
        }
        InputStream in = nUrl.openStream();
        Workbook workbook = null;
        try {
            workbook = Workbook.getWorkbook(in);
            String query = url.getQuery();
            Sheet sheet = getSheet(workbook, query, nUrl.toExternalForm());

            log.info("Excel[" + url + "] using sheet " + sheet.getName());
            columns = sheet.getColumns();
            for (int row = 0; row < sheet.getRows(); row++) {
                String rowData[] = new String[sheet.getColumns()];
                for (int col = 0; col < sheet.getColumns(); col++) {
                    Cell cell = sheet.getCell(col, row);
                    String text = cell.getContents();
                    rowData[col] = text;
                }
                if (row < headerLines) {
                    headers.add(rowData);
                } else {
                    lines.add(rowData);
                }
            }
        } catch (BiffException e1) {
            e1.printStackTrace();
            throw new IOException("Problem open Execl file '" + url + "' : " + e1.getMessage());
        } catch (IOException de) {
            IOException e = new IOException("Parse error in <" + url.toExternalForm() + ">, ");
            e.initCause(de);
            throw e;
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }
    loaded = true;
    // Update header name mapping...
    String headers[] = getHeaderData();
    for (int i = 0; i < headers.length; i++) {
        headerMap.put(headers[i], i);
    }
    return (lines);
}

From source file:ddf.catalog.source.opensearch.TestOpenSearchSource.java

private List<NameValuePair> extractQueryParams(FirstArgumentCapture answer)
        throws MalformedURLException, URISyntaxException {
    URL url = new URI(answer.getInputArg()).toURL();
    ParameterParser paramParser = new ParameterParser();
    List<NameValuePair> pairs = paramParser.parse(url.getQuery(), '&');
    return pairs;
}

From source file:de.innovationgate.wgpublisher.webtml.Include.java

private void createAJAXHTML(Status status, TMLPortlet portlet, String initialMode) throws WGException {
    String uniquePortletID = portlet.getportletkey();

    // create prefix buffer
    StringBuffer prefix = new StringBuffer();
    // create suffix buffer
    StringBuffer suffix = new StringBuffer();

    // set id as option, so tags from included module can retrieve it for rendering ajaxCall
    status.setOption(OPTION_AJAX_DIVTAG_ID, uniquePortletID, null);
    // set tmlModule as option, so tags from included module can retrieve the tmlmodulename
    status.setOption(OPTION_PORTLET_TMLMODULE, portlet.getDesign(), null);

    // create ajaxInfo
    AjaxInfo ajaxInfo = new AjaxInfo(uniquePortletID);
    try {/*  w ww  . java  2  s .  c o m*/
        URLBuilder builder = new URLBuilder(getTMLContext().getrequest(), getCore().getCharacterEncoding());
        builder.removeParameter("$action");
        java.net.URL url = new URL(builder.build(true));
        ajaxInfo.setQueryString(url.getQuery());
    } catch (Exception e1) {
        getTMLContext().addwarning("Unable to build request querystring for ajax environment.");
    }
    ajaxInfo.setPortletPath(portlet.getportletpath());
    ajaxInfo.setTmlmodule(portlet.getDesign());
    ajaxInfo.setDesignDB(portlet.gettmldb() != null ? portlet.gettmldb() : getDesigndb());
    ajaxInfo.setMediaKey((String) this.getOption(OPTION_CURRENT_MEDIAKEY));
    ajaxInfo.setContextPath(this.getTMLContext().getpath());

    ajaxInfo.setOptions(new HashMap<String, TMLOption>(getStatus().getTagOptions()));
    ajaxInfo.getOptions().keySet().removeAll(Root.UNRECOVERABLE_OPTIONS);

    ajaxInfo.setProfileSessionId(getTMLContext().getmaincontext().getprofile().getProfileSessionId());
    ajaxInfo.setInitialMode(initialMode);
    if (getTMLContext().getprofile() != null) {
        ajaxInfo.setSaveProfileOnEnd(getTMLContext().getprofile().isSavedOnEnd());
    } else {
        ajaxInfo.setSaveProfileOnEnd(false);
    }
    ajaxInfo.setSuperform(getStatus().getRelevantForm());

    TMLPageImpl page = (TMLPageImpl) WGA.get(getTMLContext()).tmlPage();
    PageConnection pc = page.getPageConnection(false);
    if (pc != null) {
        ajaxInfo.setPageId(pc.getPageId());
    }

    status._ajaxInfo = ajaxInfo;

    // create javascript object with ajaxInfo                    
    // serialize        
    String serAjaxInfo = getCore().getDefaultSerializer().toXML(ajaxInfo);
    // zip
    byte[] zipped = WGUtils.zipString(serAjaxInfo);
    String encryptedAjaxInfo = "";
    if (serAjaxInfo != null) {
        // encrypt
        try {
            encryptedAjaxInfo = this.getTMLContext().getwgacore().getSymmetricEncryptionEngine()
                    .encryptBase64Web(zipped);
        } catch (Exception e) {
            throw new TMLException(
                    "Cannot render ajax enabled include because of unsupported encoding: " + e.getMessage(),
                    true);
        }
    }

    // div tag for ajax paste
    prefix.append("<div id=\"$ajaxDiv_").append(uniquePortletID).append("\">");
    prefix.append("<div id=\"$ajaxContentDiv_").append(uniquePortletID).append("\">");

    prefix.append("<script>");

    // javascript variable ajaxInfo
    prefix.append("var $ajaxInfo_").append(uniquePortletID).append(" = '").append(encryptedAjaxInfo + "';");

    prefix.append("</script>");
    suffix.append("</div></div>");

    // set prefix and suffix
    this.setPrefix(prefix.toString());
    this.setSuffix(suffix.toString());
}

From source file:org.xwiki.contrib.confluence.filter.internal.input.ConfluenceConverterListener.java

private void fixInternalLinks(ResourceReference reference, boolean freestanding, Map<String, String> parameters,
        boolean begin) {
    ResourceReference fixedReference = reference;
    Map<String, String> fixedParameters = parameters;

    if (CollectionUtils.isNotEmpty(this.properties.getBaseURLs())
            && Objects.equals(reference.getType(), ResourceType.URL)) {
        for (URL baseURL : this.properties.getBaseURLs()) {
            String baseURLString = baseURL.toExternalForm();

            if (reference.getReference().startsWith(baseURLString)) {
                // Fix the URL if the format is known

                String urlString = reference.getReference();

                URL url;
                try {
                    url = new URL(urlString);
                } catch (MalformedURLException e) {
                    // Should never happen
                    this.logger.error("Wrong URL resource reference [{}]", reference, e);

                    continue;
                }/*from   ww w.  j a  va 2 s .co  m*/

                String pattern = urlString.substring(baseURLString.length());
                if (pattern.isEmpty() || pattern.charAt(0) != '/') {
                    pattern = "/" + pattern;
                }

                List<String[]> urlParameters = parseURLParameters(url.getQuery());
                String urlAnchor = url.getRef();

                ResourceReference ref = fixReference(pattern, urlParameters, urlAnchor);

                if (ref != null) {
                    fixedReference = ref;
                    break;
                }
            }
        }
    }

    if (begin) {
        super.beginLink(fixedReference, freestanding, fixedParameters);
    } else {
        super.endLink(fixedReference, freestanding, fixedParameters);
    }
}

From source file:com.tremolosecurity.proxy.filter.PostProcess.java

protected void setHeadersCookies(HttpFilterRequest req, UrlHolder holder, HttpRequestBase method,
        String finalURL) throws Exception {
    Iterator<String> names;
    names = req.getHeaderNames();/* w  ww .  jav a2 s.c o m*/
    String cookieName = null;
    URL url = new URL(finalURL);

    while (names.hasNext()) {
        String name = names.next();
        if (name.equalsIgnoreCase("Cookie")) {
            cookieName = name;
            continue;
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Header : " + name);
        }

        Attribute attrib = req.getHeader(name);
        Iterator<String> attrVals = attrib.getValues().iterator();
        while (attrVals.hasNext()) {
            String val = attrVals.next();

            if (name.equalsIgnoreCase("Content-Type")) {
                continue;
            } else if (name.equalsIgnoreCase("If-Range")) {
                continue;
            } else if (name.equalsIgnoreCase("Range")) {
                continue;
            } else if (name.equalsIgnoreCase("If-None-Match")) {
                continue;
            }

            if (name.equalsIgnoreCase("HOST")) {

                if (holder.isOverrideHost()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Final URL : '" + finalURL + "'");
                    }

                    val = url.getHost();
                    if (url.getPort() != -1) {
                        StringBuffer b = new StringBuffer();
                        b.append(val).append(":").append(url.getPort());
                        val = b.toString();
                    }
                }
            } else if (name.equalsIgnoreCase("Referer")) {

                if (holder.isOverrideReferer()) {
                    URL origRef = new URL(val);
                    StringBuffer newRef = new StringBuffer();

                    newRef.append(url.getProtocol()).append("://").append(url.getHost());

                    if (url.getPort() != -1) {
                        newRef.append(':').append(url.getPort());
                    }

                    newRef.append(origRef.getPath());

                    if (origRef.getQuery() != null) {
                        newRef.append('?').append(origRef.getQuery());
                    }

                    if (logger.isDebugEnabled()) {
                        logger.debug("Final Ref : '" + newRef.toString() + "'");
                    }

                    val = newRef.toString();

                }

            }

            if (this.addHeader(name)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Header Added - '" + name + "'='" + val + "'");
                }
                method.addHeader(new BasicHeader(attrib.getName(), val));
            }
        }
    }

    HashMap<String, Attribute> fromResults = (HashMap<String, Attribute>) req
            .getAttribute(AzSys.AUTO_IDM_HTTP_HEADERS);
    if (fromResults != null) {
        names = fromResults.keySet().iterator();

        while (names.hasNext()) {
            String name = names.next();
            method.removeHeaders(name);

            Attribute attrib = fromResults.get(name);
            Iterator<String> attrVals = attrib.getValues().iterator();
            while (attrVals.hasNext()) {
                String val = attrVals.next();
                if (logger.isDebugEnabled()) {
                    logger.debug("Header Added - '" + name + "'='" + val + "'");
                }
                method.addHeader(new BasicHeader(name, val));
            }
        }
    }

    String sessionCookieName = "";

    if (holder.getApp().getCookieConfig() != null) {
        sessionCookieName = holder.getApp().getCookieConfig().getSessionCookieName();
    }

    HashSet<String> toRemove = new HashSet<String>();
    toRemove.add(sessionCookieName);
    toRemove.add("autoIdmSessionCookieName");
    toRemove.add("autoIdmAppName");
    toRemove.add("JSESSIONID");

    names = req.getCookieNames().iterator();
    StringBuffer cookieHeader = new StringBuffer();
    boolean isFirst = true;

    while (names.hasNext()) {
        String name = names.next();

        if (toRemove.contains(name)) {
            continue;
        }

        ArrayList<Cookie> cookies = req.getCookies(name);

        Iterator<Cookie> itc = cookies.iterator();
        while (itc.hasNext()) {
            Cookie cookie = itc.next();
            String cookieFinalName;
            if (cookie.getName().startsWith("JSESSIONID")) {
                String host = cookie.getName().substring(cookie.getName().indexOf('-') + 1);
                host = host.replaceAll("[|]", " ");
                if (!holder.getApp().getName().equalsIgnoreCase(host)) {
                    continue;
                }

                cookieFinalName = "JSESSIONID";
            } else {
                cookieFinalName = cookie.getName();
            }

            String val = cookie.getValue();
            if (logger.isDebugEnabled()) {
                logger.debug("Cookie Added - '" + name + "'='" + val + "'");
            }

            cookieHeader.append(cookieFinalName).append('=').append(val).append("; ");
        }
    }

    if (cookieHeader.length() > 0) {
        if (cookieName == null) {
            cookieName = "Cookie";
        }

        method.addHeader(new BasicHeader(cookieName, cookieHeader.toString()));
    }
}

From source file:org.apache.synapse.transport.passthru.TargetRequest.java

public void start(NHttpClientConnection conn) throws IOException, HttpException {
    if (pipe != null) {
        TargetContext.get(conn).setWriter(pipe);
    }/*  w  ww.jav a 2  s.com*/

    String path = fullUrl || (route.getProxyHost() != null && !route.isTunnelled()) ? url.toString()
            : url.getPath() + (url.getQuery() != null ? "?" + url.getQuery() : "");

    long contentLength = -1;
    String contentLengthHeader = null;
    if (headers.get(HTTP.CONTENT_LEN) != null && headers.get(HTTP.CONTENT_LEN).size() > 0) {
        contentLengthHeader = headers.get(HTTP.CONTENT_LEN).first();
    }

    if (contentLengthHeader != null) {
        contentLength = Integer.parseInt(contentLengthHeader);
        headers.remove(HTTP.CONTENT_LEN);
    }

    MessageContext requestMsgCtx = TargetContext.get(conn).getRequestMsgCtx();

    if (requestMsgCtx.getProperty(PassThroughConstants.PASSTROUGH_MESSAGE_LENGTH) != null) {
        contentLength = (Long) requestMsgCtx.getProperty(PassThroughConstants.PASSTROUGH_MESSAGE_LENGTH);
    }

    //fix for  POST_TO_URI
    if (requestMsgCtx.isPropertyTrue(NhttpConstants.POST_TO_URI)) {
        path = url.toString();
    }

    //fix GET request empty body
    if ((("GET").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD)))
            || (("DELETE").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD)))) {
        hasEntityBody = false;
        MessageFormatter formatter = MessageProcessorSelector.getMessageFormatter(requestMsgCtx);
        OMOutputFormat format = PassThroughTransportUtils.getOMOutputFormat(requestMsgCtx);
        if (formatter != null && format != null) {
            URL _url = formatter.getTargetAddress(requestMsgCtx, format, url);
            if (_url != null && !_url.toString().isEmpty()) {
                if (requestMsgCtx.getProperty(NhttpConstants.POST_TO_URI) != null && Boolean.TRUE.toString()
                        .equals(requestMsgCtx.getProperty(NhttpConstants.POST_TO_URI))) {
                    path = _url.toString();
                } else {
                    path = _url.getPath()
                            + ((_url.getQuery() != null && !_url.getQuery().isEmpty()) ? ("?" + _url.getQuery())
                                    : "");
                }

            }
            headers.remove(HTTP.CONTENT_TYPE);
        }
    }

    Object o = requestMsgCtx.getProperty(MessageContext.TRANSPORT_HEADERS);
    if (o != null && o instanceof TreeMap) {
        Map _headers = (Map) o;
        String trpContentType = (String) _headers.get(HTTP.CONTENT_TYPE);
        if (trpContentType != null && !trpContentType.equals("")) {
            if (!trpContentType.contains(PassThroughConstants.CONTENT_TYPE_MULTIPART_RELATED)) {
                addHeader(HTTP.CONTENT_TYPE, trpContentType);
            }

        }

    }

    if (hasEntityBody) {
        request = new BasicHttpEntityEnclosingRequest(method, path,
                version != null ? version : HttpVersion.HTTP_1_1);

        BasicHttpEntity entity = new BasicHttpEntity();

        boolean forceContentLength = requestMsgCtx.isPropertyTrue(NhttpConstants.FORCE_HTTP_CONTENT_LENGTH);
        boolean forceContentLengthCopy = requestMsgCtx
                .isPropertyTrue(PassThroughConstants.COPY_CONTENT_LENGTH_FROM_INCOMING);

        if (forceContentLength) {
            entity.setChunked(false);
            if (forceContentLengthCopy && contentLength > 0) {
                entity.setContentLength(contentLength);
            }
        } else {
            if (contentLength != -1) {
                entity.setChunked(false);
                entity.setContentLength(contentLength);
            } else {
                entity.setChunked(chunk);
            }
        }

        ((BasicHttpEntityEnclosingRequest) request).setEntity(entity);

    } else {
        request = new BasicHttpRequest(method, path, version != null ? version : HttpVersion.HTTP_1_1);
    }

    Set<Map.Entry<String, TreeSet<String>>> entries = headers.entrySet();
    for (Map.Entry<String, TreeSet<String>> entry : entries) {
        if (entry.getKey() != null) {
            Iterator<String> i = entry.getValue().iterator();
            while (i.hasNext()) {
                request.addHeader(entry.getKey(), i.next());
            }
        }
    }

    //setup wsa action..
    if (request != null) {

        String soapAction = requestMsgCtx.getSoapAction();
        if (soapAction == null) {
            soapAction = requestMsgCtx.getWSAAction();
        }
        if (soapAction == null) {
            requestMsgCtx.getAxisOperation().getInputAction();
        }

        if (requestMsgCtx.isSOAP11() && soapAction != null && soapAction.length() > 0) {
            Header existingHeader = request.getFirstHeader(HTTPConstants.HEADER_SOAP_ACTION);
            if (existingHeader != null) {
                request.removeHeader(existingHeader);
            }
            MessageFormatter messageFormatter = MessageFormatterDecoratorFactory
                    .createMessageFormatterDecorator(requestMsgCtx);
            request.setHeader(HTTPConstants.HEADER_SOAP_ACTION,
                    messageFormatter.formatSOAPAction(requestMsgCtx, null, soapAction));
            //request.setHeader(HTTPConstants.USER_AGENT,"Synapse-PT-HttpComponents-NIO");
        }
    }

    request.setParams(new DefaultedHttpParams(request.getParams(), targetConfiguration.getHttpParams()));

    //Chucking is not performed for request has "http 1.0" and "GET" http method
    if (!((request.getProtocolVersion().equals(HttpVersion.HTTP_1_0))
            || (("GET").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD)))
            || (("DELETE").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD))))) {
        this.processChunking(conn, requestMsgCtx);
    }

    if (!keepAlive) {
        request.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
    }

    // Pre-process HTTP request
    conn.getContext().setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    conn.getContext().setAttribute(ExecutionContext.HTTP_TARGET_HOST, new HttpHost(url.getHost(), port));
    conn.getContext().setAttribute(ExecutionContext.HTTP_REQUEST, request);

    // start the request
    targetConfiguration.getHttpProcessor().process(request, conn.getContext());

    if (targetConfiguration.getProxyAuthenticator() != null && route.getProxyHost() != null
            && !route.isTunnelled()) {
        targetConfiguration.getProxyAuthenticator().authenticatePreemptively(request, conn.getContext());
    }

    conn.submitRequest(request);

    if (hasEntityBody) {
        TargetContext.updateState(conn, ProtocolState.REQUEST_HEAD);
    } else {
        TargetContext.updateState(conn, ProtocolState.REQUEST_DONE);
    }
}