Example usage for org.apache.commons.codec.net URLCodec encode

List of usage examples for org.apache.commons.codec.net URLCodec encode

Introduction

In this page you can find the example usage for org.apache.commons.codec.net URLCodec encode.

Prototype

public Object encode(Object pObject) throws EncoderException 

Source Link

Document

Encodes an object into its URL safe form.

Usage

From source file:eu.seaclouds.platform.planner.core.utils.HttpHelper.java

private String prepareRequestURL(String restPath, List<NameValuePair> params) {
    StringBuilder operationBuilder = new StringBuilder();
    operationBuilder.append(serviceURL);
    operationBuilder.append(restPath);/*from w w w.  j ava  2s. c o m*/
    if (params.size() > 0) {
        operationBuilder.append("?");
        URLCodec coded = new URLCodec();
        try {
            for (NameValuePair p : params)
                operationBuilder.append(p.getName() + "=" + coded.encode(p.getValue()));

        } catch (EncoderException e) {
            log.error(e.getCause().getMessage(), e);
            return "";
        }
    }
    return operationBuilder.toString();
}

From source file:fi.okm.mpass.shibboleth.authn.impl.BaseInitializeWilmaContext.java

/**
 * Constructs an URL where the user is redirected for authentication.
 * @param flowExecutionUrl The current flow execution URL, to be included in the redirect URL.
 * @param authenticationContext The context, also containing {@link WilmaAuthenticationContext}.
 * @return The redirect URL containing the checksum.
 *//*w ww  .ja v a2 s  .  c o m*/
public String getRedirect(final String flowExecutionUrl, final AuthenticationContext authenticationContext) {
    final HttpServletRequest httpRequest = getHttpServletRequest();
    final WilmaAuthenticationContext wilmaContext = authenticationContext
            .getSubcontext(WilmaAuthenticationContext.class);
    final StringBuffer redirectToBuffer = new StringBuffer(
            httpRequest.getScheme() + "://" + httpRequest.getServerName());
    if (httpRequest.getServerPort() != 443) {
        redirectToBuffer.append(":" + httpRequest.getServerPort());
    }
    redirectToBuffer.append(flowExecutionUrl).append(getAsParameter("&", "_eventId_proceed", "1"));
    redirectToBuffer
            .append(getAsParameter("&", WilmaAuthenticationContext.PARAM_NAME_NONCE, wilmaContext.getNonce()));
    final URLCodec urlCodec = new URLCodec();
    try {
        final StringBuffer unsignedUrlBuffer = new StringBuffer(wilmaContext.getRedirectUrl());
        unsignedUrlBuffer.append(getAsParameter("?", WilmaAuthenticationContext.PARAM_NAME_REDIRECT_TO,
                urlCodec.encode(redirectToBuffer.toString())));
        if (authenticationContext.isForceAuthn()) {
            unsignedUrlBuffer
                    .append(getAsParameter("&", WilmaAuthenticationContext.PARAM_NAME_FORCE_AUTH, "true"));
        }
        final String redirectUrl = unsignedUrlBuffer.toString() + getAsParameter("&",
                WilmaAuthenticationContext.PARAM_NAME_CHECKSUM,
                calculateChecksum(Mac.getInstance(algorithm), unsignedUrlBuffer.toString(), signatureKey));
        return redirectUrl;
    } catch (EncoderException | NoSuchAlgorithmException e) {
        log.error("{}: Could not encode the following URL {}", getLogPrefix(), redirectToBuffer, e);
    }
    return null;
}

From source file:com.softlayer.objectstorage.Client.java

/**
 * special wrapper function for a url encoding (handles +'s etc)
 * /*from  w w w  .j a  va2 s. c  o  m*/
 * @return a url safe string
 * @throws EncoderException
 */
protected String saferUrlEncode(String value) throws EncoderException {
    URLCodec ucode = new URLCodec();
    String uName = ucode.encode(value).replaceAll("\\+", "%20");
    return uName;
}

From source file:de.mirkosertic.desktopsearch.SearchServlet.java

private void fillinSearchResult(HttpServletRequest aRequest, HttpServletResponse aResponse)
        throws ServletException, IOException {

    URLCodec theURLCodec = new URLCodec();

    String theQueryString = aRequest.getParameter("querystring");
    String theBasePath = basePath;
    String theBackLink = basePath;
    if (!StringUtils.isEmpty(theQueryString)) {
        try {/*from ww w .jav a 2  s . c  om*/
            theBasePath = theBasePath + "/" + theURLCodec.encode(theQueryString);
            theBackLink = theBackLink + "/" + theURLCodec.encode(theQueryString);
        } catch (EncoderException e) {
            LOGGER.error("Error encoding query string " + theQueryString, e);
        }
    }
    Map<String, String> theDrilldownDimensions = new HashMap<>();

    String thePathInfo = aRequest.getPathInfo();
    if (!StringUtils.isEmpty(thePathInfo)) {
        String theWorkingPathInfo = thePathInfo;

        // First component is the query string
        if (theWorkingPathInfo.startsWith("/")) {
            theWorkingPathInfo = theWorkingPathInfo.substring(1);
        }
        String[] thePaths = StringUtils.split(theWorkingPathInfo, "/");
        for (int i = 0; i < thePaths.length; i++) {
            try {
                String theDecodedValue = thePaths[i].replace('+', ' ');
                String theEncodedValue = theURLCodec.encode(theDecodedValue);
                theBasePath = theBasePath + "/" + theEncodedValue;
                if (i < thePaths.length - 1) {
                    theBackLink = theBackLink + "/" + theEncodedValue;
                }
                if (i == 0) {
                    theQueryString = theDecodedValue;
                } else {
                    FacetSearchUtils.addToMap(theDecodedValue, theDrilldownDimensions);
                }
            } catch (EncoderException e) {
                LOGGER.error("Error while decoding drilldown params for " + aRequest.getPathInfo(), e);
            }
        }
        if (basePath.equals(theBackLink)) {
            theBackLink = null;
        }
    } else {
        theBackLink = null;
    }

    if (!StringUtils.isEmpty(theQueryString)) {
        aRequest.setAttribute("querystring", theQueryString);
        try {
            aRequest.setAttribute("queryResult",
                    backend.performQuery(theQueryString, theBackLink, theBasePath, theDrilldownDimensions));
        } catch (Exception e) {
            LOGGER.error("Error running query " + theQueryString, e);
        }
    } else {
        aRequest.setAttribute("querystring", "");
    }

    aRequest.setAttribute("serverBase", serverBase);

    aRequest.getRequestDispatcher("/index.ftl").forward(aRequest, aResponse);
}

