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:com.rackspacecloud.client.cloudfiles.FilesClient.java

/**
 * URI//w  w w .jav  a 2 s  . c o m
 * @param str
 *           
 * @return URI
 */
public static String sanitizeForURI(String str) {
    URLCodec codec = new URLCodec();
    try {
        return codec.encode(str).replaceAll("\\+", "%20");
    } catch (EncoderException ee) {
        logger.warn("Error trying to encode string for URI", ee);
        return str;
    }
}

From source file:com.rackspacecloud.client.cloudfiles.FilesClient.java

/**
 * URI///from   w  w  w .  j a  v a  2 s .c  om
 * @param str
 *           
 * @return URI
 */
public static String sanitizeAndPreserveSlashes(String str) {
    URLCodec codec = new URLCodec();
    try {
        return codec.encode(str).replaceAll("\\+", "%20").replaceAll("%2F", "/");
    } catch (EncoderException ee) {
        logger.warn("Error trying to encode string for URI", ee);
        return str;
    }
}

From source file:aaf.vhr.idp.http.VhrRemoteUserAuthServlet.java

/** {@inheritDoc} */
@Override/*from   w ww.  j a  va 2s  . c o  m*/
protected void service(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse)
        throws ServletException, IOException {

    try {
        // key to ExternalAuthentication session
        String key = null;
        boolean isVhrReturn = false;
        boolean isForceAuthn = false;
        DateTime authnStart = null; // when this authentication started at the IdP
        // array to use as return parameter when calling VhrSessionValidator
        DateTime authnInstantArr[] = new DateTime[1];

        if (httpRequest.getParameter(REDIRECT_REQ_PARAM_NAME) != null) {
            // we have come back from the VHR
            isVhrReturn = true;
            key = httpRequest.getParameter(REDIRECT_REQ_PARAM_NAME);
            HttpSession hs = httpRequest.getSession();

            if (hs != null && hs.getAttribute(AUTHN_INIT_INSTANT_ATTR_NAME + key) != null) {
                authnStart = (DateTime) hs.getAttribute(AUTHN_INIT_INSTANT_ATTR_NAME + key);
                // remove the attribute from the session so that we do not attempt to reuse it...
                hs.removeAttribute(AUTHN_INIT_INSTANT_ATTR_NAME);
            }
            ;

            if (hs != null && hs.getAttribute(IS_FORCE_AUTHN_ATTR_NAME + key) != null) {
                isForceAuthn = ((Boolean) hs.getAttribute(IS_FORCE_AUTHN_ATTR_NAME + key)).booleanValue();
                // remove the attribute from the session so that we do not attempt to reuse it...
                hs.removeAttribute(AUTHN_INIT_INSTANT_ATTR_NAME);
            }
            ;

        } else {
            // starting a new SSO request
            key = ExternalAuthentication.startExternalAuthentication(httpRequest);

            // check if forceAuthn is set
            Object forceAuthnAttr = httpRequest.getAttribute(ExternalAuthentication.FORCE_AUTHN_PARAM);
            if (forceAuthnAttr != null && forceAuthnAttr instanceof java.lang.Boolean) {
                log.debug("Loading foceAuthn value");
                isForceAuthn = ((Boolean) forceAuthnAttr).booleanValue();
            }

            // check if we can see when authentication was initiated
            final AuthenticationContext authCtx = ExternalAuthentication
                    .getProfileRequestContext(key, httpRequest)
                    .getSubcontext(AuthenticationContext.class, false);
            if (authCtx != null) {
                log.debug("Authentication initiation is {}", authCtx.getInitiationInstant());
                authnStart = new DateTime(authCtx.getInitiationInstant(), DateTimeZone.UTC);
                log.debug("AuthnStart is {}", authnStart);
            }
            ;

        }
        ;
        log.debug("forceAuthn is {}, authnStart is {}", isForceAuthn, authnStart);

        if (key == null) {
            log.error("No ExternalAuthentication sesssion key found");
            throw new ServletException("No ExternalAuthentication sesssion key found");
        }
        ;
        // we now have a key - either:
        // * we started new authentication
        // * or we have returned from VHR and loaded the key from the HttpSession

        String username = null;

        // We may have a cookie - either as part of return or from previous session
        // Attempt to locate VHR SessionID
        String vhrSessionID = null;
        Cookie[] cookies = httpRequest.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(SSO_COOKIE_NAME)) {
                vhrSessionID = cookie.getValue();
                break;
            }
        }

        if (vhrSessionID != null) {
            log.info("Found vhrSessionID from {}. Establishing validity.", httpRequest.getRemoteHost());
            username = vhrSessionValidator.validateSession(vhrSessionID, (isForceAuthn ? authnStart : null),
                    authnInstantArr);
        }
        ;

        // If we do not have a username yet (no Vhr session cookie or did not validate),
        // we redirect to VHR - but only if we are not returning from the VHR
        // Reason: (i) we do not want to loop and (ii) we do not have the full context otherwise initialized by
        // ExternalAuthentication.startExternalAuthentication()
        if (username == null && !isVhrReturn) {

            URLCodec codec = new URLCodec();
            String relyingParty = (String) httpRequest.getAttribute("relyingParty");
            String serviceName = "";

            log.info("No vhrSessionID found from {}. Directing to VHR authentication process.",
                    httpRequest.getRemoteHost());
            log.debug("Relying party which initiated the SSO request was: {}", relyingParty);

            // try getting a RelyingPartyUIContext
            // we should pass on the request for consent revocation
            final ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(key, httpRequest);
            final RelyingPartyUIContext rpuiCtx = prc.getSubcontext(AuthenticationContext.class, true)
                    .getSubcontext(RelyingPartyUIContext.class, false);
            if (rpuiCtx != null) {
                serviceName = rpuiCtx.getServiceName();
                log.debug("RelyingPartyUIContext received, ServiceName is {}", serviceName);
            }
            ;

            // save session *key*
            HttpSession hs = httpRequest.getSession(true);
            hs.setAttribute(IS_FORCE_AUTHN_ATTR_NAME + key, new Boolean(isForceAuthn));
            hs.setAttribute(AUTHN_INIT_INSTANT_ATTR_NAME + key, authnStart);

            try {
                httpResponse.sendRedirect(String.format(vhrLoginEndpoint,
                        codec.encode(httpRequest.getRequestURL().toString() + "?" + REDIRECT_REQ_PARAM_NAME
                                + "=" + codec.encode(key)),
                        codec.encode(relyingParty), codec.encode(serviceName)));
            } catch (EncoderException e) {
                log.error("Could not encode VHR redirect params");
                throw new IOException(e);
            }
            return; // we issued a redirect - return now
        }
        ;

        if (username == null) {
            log.warn("VirtualHome authentication failed: no username received");
            httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY,
                    "VirtualHome authentication failed: no username received");
            ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
            return;
        }

        // check if consent revocation was requested
        String consentRevocationParam = httpRequest.getParameter(consentRevocationParamName);
        if (consentRevocationParam != null) {
            // we should pass on the request for consent revocation
            final ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(key, httpRequest);
            final ConsentManagementContext consentCtx = prc.getSubcontext(ConsentManagementContext.class, true);
            log.debug("Consent revocation request received, setting revokeConsent in consentCtx");
            consentCtx.setRevokeConsent(consentRevocationParam.equalsIgnoreCase("true"));
        }
        ;

        // Set authnInstant to timestamp returned by VHR
        if (authnInstantArr[0] != null) {
            log.debug("Response from VHR includes authenticationInstant time {}, passing this back to IdP",
                    authnInstantArr[0]);
            httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_INSTANT_KEY, authnInstantArr[0]);
        }
        ;

        httpRequest.setAttribute(ExternalAuthentication.PRINCIPAL_NAME_KEY, username);

        ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);

    } catch (final ExternalAuthenticationException e) {
        throw new ServletException("Error processing external authentication request", e);
    }
}

