Example usage for org.apache.commons.httpclient.util URIUtil encodeWithinQuery

List of usage examples for org.apache.commons.httpclient.util URIUtil encodeWithinQuery

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.util URIUtil encodeWithinQuery.

Prototype

public static String encodeWithinQuery(String unescaped) throws URIException 

Source Link

Document

Escape and encode a string regarded as within the query component of an URI with the default protocol charset.

Usage

From source file:ch.lipsch.subsonic4j.internal.SubsonicUtil.java

/**
 * Appends a key value pair to an url if the value is set. Must only be used
 * there is already a parameter set on the url. * @param url
 * //from  w  w w .  ja  va  2 s  .  c  om
 * @param key
 *            The parameter name. May be <code>null</code>.
 * @param value
 *            The value. May be <code>null</code>.
 * @return The key & value added to the url:
 *         http://12.34.56.78?first=bla&key=value
 * @throws SubsonicException
 *             In case the value can not be encode to fit into the url.
 */
public static String appendIfSet(String url, String key, String value) throws SubsonicException {
    if (key != null && value != null) {
        try {
            return url + "&" + key + "=" + URIUtil.encodeWithinQuery(value);
        } catch (URIException e) {
            throw new SubsonicException(ErrorType.GENERIC, e);
        }
    } else {
        return url;
    }
}

From source file:net.hillsdon.reviki.web.pages.impl.TextFormatSearchResults.java

public void render(final HttpServletRequest request, final PrintWriter writer) throws Exception {
    String wiki;//  w ww .j av a 2s. c  o m
    String page;
    for (SearchMatch matcher : _results) {
        wiki = matcher.getWiki();
        page = matcher.getPage();

        if (matcher.isSameWiki()) {
            writer.println(matcher.getPage());
        } else {
            StringBuilder s = new StringBuilder(wiki + ";" + page);
            try {
                s.append(";" + getUrlForPage(request, wiki, page));
            } catch (UnknownWikiException e) {
                // Do not respond with URL component
            }
            writer.println(s.toString());
        }
    }
    if (request.getHeader("Authorization") == null) {
        writer.println("Not logged in;Log in to see all results;" + getUrlForPage(request, null, "FindPage")
                + "?query=" + URIUtil.encodeWithinQuery(request.getParameter("query")));
    }
}

From source file:davmail.util.StringUtilTest.java

public void testEncodeQuestion() {
    try {/*from  w ww. java  2 s .com*/
        URIUtil.encodeWithinQuery("test ?");
    } catch (URIException e) {
        e.printStackTrace();
    }
    assertEquals("test %3F", StringUtil.encodeUrlcompname("test ?"));
    assertEquals("test ?", StringUtil.decodeUrlcompname("test %3F"));
}

From source file:com.panet.imeta.trans.steps.http.HTTP.java

private String determineUrl(RowMetaInterface outputRowMeta, Object[] row)
        throws KettleValueException, KettleException {
    try {//from w  ww .j  av  a2  s.co  m
        if (meta.isUrlInField()) {
            // get dynamic url
            data.realUrl = outputRowMeta.getString(row, data.indexOfUrlField);
        }
        StringBuffer url = new StringBuffer(data.realUrl); // the base URL with variable substitution

        for (int i = 0; i < data.argnrs.length; i++) {
            if (i == 0 && url.indexOf("?") < 0) {
                url.append('?');
            } else {
                url.append('&');
            }

            url.append(URIUtil.encodeWithinQuery(meta.getArgumentParameter()[i]));
            url.append('=');
            String s = outputRowMeta.getString(row, data.argnrs[i]);
            if (s != null)
                s = URIUtil.encodeWithinQuery(s);
            url.append(s);
        }

        return url.toString();
    } catch (Exception e) {
        throw new KettleException(Messages.getString("HTTP.Log.UnableCreateUrl"), e);
    }
}

From source file:au.org.ala.biocache.dto.SearchRequestParams.java

/**
 * URI encode the param value if isEncoded is true
 *
 * @param input//  ww w  . j a v a2  s . co  m
 * @param isEncoded
 * @return query string
 */
protected String conditionalEncode(String input, Boolean isEncoded) {
    String output;

    if (isEncoded) {
        try {
            output = URIUtil.encodeWithinQuery(input);
        } catch (URIException e) {
            logger.warn("URIUtil encoding error: " + e.getMessage(), e);
            output = input;
        }
    } else {
        output = input;
    }

    return output;
}

From source file:davmail.caldav.CaldavConnection.java

