FileDocCategorySizeDatePackage
UrlHelper.javaAPI DocExample12678Mon Jul 23 13:26:50 BST 2007org.apache.struts2.views.util

UrlHelper

public class UrlHelper extends Object
UrlHelper

Fields Summary
private static final Log
LOG
private static final int
DEFAULT_HTTP_PORT
Default HTTP port (80).
private static final int
DEFAULT_HTTPS_PORT
Default HTTPS port (443).
private static final String
AMP
private static int
httpPort
private static int
httpsPort
private static String
customEncoding
Constructors Summary
Methods Summary
public static voidbuildParametersString(java.util.Map params, java.lang.StringBuffer link)

        buildParametersString(params, link, AMP);
    
public static voidbuildParametersString(java.util.Map params, java.lang.StringBuffer link, java.lang.String paramSeparator)

        if ((params != null) && (params.size() > 0)) {
            if (link.toString().indexOf("?") == -1) {
                link.append("?");
            } else {
                link.append(paramSeparator);
            }

            // Set params
            Iterator iter = params.entrySet().iterator();

            String[] valueHolder = new String[1];

            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String name = (String) entry.getKey();
                Object value = entry.getValue();

                String[] values;

                if (value instanceof String[]) {
                    values = (String[]) value;
                } else {
                    valueHolder[0] = value.toString();
                    values = valueHolder;
                }

                for (int i = 0; i < values.length; i++) {
                    if (values[i] != null) {
                        link.append(name);
                        link.append('=");
                        link.append(translateAndEncode(values[i]));
                    }

                    if (i < (values.length - 1)) {
                        link.append(paramSeparator);
                    }
                }

                if (iter.hasNext()) {
                    link.append(paramSeparator);
                }
            }
        }
    
public static java.lang.StringbuildUrl(java.lang.String action, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, java.util.Map params)

        return buildUrl(action, request, response, params, null, true, true);
    
public static java.lang.StringbuildUrl(java.lang.String action, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, java.util.Map params, java.lang.String scheme, boolean includeContext, boolean encodeResult)

        return buildUrl(action, request, response, params, scheme, includeContext, encodeResult, false);
    
