Example usage for javax.servlet.http HttpUtils parseQueryString

List of usage examples for javax.servlet.http HttpUtils parseQueryString

Introduction

In this page you can find the example usage for javax.servlet.http HttpUtils parseQueryString.

Prototype

public static Hashtable<String, String[]> parseQueryString(String s) 

Source Link

Document

Parses a query string passed from the client to the server and builds a HashTable object with key-value pairs.

Usage

From source file:com.trsst.server.TrsstAdapter.java

@SuppressWarnings({ "rawtypes" })
protected void fetchEntriesFromStorage(RequestContext context, Feed feed)
        throws FileNotFoundException, IOException {
    // NOTE: occasionally (<1%) jetty and/or abdera give us a servlet
    // request that has a valid query string but returns no parameters;
    // we now just parse the query manually every time just to be safe
    Hashtable params = new Hashtable();
    String uri = context.getUri().toString();
    int i = uri.indexOf('?');
    if (i != -1) {
        params = HttpUtils.parseQueryString(uri.substring(i + 1));
    }//from w w  w .jav  a 2  s . c  om
    // System.out.println("fetchEntriesFromStorage: " + params + " : " +
    // uri);

    String searchTerms = params.get("q") == null ? null : ((String[]) params.get("q"))[0];
    Date beginDate = null;

    String verb = params.get("verb") == null ? null : ((String[]) params.get("verb"))[0];

    String[] mentions = (String[]) params.get("mention");
    String[] tags = (String[]) params.get("tag");
    String after = params.get("after") == null ? null : ((String[]) params.get("after"))[0];
    if (after != null) {
        try {
            // try to parse an entry id timestamp
            beginDate = new Date(Long.parseLong(after, 16));
        } catch (NumberFormatException nfe) {
            // try to parse as ISO date
            String begin = after;
            String beginTemplate = "0000-01-01T00:00:00.000Z";
            if (begin.length() < beginTemplate.length()) {
                begin = begin + beginTemplate.substring(begin.length());
            }
            try {
                beginDate = new AtomDate(begin).getDate();
            } catch (IllegalArgumentException e) {
                throw new IllegalArgumentException("Could not parse begin date: " + begin);
            }
        }

    }
    Date endDate = null;
    String before = params.get("before") == null ? null : ((String[]) params.get("before"))[0];
    if (before != null) {
        try {
            // try to parse an entry id timestamp
            endDate = new Date(Long.parseLong(before, 16));
        } catch (NumberFormatException nfe) {
            // try to parse as ISO date
            String end = before;
            String endTemplate = "9999-12-31T23:59:59.999Z";
            if (end.length() < endTemplate.length()) {
                end = end + endTemplate.substring(end.length());
            }
            try {
                endDate = new AtomDate(end).getDate();
            } catch (IllegalArgumentException e) {
                throw new IllegalArgumentException("Could not parse end date: " + end);
            }
        }
    }

    // note: "default" to getPageSize was actually max page size
    int length = ProviderHelper.getPageSize(context, "count", 99);
    String _count = params.get("count") == null ? null : ((String[]) params.get("count"))[0];
    if (_count != null) {
        try {
            int newLength = Integer.parseInt(_count);
            if (length != newLength) {
                // BUG in abdera?
                log.error("Abdera returning no count from valid count parameter: " + context.getUri());
            }
            length = newLength;
        } catch (NumberFormatException exc) {
            log.trace("Unrecognized count parameter: " + _count);
        }
    }
    // int offset = ProviderHelper.getOffset(context, "page", length);
    String _page = params.get("page") == null ? null : ((String[]) params.get("page"))[0];
    int page = (_page != null) ? Integer.parseInt(_page) : 0;
    int begin = page * length;
    int total = 0;
    if (length > 0) {
        total = addEntriesFromStorage(feed, begin, length, beginDate, endDate, searchTerms, mentions, tags,
                verb);
    } else {
        total = countEntriesFromStorage(beginDate, endDate, searchTerms, mentions, tags, verb);
    }

    if (feed.getEntries().size() > length) {
        log.error("Returned count exceeded limit: " + feed.getEntries().size() + " : " + length + " : "
                + context.getUri());
    }

    addPagingLinks(context, feed, page, length, total, searchTerms, before, after, mentions, tags, verb);

    // ARGH:
    // because having links appear after entries is invalid
    // we have to remove and then reinsert each entry.
    // would have expected Feed.addLink to insert before entries.
    List<Entry> entries = feed.getEntries();
    for (Entry entry : entries) {
        entry.discard();
    }
    for (Entry entry : entries) {
        feed.addEntry(entry);
    }
}