protected void appendItemResponse(CaldavResponse response, CaldavRequest request, ExchangeSession.Item item)
        throws IOException {
    StringBuilder eventPath = new StringBuilder();
    eventPath.append(encodePath(request, request.getPath()));
    if (!(eventPath.charAt(eventPath.length() - 1) == '/')) {
        eventPath.append('/');
    }//  w w  w .  j  av a 2 s .  com
    String itemName = StringUtil.xmlEncode(item.getName());
    eventPath.append(URIUtil.encodeWithinQuery(itemName));
    response.startResponse(eventPath.toString());
    response.startPropstat();
    if (request.hasProperty("calendar-data") && item instanceof ExchangeSession.Event) {
        response.appendCalendarData(item.getBody());
    }
    if (request.hasProperty("address-data") && item instanceof ExchangeSession.Contact) {
        response.appendContactData(item.getBody());
    }
    if (request.hasProperty("getcontenttype")) {
        if (item instanceof ExchangeSession.Event) {
            response.appendProperty("D:getcontenttype", "text/calendar; component=vevent");
        } else if (item instanceof ExchangeSession.Contact) {
            response.appendProperty("D:getcontenttype", "text/vcard");
        }
    }
    if (request.hasProperty("getetag")) {
        response.appendProperty("D:getetag", item.getEtag());
    }
    if (request.hasProperty("resourcetype")) {
        response.appendProperty("D:resourcetype");
    }
    if (request.hasProperty("displayname")) {
        response.appendProperty("D:displayname", itemName);
    }
    response.endPropStatOK();
    response.endResponse();
}

From source file:davmail.exchange.dav.DavExchangeSession.java

@Override
public Map<String, ExchangeSession.Contact> galFind(Condition condition, Set<String> returningAttributes,
        int sizeLimit) throws IOException {
    Map<String, ExchangeSession.Contact> contacts = new HashMap<String, ExchangeSession.Contact>();
    if (disableGalFind) {
        // do nothing
    } else if (condition instanceof MultiCondition) {
        List<Condition> conditions = ((ExchangeSession.MultiCondition) condition).getConditions();
        Operator operator = ((ExchangeSession.MultiCondition) condition).getOperator();
        if (operator == Operator.Or) {
            for (Condition innerCondition : conditions) {
                contacts.putAll(galFind(innerCondition, returningAttributes, sizeLimit));
            }/*from   ww w.  j a  v  a 2 s. c  om*/
        } else if (operator == Operator.And && !conditions.isEmpty()) {
            Map<String, ExchangeSession.Contact> innerContacts = galFind(conditions.get(0), returningAttributes,
                    sizeLimit);
            for (ExchangeSession.Contact contact : innerContacts.values()) {
                if (condition.isMatch(contact)) {
                    contacts.put(contact.getName().toLowerCase(), contact);
                }
            }
        }
    } else if (condition instanceof AttributeCondition) {
        String searchAttributeName = ((ExchangeSession.AttributeCondition) condition).getAttributeName();
        String searchAttribute = GALFIND_CRITERIA_MAP.get(searchAttributeName);
        if (searchAttribute != null) {
            String searchValue = ((ExchangeSession.AttributeCondition) condition).getValue();
            StringBuilder query = new StringBuilder();
            if ("EM".equals(searchAttribute)) {
                // mail search, split
                int atIndex = searchValue.indexOf('@');
                // remove suffix
                if (atIndex >= 0) {
                    searchValue = searchValue.substring(0, atIndex);
                }
                // split firstname.lastname
                int dotIndex = searchValue.indexOf('.');
                if (dotIndex >= 0) {
                    // assume mail starts with firstname
                    query.append("&FN=").append(URIUtil.encodeWithinQuery(searchValue.substring(0, dotIndex)));
                    query.append("&LN=").append(URIUtil.encodeWithinQuery(searchValue.substring(dotIndex + 1)));
                } else {
                    query.append("&FN=").append(URIUtil.encodeWithinQuery(searchValue));
                }
            } else {
                query.append('&').append(searchAttribute).append('=')
                        .append(URIUtil.encodeWithinQuery(searchValue));
            }
            Map<String, Map<String, String>> results = galFind(query.toString());
            for (Map<String, String> result : results.values()) {
                Contact contact = new Contact();
                contact.setName(result.get("AN"));
                contact.put("imapUid", result.get("AN"));
                buildGalfindContact(contact, result);
                if (needGalLookup(searchAttributeName, returningAttributes)) {
                    galLookup(contact);
                    // iCal fix to suit both iCal 3 and 4:  move cn to sn, remove cn
                } else if (returningAttributes.contains("apple-serviceslocator")) {
                    if (contact.get("cn") != null && returningAttributes.contains("sn")) {
                        contact.put("sn", contact.get("cn"));
                        contact.remove("cn");
                    }
                }
                if (condition.isMatch(contact)) {
                    contacts.put(contact.getName().toLowerCase(), contact);
                }
            }
        }

    }
    return contacts;
}

From source file:davmail.exchange.dav.DavExchangeSession.java

/**
 * Get user email from global address list (galfind).
 *
 * @param alias user alias/* ww  w.j a va  2s. c  om*/
 * @return user email
 */