public static java.lang.StringbuildUrl(java.lang.String action, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, java.util.Map params, java.lang.String scheme, boolean includeContext, boolean encodeResult, boolean forceAddSchemeHostAndPort)

        StringBuffer link = new StringBuffer();

        boolean changedScheme = false;

        // only append scheme if it is different to the current scheme *OR*
        // if we explicity want it to be appended by having forceAddSchemeHostAndPort = true
        if (forceAddSchemeHostAndPort) {
            String reqScheme = request.getScheme();
            changedScheme = true;
            link.append(scheme != null ? scheme : reqScheme);
            link.append("://");
            link.append(request.getServerName());

            if (scheme != null) {
                if ((scheme.equals("http") && (httpPort != DEFAULT_HTTP_PORT)) || (scheme.equals("https") && httpsPort != DEFAULT_HTTPS_PORT))
                {
                    link.append(":");
                    link.append(scheme.equals("http") ? httpPort : httpsPort);
                }
            }
        }
        else if (
           (scheme != null) && !scheme.equals(request.getScheme())) {
            changedScheme = true;
            link.append(scheme);
            link.append("://");
            link.append(request.getServerName());

            if ((scheme.equals("http") && (httpPort != DEFAULT_HTTP_PORT)) || (scheme.equals("https") && httpsPort != DEFAULT_HTTPS_PORT))
            {
                link.append(":");
                link.append(scheme.equals("http") ? httpPort : httpsPort);
            }
        }

        if (action != null) {
            // Check if context path needs to be added
            // Add path to absolute links
            if (action.startsWith("/") && includeContext) {
                String contextPath = request.getContextPath();
                if (!contextPath.equals("/")) {
                    link.append(contextPath);
                }
            } else if (changedScheme) {

                // (Applicable to Servlet 2.4 containers)
                // If the request was forwarded, the attribute below will be set with the original URL
                String uri = (String) request.getAttribute("javax.servlet.forward.request_uri");

                // If the attribute wasn't found, default to the value in the request object
                if (uri == null) {
                    uri = request.getRequestURI();
                }

                link.append(uri.substring(0, uri.lastIndexOf('/") + 1));
            }

            // Add page
            link.append(action);
        } else {
            // Go to "same page"
            String requestURI = (String) request.getAttribute("struts.request_uri");

            // (Applicable to Servlet 2.4 containers)
            // If the request was forwarded, the attribute below will be set with the original URL
            if (requestURI == null) {
                requestURI = (String) request.getAttribute("javax.servlet.forward.request_uri");
            }

            // If neither request attributes were found, default to the value in the request object
            if (requestURI == null) {
                requestURI = request.getRequestURI();
            }

            link.append(requestURI);
        }

        //if the action was not explicitly set grab the params from the request
        buildParametersString(params, link);

        String result;

        try {
            result = encodeResult ? response.encodeURL(link.toString()) : link.toString();
        } catch (Exception ex) {
            // Could not encode the URL for some reason
            // Use it unchanged
            result = link.toString();
        }

        return result;
    
private static java.lang.StringgetEncodingFromConfiguration()

        final String encoding;
        if (customEncoding != null) {
            encoding = customEncoding;
        } else {
            encoding = "UTF-8";
        }
        return encoding;
    
public static java.util.MapparseQueryString(java.lang.String queryString)

        Map queryParams = new LinkedHashMap();
        if (queryString != null) {
            String[] params = queryString.split("&");
            for (int a=0; a< params.length; a++) {
                if (params[a].trim().length() > 0) {
                    String[] tmpParams = params[a].split("=");
                    String paramName = null;
                    String paramValue = "";
                    if (tmpParams.length > 0) {
                        paramName = tmpParams[0];
                    }
                    if (tmpParams.length > 1) {
                        paramValue = tmpParams[1];
                    }
                    if (paramName != null) {
                        String translatedParamValue = translateAndDecode(paramValue);

                        if(queryParams.containsKey(paramName)) {
                            // WW-1619 append new param value to existing value(s)
                            Object currentParam = queryParams.get(paramName);
                            if(currentParam instanceof String) {
                                queryParams.put(paramName, new String[] {
                                        (String) currentParam, translatedParamValue});
                            } else {
                                String currentParamValues[] = (String[]) currentParam;
                                List paramList = new ArrayList(Arrays
                                    .asList(currentParamValues));
                                paramList.add(translatedParamValue);
                                String newParamValues[] = new String[paramList
                                    .size()];
                                queryParams.put(paramName, paramList
                                    .toArray(newParamValues));
                            }
                        } else {
                            queryParams.put(paramName, translatedParamValue);
                        }
                    }
                }
            }
        }
        return queryParams;
    
public static voidsetCustomEncoding(java.lang.String val)

        customEncoding = val;
    
public static voidsetHttpPort(java.lang.String val)


    
         
        httpPort = Integer.parseInt(val);
    
public static voidsetHttpsPort(java.lang.String val)

        httpsPort = Integer.parseInt(val);
    
public static java.lang.StringtranslateAndDecode(java.lang.String input)

        String translatedInput = translateVariable(input);
        String encoding = getEncodingFromConfiguration();

        try {
            return URLDecoder.decode(translatedInput, encoding);
        } catch (UnsupportedEncodingException e) {
            LOG.warn("Could not encode URL parameter '" + input + "', returning value un-encoded");
            return translatedInput;
        }
    
public static java.lang.StringtranslateAndEncode(java.lang.String input)
Translates any script expressions using {@link com.opensymphony.xwork2.util.TextParseUtil#translateVariables} and encodes the URL using {@link java.net.URLEncoder#encode} with the encoding specified in the configuration.

param
input
return
the translated and encoded string

        String translatedInput = translateVariable(input);
        String encoding = getEncodingFromConfiguration();

        try {
            return URLEncoder.encode(translatedInput, encoding);
        } catch (UnsupportedEncodingException e) {
            LOG.warn("Could not encode URL parameter '" + input + "', returning value un-encoded");
            return translatedInput;
        }
    
private static java.lang.StringtranslateVariable(java.lang.String input)

        ValueStack valueStack = ServletActionContext.getContext().getValueStack();
        String output = TextParseUtil.translateVariables(input, valueStack);
        return output;