From source file:org.rhq.enterprise.gui.legacy.taglib.display.TableTag.java

private String removePageControlParams(String url) {
    int index = url.indexOf('?');
    if (index != -1) {
        String base = url.substring(0, index);
        StringBuilder buf = new StringBuilder(base);
        String queryString = url.substring(index + 1);
        Map<String, Object> params = HttpUtils.parseQueryString(queryString);
        params.remove(ParamConstants.SORTCOL_PARAM);
        params.remove(ParamConstants.SORTORDER_PARAM);
        params.remove(ParamConstants.PAGESIZE_PARAM);
        params.remove(ParamConstants.PAGENUM_PARAM);
        if (!params.isEmpty()) {
            buf.append('?').append(convertMapToQueryString(params));
        }/*  w  w  w .  jav  a2  s.c o m*/

        url = buf.toString();
    }

    return url;
}

From source file:org.sakaiproject.metaobj.shared.control.servlet.FileDownloadServlet.java

/**
 * Called by the server (via the <code>service</code> method) to
 * allow a servlet to handle a GET request.
 * <p/>/*w  ww  .  j  a v  a2s  . c  o m*/
 * <p>Overriding this method to support a GET request also
 * automatically supports an HTTP HEAD request. A HEAD
 * request is a GET request that returns no body in the
 * response, only the request header fields.
 * <p/>
 * <p>When overriding this method, read the request data,
 * write the response headers, get the response's writer or
 * output stream object, and finally, write the response data.
 * It's best to include content type and encoding. When using
 * a <code>PrintWriter</code> object to return the response,
 * set the content type before accessing the
 * <code>PrintWriter</code> object.
 * <p/>
 * <p>The servlet container must write the headers before
 * committing the response, because in HTTP the headers must be sent
 * before the response body.
 * <p/>
 * <p>Where possible, set the Content-Length header (with the
 * {@link javax.servlet.ServletResponse#setContentLength} method),
 * to allow the servlet container to use a persistent connection
 * to return its response to the client, improving performance.
 * The content length is automatically set if the entire response fits
 * inside the response buffer.
 * <p/>
 * <p>When using HTTP 1.1 chunked encoding (which means that the response
 * has a Transfer-Encoding header), do not set the Content-Length header.
 * <p/>
 * <p>The GET method should be safe, that is, without
 * any side effects for which users are held responsible.
 * For example, most form queries have no side effects.
 * If a client request is intended to change stored data,
 * the request should use some other HTTP method.
 * <p/>
 * <p>The GET method should also be idempotent, meaning
 * that it can be safely repeated. Sometimes making a
 * method safe also makes it idempotent. For example,
 * repeating queries is both safe and idempotent, but
 * buying a product online or modifying data is neither
 * safe nor idempotent.
 * <p/>
 * <p>If the request is incorrectly formatted, <code>doGet</code>
 * returns an HTTP "Bad Request" message.
 *
 * @param request  an {@link javax.servlet.http.HttpServletRequest} object that
 *                 contains the request the client has made
 *                 of the servlet
 * @param response an {@link javax.servlet.http.HttpServletResponse} object that
 *                 contains the response the servlet sends
 *                 to the client
 * @throws java.io.IOException            if an input or output error is
 *                                        detected when the servlet handles
 *                                        the GET request
 * @throws javax.servlet.ServletException if the request for the GET
 *                                        could not be handled
 * @see javax.servlet.ServletResponse#setContentType
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    java.util.Enumeration tokenizer = new StringTokenizer(request.getRequestURI(), "/");

    if (!tokenizer.hasMoreElements()) {
        throw new ServletException("Incorrect format url.");
    }
    String base = (String) tokenizer.nextElement(); // burn off the first element of the path

    while (!base.equalsIgnoreCase(REPOSITORY_PREFIX)) {
        if (!tokenizer.hasMoreElements()) {
            throw new ServletException("Incorrect format url.");
        }
        base = (String) tokenizer.nextElement();
    }

    Hashtable params = HttpUtils.parseQueryString(getNextToken(tokenizer));

    DownloadableManager manager = getDownloadableManager(((String[]) params.get(MANAGER_NAME))[0]);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    String filename = manager.packageForDownload(params, bos);

    response.setHeader("Content-Type", "application/octet-stream");
    response.setHeader("Content-Disposition", "attachment"
            + ((filename != null && !filename.equals("")) ? ";filename=\"" + filename + "\"" : ""));
    response.setHeader("Content-Length", Integer.toString(bos.size()));

    copyStream(new ByteArrayInputStream(bos.toByteArray()), response.getOutputStream());

}