From source file:jp.dip.komusubi.botter.util.BitlyUrlUtil.java

@Override
public String shorten(String url) {
    parameters.put(PARAMETER_NAME_LONGURL, url);
    StringBuilder builder = new StringBuilder(SHORTEN_SERVICE_URL);
    URLCodec codec = new URLCodec();

    String responseLine = null;//from   w ww  . ja  v  a 2s  . c  o m
    boolean done = false;
    for (Entry<String, String> entry : parameters.entrySet()) {
        if (done == false) {
            builder.append("?");
            done = true;
        } else {
            builder.append("&");
        }
        try {
            builder.append(codec.encode(entry.getKey())).append("=").append(codec.encode(entry.getValue()));
        } catch (EncoderException e) {
            throw new BotterException(e);
        }
    }
    responseLine = UrlAccessDelegate.readFirstLine(builder.toString());
    if (responseLine == null)
        logger.warn("bit.ly response is null, URL is :{}", builder.toString());
    return responseLine;
}

From source file:ch.iterate.openstack.swift.Client.java

private static String encode(String object) {
    URLCodec codec = new URLCodec();
    try {//from www  . j a  v  a 2  s  . co  m
        return codec.encode(object).replaceAll("\\+", "%20");
    } catch (EncoderException ee) {
        return object;
    }
}

From source file:com.bloatit.framework.webprocessor.url.UrlParameter.java

@Override
protected void constructUrl(final StringBuilder sb) {
    final String stringValue = getStringValue();
    if (getRole() == Role.GET || getRole() == Role.PRETTY || getRole() == Role.POSTGET) {
        if (!stringValue.isEmpty() && !stringValue.equals(getDefaultValue()) && value != null) {
            final URLCodec urlCodec = new URLCodec();
            try {
                if (value instanceof List) {
                    sb.append(stringValue);
                } else {
                    sb.append(urlCodec.encode(getName())).append('=').append(urlCodec.encode(stringValue));
                }//from www.  j  av a  2s .c o m
            } catch (final EncoderException e) {
                throw new BadProgrammerException(e);
            }
        }
    }
}

From source file:de.mirkosertic.desktopsearch.LuceneIndexHandler.java

private String encode(String aValue) {
    URLCodec theURLCodec = new URLCodec();
    try {/*w ww .java  2  s . c om*/
        return theURLCodec.encode(aValue);
    } catch (EncoderException e) {
        return null;
    }
}

From source file:edu.lternet.pasta.portal.HarvestReport.java

private String getQualityReportLink(String packageId, String localPath) {
    String link = "";
    URLCodec urlCodec = new URLCodec();

    try {/*from w  w  w  . j av  a2s  .  c  o  m*/
        if (packageId != null && packageId.length() > 0) {
            link = "<a class=\"searchsubcat\" href=\"./reportviewer?packageid=" + packageId;

            if (localPath != null) {
                String encodedPath = urlCodec.encode(localPath);
                link += "&localPath=" + encodedPath;
            }

            link += "\" target=\"_blank\">view</a>";
        }
    } catch (EncoderException e) {
        e.printStackTrace();
        logger.error(e.getMessage());
    }

    return link;
}

From source file:com.ge.research.semtk.sparqlX.SparqlEndpointInterface.java

/**
 * Execute query using GET (use should be rare - in cases where POST is not supported) 
 * @return a JSONObject wrapping the results. in the event the results were tabular, they can be obtained in the JsonArray "@Table". if the results were a graph, use "@Graph" for json-ld
 * @throws Exception/*from w  ww . ja  va  2s.  c  om*/
 */
public JSONObject executeQueryGet(String query, SparqlResultTypes resultsType) throws Exception {

    if (resultsType == null) {
        resultsType = getDefaultResultType();
    }

    // encode the query and build a real URL
    URLCodec encoder = new URLCodec();
    String cleanURL = getGetURL() + encoder.encode(query);
    URL url = new URL(null, cleanURL, handler);
    System.out.println("URL: " + url);

    // create an http GET connection and make the request
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // set the type of output desired. this might not work....
    String resultsFormat = this.getContentType(resultsType);
    conn.setRequestProperty("Accept", resultsFormat);

    conn.setRequestMethod("GET");

    // read the results
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String results = "";
    // get everythign from reader
    String line;
    while ((line = rd.readLine()) != null) {
        results += line;
    }

    try {
        this.response = (JSONObject) new JSONParser().parse(results);
    } catch (Exception e) {
        throw new Exception("Cannot parse query result into JSON: " + results);
    }

    JSONObject interimObj = new JSONObject(this.response);
    rd.close(); // close the reader

    if (this.response == null) {
        System.err.println("the response could not be transformed into json");

        return null;
    } else {
        JSONObject procResp = getResultsFromResponse(interimObj, resultsType);

        return procResp;
    }

}