From source file:edu.jhuapl.openessence.controller.ReportController.java

private String appendUrlParameter(String url, String param, String value) {
    StringBuilder sb = new StringBuilder(url);
    if (url.contains("?")) {
        sb.append('&');
    } else {/* w w w  .j  a  v  a  2 s. c  o  m*/
        sb.append('?');
    }

    URLCodec codec = new URLCodec();

    try {
        sb.append(codec.encode(param));
    } catch (EncoderException e) {
        log.error("Exception encoding URL param " + param, e);
    }

    try {
        sb.append('=').append(codec.encode(value));
    } catch (EncoderException e) {
        log.error("Exception encoding URL value " + value, e);
    }

    return sb.toString();
}

From source file:com.wwpass.connection.WWPassConnection.java

private InputStream makeRequest(String method, String command, Map<String, ?> parameters)
        throws IOException, WWPassProtocolException {
    String commandUrl = SpfeURL + command + ".xml";
    //String command_url = SpfeURL + command + ".json";

    StringBuilder sb = new StringBuilder();
    URLCodec codec = new URLCodec();

    @SuppressWarnings("unchecked")
    Map<String, Object> localParams = (Map<String, Object>) parameters;

    for (Map.Entry<String, Object> entry : localParams.entrySet()) {
        sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        sb.append("=");
        if (entry.getValue() instanceof String) {
            sb.append(URLEncoder.encode((String) entry.getValue(), "UTF-8"));
        } else {//from  w  w w.j a v a2 s  . c o  m
            sb.append(new String(codec.encode((byte[]) entry.getValue())));
        }
        sb.append("&");
    }
    String paramsString = sb.toString();
    sb = null;
    if ("GET".equalsIgnoreCase(method)) {
        commandUrl += "?" + paramsString;
    } else if ("POST".equalsIgnoreCase(method)) {

    } else {
        throw new IllegalArgumentException("Method " + method + " not supported.");
    }

    HttpsURLConnection conn = null;
    try {
        URL url = new URL(commandUrl);
        conn = (HttpsURLConnection) url.openConnection();
        conn.setReadTimeout(timeoutMs);
        conn.setSSLSocketFactory(SPFEContext.getSocketFactory());
        if ("POST".equalsIgnoreCase(method)) {
            conn.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
            writer.write(paramsString);
            writer.flush();
        }
        InputStream in = conn.getInputStream();
        return getReplyData(in);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Command-parameters combination is invalid: " + e.getMessage());
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

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

/**
 * The doPost method of the servlet. <br>
 * /* w ww .  j  a v a2 s  . c  o  m*/
 * This method is called when a form has its tag value method equals to post.
 * 
 * @param request
 *          the request send by the client to the server
 * @param response
 *          the response send by the server to the client
 * @throws ServletException
 *           if an error occurred
 * @throws IOException
 *           if an error occurred
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession httpSession = request.getSession();
    String titleHTML = "";
    String creatorsHTML = "";
    String abstractHTML = "";
    String publicationDateHTML = "";
    String spatialCoverageHTML = "";
    String googleMapHTML = "";
    String packageIdHTML = "";
    String resourcesHTML = "";
    String citationHTML = "";
    String provenanceHTML = "";
    String codeGenerationHTML = "";
    String digitalObjectIdentifier = "";
    String pastaDataObjectIdentifier = "";
    String savedDataHTML = "";
    boolean showSaved = false;
    boolean isSaved = false;

    String uid = (String) httpSession.getAttribute("uid");

    if (uid == null || uid.isEmpty()) {
        uid = "public";
    } else {
        showSaved = true;
    }

    Integer id = null;
    boolean isPackageId = false;

    // Accept packageId by parts or whole
    String scope = request.getParameter("scope");
    String identifier = request.getParameter("identifier");
    String revision = request.getParameter("revision");
    String packageid = request.getParameter("packageid");

    try {
        if (scope != null && !(scope.isEmpty()) && identifier != null && !(identifier.isEmpty())) {

            if (revision == null || revision.isEmpty()) {
                revision = "newest";
            }

            id = Integer.valueOf(identifier);
            isPackageId = true;
        } else if (packageid != null && !packageid.isEmpty()) {

            String[] tokens = packageid.split("\\.");

            if (tokens.length == 3) {
                scope = tokens[0];
                identifier = tokens[1];
                id = Integer.valueOf(identifier);
                revision = tokens[2];
                isPackageId = true;
            }
        } else {
            String msg = "A well-formed packageId was not found.";
            throw new UserErrorException(msg);
        }

        if (isPackageId) {
            StringBuilder titleHTMLBuilder = new StringBuilder();
            StringBuilder creatorsHTMLBuilder = new StringBuilder();
            StringBuilder publicationDateHTMLBuilder = new StringBuilder();
            StringBuilder spatialCoverageHTMLBuilder = new StringBuilder();
            StringBuilder googleMapHTMLBuilder = new StringBuilder();
            StringBuilder packageIdHTMLBuilder = new StringBuilder();
            StringBuilder resourcesHTMLBuilder = new StringBuilder();
            StringBuilder citationHTMLBuilder = new StringBuilder();
            StringBuilder provenanceHTMLBuilder = new StringBuilder();
            StringBuilder codeGenerationHTMLBuilder = new StringBuilder();
            StringBuilder savedDataHTMLBuilder = new StringBuilder();

            String packageId = null;

            Integer size = null;
            Integer predecessor = null;
            Integer successor = null;
            String previous = "";
            String next = "";
            String revisions = "";

            String metadataUri = pastaUriHead + "metadata/eml";
            String reportUri = pastaUriHead + "report";
            String dataUri = pastaUriHead + "data/eml";

            String[] uriTokens = null;
            String entityId = null;
            String resource = null;

            String map = null;
            StrTokenizer tokens = null;
            String emlString = null;
            EmlObject emlObject = null;
            ArrayList<Title> titles = null;
            ArrayList<ResponsibleParty> creators = null;

            DataPackageManagerClient dpmClient = null;
            RevisionUtility revUtil = null;

            try {

                dpmClient = new DataPackageManagerClient(uid);

                String revisionList = dpmClient.listDataPackageRevisions(scope, id, null);
                revUtil = new RevisionUtility(revisionList);
                size = revUtil.getSize();

                if (revision.equals("newest"))
                    revision = revUtil.getNewest().toString();

                packageId = scope + "." + id.toString() + "." + revision;
                predecessor = revUtil.getPredecessor(Integer.valueOf(revision));
                successor = revUtil.getSuccessor(Integer.valueOf(revision));

                emlString = dpmClient.readMetadata(scope, id, revision);
                emlObject = new EmlObject(emlString);
                titles = emlObject.getTitles();

                if (showSaved) {
                    SavedData savedData = new SavedData(uid);
                    Integer identifierInt = new Integer(identifier);
                    isSaved = savedData.hasDocid(scope, identifierInt);
                }

                if (showSaved) {
                    String operation = isSaved ? "unsave" : "save";
                    String display = isSaved ? "Remove from your data shelf" : "Add to your data shelf";
                    String imgName = isSaved ? "minus_blue_small.png" : "plus_blue_small.png";

                    savedDataHTMLBuilder.append(
                            "<form style=\"display:inline-block\" id=\"savedData\" class=\"form-no-margin\" name=\"savedDataForm\" method=\"post\" action=\"./savedDataServlet\" >\n");
                    savedDataHTMLBuilder.append(
                            "  <input type=\"hidden\" name=\"operation\" value=\"" + operation + "\" >\n");
                    savedDataHTMLBuilder.append(
                            "  <input type=\"hidden\" name=\"packageId\" value=\"" + packageId + "\" >\n");
                    savedDataHTMLBuilder.append("  <input type=\"hidden\" name=\"forward\" value=\"\" >\n");
                    savedDataHTMLBuilder.append("  <sup><input type=\"image\" name=\"submit\" src=\"images/"
                            + imgName + "\" alt=\"" + display + "\" title=\"" + display + "\"></sup>");
                    savedDataHTMLBuilder.append("</form>\n");
                    savedDataHTML = savedDataHTMLBuilder.toString();
                }

                if (titles != null) {
                    titleHTMLBuilder.append("<ul class=\"no-list-style\">\n");

                    for (Title title : titles) {
                        String listItem = "<li>" + title.getTitle() + "</li>\n";
                        titleHTMLBuilder.append(listItem);
                    }

                    titleHTMLBuilder.append("</ul>\n");
                    titleHTML = titleHTMLBuilder.toString();
                }

                creators = emlObject.getCreators();

                if (creators != null) {

                    creatorsHTMLBuilder.append("<ul class=\"no-list-style\">\n");

                    for (ResponsibleParty creator : creators) {
                        creatorsHTMLBuilder.append("<li>");

                        String individualName = creator.getIndividualName();
                        String positionName = creator.getPositionName();
                        String organizationName = creator.getOrganizationName();

                        if (individualName != null) {
                            creatorsHTMLBuilder.append(individualName);
                        }

                        if (positionName != null) {
                            if (individualName != null) {
                                creatorsHTMLBuilder.append("; " + positionName);
                            } else {
                                creatorsHTMLBuilder.append(positionName);
                            }
                        }

                        if (organizationName != null) {
                            if (positionName != null || individualName != null) {
                                creatorsHTMLBuilder.append("; " + organizationName);
                            } else {
                                creatorsHTMLBuilder.append(organizationName);
                            }
                        }

                        creatorsHTMLBuilder.append("</li>\n");
                    }

                    creatorsHTMLBuilder.append("</ul>\n");
                    creatorsHTML = creatorsHTMLBuilder.toString();
                }

                String abstractText = emlObject.getAbstractText();

                if (abstractText != null) {
                    abstractHTML = toSingleLine(abstractText);
                }

                String pubDate = emlObject.getPubDate();

                if (pubDate != null) {
                    publicationDateHTMLBuilder.append("<ul class=\"no-list-style\">\n");
                    publicationDateHTMLBuilder.append("<li>" + pubDate + "</li>");
                    publicationDateHTMLBuilder.append("</ul>");
                    publicationDateHTML = publicationDateHTMLBuilder.toString();
                }

                map = dpmClient.readDataPackage(scope, id, revision);

                String jsonCoordinates = emlObject.jsonSerializeCoordinates();
                String stringCoordinates = emlObject.stringSerializeCoordinates();

                request.setAttribute("jsonCoordinates", jsonCoordinates);
                if (stringCoordinates != null && !stringCoordinates.equals("")) {

                    String[] coordinatesArray = stringCoordinates.split(":");

                    /*
                     * If there are two or fewer sets of coordinates, then initially
                     * show them expanded, otherwise show them collapsed (to save
                     * screen space.)
                     */
                    request.setAttribute("expandCoordinates", new Boolean((coordinatesArray.length <= 2)));

                    // Only use the expander widget if there's more than one set of coordinates
                    boolean useExpander = (coordinatesArray.length > 1) ? true : false;

                    if (useExpander) {
                        spatialCoverageHTMLBuilder.append("<div id='jqxWidget'>\n");
                        spatialCoverageHTMLBuilder.append("    <div id='jqxExpander'>\n");
                        spatialCoverageHTMLBuilder.append("        <div>Geographic Coordinates</div>\n");
                        spatialCoverageHTMLBuilder.append("        <div>\n");
                        spatialCoverageHTMLBuilder.append("            <ul class=\"no-list-style\">\n");
                        boolean firstCoordinates = true;

                        for (String coordinates : coordinatesArray) {
                            String[] nsew = coordinates.split(",");
                            Double northCoord = new Double(nsew[0]);
                            Double southCoord = new Double(nsew[1]);
                            Double eastCoord = new Double(nsew[2]);
                            Double westCoord = new Double(nsew[3]);
                            if (firstCoordinates) {
                                request.setAttribute("northCoord", northCoord);
                                request.setAttribute("southCoord", southCoord);
                                request.setAttribute("eastCoord", eastCoord);
                                request.setAttribute("westCoord", westCoord);
                            }
                            firstCoordinates = false;
                            String spatial = String.format("N: %s,  S: %s,  E: %s,  W: %s", northCoord,
                                    southCoord, eastCoord, westCoord);
                            spatialCoverageHTMLBuilder.append(String.format("  <li>%s</li>\n", spatial));
                        }

                        spatialCoverageHTMLBuilder.append("            </ul>\n");
                        spatialCoverageHTMLBuilder.append("        </div>\n");
                        spatialCoverageHTMLBuilder.append("    </div>\n");
                        spatialCoverageHTMLBuilder.append("</div>\n");
                    } else {
                        String[] nsew = coordinatesArray[0].split(",");
                        Double northCoord = new Double(nsew[0]);
                        Double southCoord = new Double(nsew[1]);
                        Double eastCoord = new Double(nsew[2]);
                        Double westCoord = new Double(nsew[3]);
                        request.setAttribute("northCoord", northCoord);
                        request.setAttribute("southCoord", southCoord);
                        request.setAttribute("eastCoord", eastCoord);
                        request.setAttribute("westCoord", westCoord);
                        final String spacer = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                        spatialCoverageHTMLBuilder.append("<div>\n");
                        String spatial = String.format("N: %s%sS: %s%sE: %s%sW: %s", northCoord, spacer,
                                southCoord, spacer, eastCoord, spacer, westCoord);
                        spatialCoverageHTMLBuilder.append(String.format("%s\n", spatial));
                        spatialCoverageHTMLBuilder.append("</div>\n");
                    }

                    spatialCoverageHTML = spatialCoverageHTMLBuilder.toString();

                    googleMapHTMLBuilder.append("<ul class=\"no-list-style\">\n");
                    googleMapHTMLBuilder.append("  <li><div id='map-canvas-summary'></div></li>");
                    googleMapHTMLBuilder.append("</ul>\n");
                    googleMapHTML = googleMapHTMLBuilder.toString();
                }

            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
                throw (e);
            }

            tokens = new StrTokenizer(map);

            URLCodec urlCodec = new URLCodec();

            String packageIdListItem = null;
            String metadata = null;
            String report = null;
            String data = "";
            String doiId = null;
            String entityNames = dpmClient.readDataEntityNames(scope, id, revision);
            String entitySizes = dpmClient.readDataEntitySizes(scope, id, revision);

            while (tokens.hasNext()) {
                resource = tokens.nextToken();

                if (resource.contains(metadataUri)) {

                    metadata = "<li><a class=\"searchsubcat\" href=\"./metadataviewer?packageid=" + packageId
                            + "\">Metadata</a></li>\n";

                } else if (resource.contains(reportUri)) {

                    report = "<li><a class=\"searchsubcat\" href=\"./reportviewer?packageid=" + packageId
                            + "\" target=\"_blank\">Report</a></li>\n";

                } else if (resource.contains(dataUri)) {
                    uriTokens = resource.split("/");
                    entityId = uriTokens[uriTokens.length - 1];
                    String entityName = null;
                    String entitySize = null;
                    String entitySizeStr = "";

                    entityName = findEntityName(entityNames, entityId);
                    entitySize = findEntitySize(entitySizes, entityId);

                    if (entitySize != null) {
                        entitySizeStr = String.format("&nbsp;&nbsp;<small><em>(%s bytes)</em></small>",
                                entitySize);
                    }

                    // Safe URL encoding of entity id
                    try {
                        entityId = urlCodec.encode(entityId);
                    } catch (EncoderException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }

                    /*
                     * Entity name will only be returned for authorized data
                     * entities, so if it's non-null then we know the user is authorized.
                     */
                    Boolean isAuthorized = false;

                    if (entityName != null) {
                        isAuthorized = true;
                    }

                    if (isAuthorized) {
                        data += "<li><a class=\"searchsubcat\" href=\"./dataviewer?packageid=" + packageId
                                + "&entityid=" + entityId + "\" target=\"_blank\">" + entityName + "</a>"
                                + entitySizeStr + "</li>\n";
                    } else {
                        entityName = "Data object";
                        String tooltip = null;
                        if (uid.equals("public")) {
                            tooltip = "You may need to log in before you can access this data object.";
                        } else {
                            tooltip = "You may not have permission to access this data object.";
                        }
                        data += String.format(
                                "<li>%s [<span name='%s' class='tooltip'><em>more info</em></span>]</li>\n",
                                entityName, tooltip);
                    }
                } else {

                    try {
                        doiId = dpmClient.readDataPackageDoi(scope, id, revision);
                    } catch (Exception e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }

                    pastaDataObjectIdentifier = dpmClient.getPastaPackageUri(scope, id, revision);

                    packageIdListItem = "<li>" + packageId + "&nbsp;&nbsp;" + savedDataHTML + "</li>\n";

                    if (predecessor != null) {
                        previous = "<li><a class=\"searchsubcat\" href=\"./mapbrowse?scope=" + scope
                                + "&identifier=" + identifier.toString() + "&revision=" + predecessor.toString()
                                + "\">previous revision</a></li>\n";
                    }

                    if (successor != null) {
                        next = "<li><a class=\"searchsubcat\" href=\"./mapbrowse?scope=" + scope
                                + "&identifier=" + identifier.toString() + "&revision=" + successor.toString()
                                + "\">next revision</a></li>\n";
                    }

                    if (size > 1) {
                        revisions = "<li><a class=\"searchsubcat\" href=\"./revisionbrowse?scope=" + scope
                                + "&identifier=" + identifier.toString() + "\">all revisions</a></li>\n";
                    }

                }

            }

            packageIdHTMLBuilder.append("<ul class=\"no-list-style\">\n");
            packageIdHTMLBuilder.append(packageIdListItem);
            packageIdHTMLBuilder.append(previous);
            packageIdHTMLBuilder.append(next);
            packageIdHTMLBuilder.append(revisions);
            packageIdHTMLBuilder.append("</ul>\n");
            packageIdHTML = packageIdHTMLBuilder.toString();

            resourcesHTMLBuilder.append("<ul class=\"no-list-style\">\n");
            resourcesHTMLBuilder.append(metadata);
            resourcesHTMLBuilder.append(report);
            resourcesHTMLBuilder.append("<li>Data <sup><strong>*</strong></sup>\n");
            resourcesHTMLBuilder.append("<ol>\n");
            resourcesHTMLBuilder.append(data);
            resourcesHTMLBuilder.append("</ol>\n");
            resourcesHTMLBuilder.append("</li>\n");

            resourcesHTMLBuilder.append("<li>&nbsp;</li>\n");

            resourcesHTMLBuilder.append("<li>\n");
            resourcesHTMLBuilder.append("<div>\n");
            resourcesHTMLBuilder.append(
                    "<form id=\"archive\" name=\"archiveform\" method=\"post\" action=\"./archiveDownload\"   target=\"_top\">\n");
            resourcesHTMLBuilder
                    .append("  <input type=\"hidden\" name=\"packageid\" value=\"" + packageId + "\" >\n");
            resourcesHTMLBuilder.append(
                    "  <input class=\"btn btn-info btn-default\" type=\"submit\" name=\"archive\" value=\"Download Zip Archive\" >\n");
            resourcesHTMLBuilder.append("</form>\n");
            resourcesHTMLBuilder.append("</div>\n");
            resourcesHTMLBuilder.append("</li>\n");

            resourcesHTMLBuilder.append("<li>\n");
            resourcesHTMLBuilder.append(
                    "<sup><strong>*</strong></sup> <em>By downloading any data you implicitly acknowledge the "
                            + "<a class=\"searchsubcat\" href=\"http://www.lternet.edu/data/netpolicy.html\">"
                            + "LTER Data Policy</a></em>");
            resourcesHTMLBuilder.append("</li>\n");

            resourcesHTMLBuilder.append("</ul>\n");
            resourcesHTML = resourcesHTMLBuilder.toString();

            if (doiId != null) {
                digitalObjectIdentifier = doiId;
            }

            citationHTMLBuilder.append("<a class=\"searchsubcat\" href=\"./dataPackageCitation?scope=" + scope
                    + "&" + "identifier=" + identifier.toString() + "&" + "revision=" + revision
                    + "\">How to cite this data package</a>\n");
            citationHTML = citationHTMLBuilder.toString();

            String dataSourcesStr = dpmClient.listDataSources(scope, id, revision);

            String source = null;
            String derived = null;

            if (dataSourcesStr != null && dataSourcesStr.length() > 0) {
                derived = packageId;
                String[] dataSources = dataSourcesStr.split("\n");
                if (dataSources.length > 0) {
                    String dataSource = dataSources[0];
                    if (dataSource != null && dataSource.length() > 0) {
                        provenanceHTMLBuilder
                                .append("This data package is derived from the following sources:<br/>");
                        provenanceHTMLBuilder.append("<ol>\n");
                        for (String uri : dataSources) {
                            String mapbrowseURL = mapbrowseURL(uri);
                            if (source == null) {
                                source = packageIdFromPastaId(uri);
                            }
                            String listItem = String.format("<li>%s</li>", mapbrowseURL);
                            provenanceHTMLBuilder.append(listItem);
                        }
                        provenanceHTMLBuilder.append("</ol>\n");
                        provenanceHTMLBuilder.append("<br/>");
                    }
                }
            }

            String dataDescendantsStr = dpmClient.listDataDescendants(scope, id, revision);

            if (dataDescendantsStr != null && dataDescendantsStr.length() > 0) {
                source = packageId;
                String[] dataDescendants = dataDescendantsStr.split("\n");
                if (dataDescendants.length > 0) {
                    String dataDescendant = dataDescendants[0];
                    if (dataDescendant != null && dataDescendant.length() > 0) {
                        provenanceHTMLBuilder.append(
                                "This data package is a source for the following derived data packages:<br/>");
                        provenanceHTMLBuilder.append("<ol>\n");
                        for (String uri : dataDescendants) {
                            String mapbrowseURL = mapbrowseURL(uri);
                            if (derived == null) {
                                derived = packageIdFromPastaId(uri);
                            }
                            String listItem = String.format("<li>%s</li>", mapbrowseURL);
                            provenanceHTMLBuilder.append(listItem);
                        }
                        provenanceHTMLBuilder.append("</ol>\n");
                        provenanceHTMLBuilder.append("<br/>");
                    }
                }
            }

            /*
             * Provenance graph
             */
            if ((source != null) && (derived != null)) {
                String graphString = String.format(
                        "View a <a class=\"searchsubcat\" href=\"./provenanceGraph?source=%s&derived=%s\">"
                                + "provenance graph</a> of this data package",
                        source, derived);
                provenanceHTMLBuilder.append(graphString);
                provenanceHTMLBuilder.append("<br/><br/>");
            }

            /*
             * Provenance metadata generator
             */
            provenanceHTMLBuilder
                    .append(String.format(
                            "Generate <a class=\"searchsubcat\" href=\"./provenanceGenerator?packageid=%s\">"
                                    + "provenance metadata</a> for use within your derived data package",
                            packageId));

            provenanceHTML = provenanceHTMLBuilder.toString();

            /*
             * Add code generation section only if this data package has at
             * least one entity that is a data table.
             */
            DataPackage dataPackage = emlObject.getDataPackage();
            boolean hasDataTableEntity = dataPackage.hasDataTableEntity();
            if (hasDataTableEntity) {
                ArrayList<String> programLinks = CodeGenerationServlet.getProgramLinks(packageId);
                codeGenerationHTMLBuilder.append("Analyze this data package using ");
                for (String programLink : programLinks) {
                    codeGenerationHTMLBuilder.append(String.format("%s, ", programLink));
                }
                codeGenerationHTML = codeGenerationHTMLBuilder.toString();
                codeGenerationHTML = codeGenerationHTML.substring(0, codeGenerationHTML.length() - 2); // trim the last
                // comma and
                // space
            }

        }

        else {
            String msg = "The 'scope', 'identifier', or 'revision' field of the packageId is empty.";
            throw new UserErrorException(msg);
        }
    } catch (Exception e) {
        handleDataPortalError(logger, e);
    }

    request.setAttribute("dataPackageTitleHTML", titleHTML);
    request.setAttribute("dataPackageCreatorsHTML", creatorsHTML);
    request.setAttribute("abstractHTML", abstractHTML);
    request.setAttribute("dataPackagePublicationDateHTML", publicationDateHTML);
    request.setAttribute("spatialCoverageHTML", spatialCoverageHTML);
    request.setAttribute("googleMapHTML", googleMapHTML);
    request.setAttribute("dataPackageIdHTML", packageIdHTML);
    request.setAttribute("dataPackageResourcesHTML", resourcesHTML);
    request.setAttribute("dataPackageCitationHTML", citationHTML);
    request.setAttribute("digitalObjectIdentifier", digitalObjectIdentifier);
    request.setAttribute("pastaDataObjectIdentifier", pastaDataObjectIdentifier);
    request.setAttribute("provenanceHTML", provenanceHTML);
    request.setAttribute("codeGenerationHTML", codeGenerationHTML);

    RequestDispatcher requestDispatcher = request.getRequestDispatcher(forward);
    requestDispatcher.forward(request, response);
}

From source file:nor.util.Codec.java

public static String urlEncode(final String str) {

    String ret = str;//from ww w  .  j a  v a 2  s. co  m
    try {

        ret = URLCodec.encode(str);

    } catch (EncoderException e) {

        LOGGER.severe(e.getLocalizedMessage());

    }

    return ret;

}

From source file:org.alfresco.solr.client.SOLRAPIClient.java

public Transactions getTransactions(Long fromCommitTime, Long minTxnId, Long toCommitTime, Long maxTxnId,
        int maxResults, ShardState shardState)
        throws AuthenticationException, IOException, JSONException, EncoderException {
    URLCodec encoder = new URLCodec();

    StringBuilder url = new StringBuilder(GET_TRANSACTIONS_URL);
    StringBuilder args = new StringBuilder();
    if (fromCommitTime != null) {
        args.append("?").append("fromCommitTime").append("=").append(fromCommitTime);
    }/*from w w  w  .j a  va2 s  .  c  o m*/
    if (minTxnId != null) {
        args.append(args.length() == 0 ? "?" : "&").append("minTxnId").append("=").append(minTxnId);
    }
    if (toCommitTime != null) {
        args.append(args.length() == 0 ? "?" : "&").append("toCommitTime").append("=").append(toCommitTime);
    }
    if (maxTxnId != null) {
        args.append(args.length() == 0 ? "?" : "&").append("maxTxnId").append("=").append(maxTxnId);
    }
    if (maxResults != 0 && maxResults != Integer.MAX_VALUE) {
        args.append(args.length() == 0 ? "?" : "&").append("maxResults").append("=").append(maxResults);
    }
    if (shardState != null) {
        args.append(args.length() == 0 ? "?" : "&");
        args.append(encoder.encode("baseUrl")).append("=")
                .append(encoder.encode(shardState.getShardInstance().getBaseUrl()));
        args.append("&").append(encoder.encode("hostName")).append("=")
                .append(encoder.encode(shardState.getShardInstance().getHostName()));
        args.append("&").append(encoder.encode("template")).append("=")
                .append(encoder.encode(shardState.getShardInstance().getShard().getFloc().getTemplate()));

        for (String key : shardState.getShardInstance().getShard().getFloc().getPropertyBag().keySet()) {
            String value = shardState.getShardInstance().getShard().getFloc().getPropertyBag().get(key);
            if (value != null) {
                args.append("&").append(encoder.encode("floc.property." + key)).append("=")
                        .append(encoder.encode(value));
            }
        }

        for (String key : shardState.getPropertyBag().keySet()) {
            String value = shardState.getPropertyBag().get(key);
            if (value != null) {
                args.append("&").append(encoder.encode("state.property." + key)).append("=")
                        .append(encoder.encode(value));
            }
        }

        args.append("&").append(encoder.encode("instance")).append("=")
                .append(encoder.encode("" + shardState.getShardInstance().getShard().getInstance()));
        args.append("&").append(encoder.encode("numberOfShards")).append("=").append(
                encoder.encode("" + shardState.getShardInstance().getShard().getFloc().getNumberOfShards()));
        args.append("&").append(encoder.encode("port")).append("=")
                .append(encoder.encode("" + shardState.getShardInstance().getPort()));
        args.append("&").append(encoder.encode("stores")).append("=");
        for (StoreRef store : shardState.getShardInstance().getShard().getFloc().getStoreRefs()) {
            if (args.charAt(args.length() - 1) != '=') {
                args.append(encoder.encode(","));
            }
            args.append(encoder.encode(store.toString()));
        }
        args.append("&").append(encoder.encode("isMaster")).append("=")
                .append(encoder.encode("" + shardState.isMaster()));
        args.append("&").append(encoder.encode("hasContent")).append("=")
                .append(encoder.encode("" + shardState.getShardInstance().getShard().getFloc().hasContent()));
        args.append("&").append(encoder.encode("shardMethod")).append("=").append(
                encoder.encode(shardState.getShardInstance().getShard().getFloc().getShardMethod().toString()));

        args.append("&").append(encoder.encode("lastUpdated")).append("=")
                .append(encoder.encode("" + shardState.getLastUpdated()));
        args.append("&").append(encoder.encode("lastIndexedChangeSetCommitTime")).append("=")
                .append(encoder.encode("" + shardState.getLastIndexedChangeSetCommitTime()));
        args.append("&").append(encoder.encode("lastIndexedChangeSetId")).append("=")
                .append(encoder.encode("" + shardState.getLastIndexedChangeSetId()));
        args.append("&").append(encoder.encode("lastIndexedTxCommitTime")).append("=")
                .append(encoder.encode("" + shardState.getLastIndexedTxCommitTime()));
        args.append("&").append(encoder.encode("lastIndexedTxId")).append("=")
                .append(encoder.encode("" + shardState.getLastIndexedTxId()));

    }

    url.append(args);

    GetRequest req = new GetRequest(url.toString());
    Response response = null;
    List<Transaction> transactions = new ArrayList<Transaction>();
    Long maxTxnCommitTime = null;
    Long maxTxnIdOnServer = null;
    try {
        response = repositoryHttpClient.sendRequest(req);
        if (response.getStatus() != HttpStatus.SC_OK) {
            throw new AlfrescoRuntimeException("GetTransactions return status is " + response.getStatus());
        }

        Reader reader = new BufferedReader(new InputStreamReader(response.getContentAsStream(), "UTF-8"));
        JsonParser parser = jsonFactory.createJsonParser(reader);

        JsonToken token = parser.nextValue();
        while (token != null) {
            if ("transactions".equals(parser.getCurrentName())) {
                token = parser.nextToken(); //START_ARRAY
                while (token == JsonToken.START_OBJECT) {
                    token = parser.nextValue();
                    long id = parser.getLongValue();

                    token = parser.nextValue();
                    long commitTime = parser.getLongValue();

                    token = parser.nextValue();
                    long updates = parser.getLongValue();

                    token = parser.nextValue();
                    long deletes = parser.getLongValue();

                    Transaction txn = new Transaction();
                    txn.setCommitTimeMs(commitTime);
                    txn.setDeletes(deletes);
                    txn.setId(id);
                    txn.setUpdates(updates);

                    transactions.add(txn);

                    token = parser.nextToken(); //END_OBJECT
                    token = parser.nextToken(); // START_OBJECT or END_ARRAY;
                }
            } else if ("maxTxnCommitTime".equals(parser.getCurrentName())) {
                maxTxnCommitTime = parser.getLongValue();
            } else if ("maxTxnId".equals(parser.getCurrentName())) {
                maxTxnIdOnServer = parser.getLongValue();
            }
            token = parser.nextValue();
        }
        parser.close();
        reader.close();

    } finally {
        if (response != null) {
            response.release();
        }
    }

    return new Transactions(transactions, maxTxnCommitTime, maxTxnIdOnServer);
}

From source file:org.apache.tuscany.sca.binding.jsonp.runtime.JSONPInvoker.java

protected String invokeHTTPRequest(String url, String[] jsonArgs) throws IOException, EncoderException {

    HttpClient httpclient = new DefaultHttpClient();

    URLCodec uc = new URLCodec();
    for (int i = 0; i < jsonArgs.length; i++) {
        if (i == 0) {
            url += '?';
        } else {//from w  w  w .ja  v a2  s.  c om
            url += '&';
        }
        url += "arg" + i + "=";
        url += uc.encode(jsonArgs[i]);
    }

    HttpGet httpget = new HttpGet(url);

    HttpResponse response = httpclient.execute(httpget);

    StringBuffer responseJSON = new StringBuffer();

    HttpEntity entity = response.getEntity();

    // If the response does not enclose an entity, there is no need
    // to worry about connection release
    if (entity != null) {
        InputStream instream = entity.getContent();
        try {

            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            String s = null;
            while ((s = reader.readLine()) != null) {
                responseJSON.append(s);
            }

        } catch (IOException ex) {

            // In case of an IOException the connection will be released
            // back to the connection manager automatically
            throw ex;

        } catch (RuntimeException ex) {

            // In case of an unexpected exception you may want to abort
            // the HTTP request in order to shut down the underlying 
            // connection and release it back to the connection manager.
            httpget.abort();
            throw ex;

        } finally {

            // Closing the input stream will trigger connection release
            instream.close();

        }

        // When HttpClient instance is no longer needed, 
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    return responseJSON.toString();
}

From source file:org.datacleaner.monitor.pentaho.PentahoCarteClient.java

private String getUrl(String serviceName, String id, String name) throws PentahoJobException {
    final URLCodec urlCodec = new URLCodec();

    final StringBuilder url = new StringBuilder();
    url.append("http://");
    url.append(_pentahoJobType.getCarteHostname());
    url.append(':');
    url.append(_pentahoJobType.getCartePort());
    url.append("/kettle/");
    url.append(serviceName);//from   www  . j  a  v  a  2s  .  co  m
    url.append("/?xml=y");
    if (!StringUtils.isNullOrEmpty(id)) {
        url.append("&id=");
        try {
            final String encodedId = urlCodec.encode(id);
            url.append(encodedId);
        } catch (EncoderException e) {
            throw new PentahoJobException("Failed to encode transformation id: " + id);
        }
    }

    if (!StringUtils.isNullOrEmpty(name)) {
        url.append("&name=");
        try {
            final String encodedName = urlCodec.encode(name);
            url.append(encodedName);
        } catch (EncoderException e) {
            throw new PentahoJobException("Failed to encode transformation name: " + name);
        }
    }

    return url.toString();
}