public String getEmail(String alias) {
    String emailResult = null;
    if (alias != null && !disableGalFind) {
        try {
            Map<String, Map<String, String>> results = galFind("&AN=" + URIUtil.encodeWithinQuery(alias));
            Map<String, String> result = results.get(alias.toLowerCase());
            if (result != null) {
                emailResult = result.get("EM");
            }
        } catch (IOException e) {
            // galfind not available
            disableGalFind = true;
            LOGGER.debug("getEmail(" + alias + ") failed");
        }
    }
    return emailResult;
}

From source file:org.apache.ode.axis2.util.UrlReplacementTransformer.java

/**
 * @param baseUri - the base uri template containing part names enclosed within single curly braces
 * @param values  - a map<String, Element>, the key is a part name (without curly braces), the value the replacement value for the part name. If the value is not a simple type, it will be skipped.
 * @return the encoded uri//w  w  w .  j  a v a  2s  . co  m
 * @throws java.lang.IllegalArgumentException
 *          if a replacement value is null in the map or if a part pattern is found more than once
 */
public String transform(String baseUri, Map<String, Element> values) {
    // the list containing the final split result
    List<String> result = new ArrayList<String>();

    // initial value
    result.add(baseUri);

    // replace each part exactly once
    for (Map.Entry<String, Element> e : values.entrySet()) {

        String partName = e.getKey();
        String replacementValue;
        {
            Element value = e.getValue();
            if (DOMUtils.isEmptyElement(value)) {
                replacementValue = "";
            } else {
                /*
                The expected part value could be a simple type
                or an element of a simple type.
                So if a element is there, take its text content
                else take the text content of the part element itself
                */
                Element childElement = DOMUtils.getFirstChildElement(value);
                if (childElement != null) {
                    replacementValue = DOMUtils.getTextContent(childElement);
                } else {
                    replacementValue = DOMUtils.getTextContent(value);
                }
            }
        }

        // if it is not a simple type, skip it
        if (replacementValue != null) {
            try {
                replacementValue = URIUtil.encodeWithinQuery(replacementValue);
            } catch (URIException urie) {
                // this exception is never thrown by the code of httpclient
                if (log.isWarnEnabled())
                    log.warn(urie.getMessage(), urie);
            }

            // first, search for parentheses
            String partPattern = "\\(" + partName + "\\)";
            if (!replace(result, partPattern, replacementValue)) {
                // if parentheses not found, try braces
                partPattern = "\\{" + partName + "\\}";
                replace(result, partPattern, replacementValue);
            }
        }
    }

    // join all the array elements to form the final url
    StringBuilder sb = new StringBuilder(128);
    for (String aResult : result)
        sb.append(aResult);
    return sb.toString();
}

From source file:org.apache.ode.utils.URITemplate.java

/**
 * Same as {@link #varSubstitution(String, Object[], java.util.Map)} but the {@code preserveUndefinedVar} boolean
 * argument (if {@code true}) allows to preserve an expansion template if the corresponding variable is not defined in the {@code nameValuePairs} map (i.e. map.contains(var)==false).
 * <br/> If a default value exists for the undefined value, it will be used to replace the expansion pattern.
 * <p/>//from  ww  w  .  jav  a 2  s  . c o  m
 * <strong>Beware that this behavior deviates from the URI Template specification.</strong>
 * <p/>
 * For instance:
 * <br/>Given the following template variable names and values:
 * <ul>
 * <li>bar = java</li>
 * <li>foo undefined
 * </ul>
 * <p/>The following expansion templates will be expanded as shown if {@code preserveUndefinedVar} is true:
 * <br/>{bar}
 * <br/>java
 * <br/>
 * <br/>{foo=a_default_value}
 * <br/>a_default_value
 * <br/>
 * <br/>{foo}
 * <br/>{foo}
 */
public static String varSubstitution(String expansionPattern, Object[] expansionInfo,
        Map<String, String> nameValuePairs, boolean preserveUndefinedVar) throws URIException {
    Map vars = (Map) expansionInfo[2];
    // only one var per pattern
    Map.Entry e = (Map.Entry) vars.entrySet().iterator().next();
    String var = (String) e.getKey();
    String defaultValue = (String) e.getValue();
    boolean hasDefaultValue = defaultValue != null;
    // this boolean indicates if the var is mentioned in the map, not that the associated value is not null.
    boolean varDefined = nameValuePairs.containsKey(var);
    String providedValue = nameValuePairs.get(var);
    String res;
    boolean escapingNeeded = true;
    if (varDefined) {
        if (providedValue == null && !hasDefaultValue) {
            res = "";
        } else {
            res = providedValue != null ? providedValue : defaultValue;
        }
    } else {
        // If the variable is undefined and no default value is given then substitute with the empty string,
        // except if preserveUndefinedVar is true

        if (hasDefaultValue) {
            res = defaultValue;
        } else {
            if (preserveUndefinedVar) {
                res = expansionPattern;
                escapingNeeded = false;
            } else {
                res = "";
            }
        }
    }
    // We assume that the replacement value is for the query part of the URI.
    // Actually the query allows less character than the path part. $%&+,:@
    // (acording to RFC2396
    return escapingNeeded ? URIUtil.encodeWithinQuery(res) : res;
}