RequestWrapper.java :  » REST » alc-rest » org » allcolor » services » servlet » Java Open Source

Java Open Source » REST » alc rest 
alc rest » org » allcolor » services » servlet » RequestWrapper.java
package org.allcolor.services.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.fileupload.FileItem;

public final class RequestWrapper extends HttpServletRequestWrapper {

  private static final ThreadLocal<Reference<List<FileItem>>> localFiles = new ThreadLocal<Reference<List<FileItem>>>();

  public static List<FileItem> getFiles() {
    final Reference<List<FileItem>> ref = RequestWrapper.localFiles.get();
    if (ref == null) {
      return new ArrayList<FileItem>(0);
    }
    final List<FileItem> files = ref.get();
    if (files == null) {
      return new ArrayList<FileItem>(0);
    }
    return files;
  }

  public static void resetFiles() {
    RequestWrapper.localFiles.set(null);
  }

  private final List<FileItem> files = new ArrayList<FileItem>(0);
  private final Map<String, String[]> parameters = new TreeMap<String, String[]>();

  private String queryString = null;

  public RequestWrapper(final HttpServletRequest request,
      final List<FileItem> multipartParameters) {
    super(request);
    try {
      request.setCharacterEncoding("utf-8");
    } catch (final Exception ignore) {
    }
    @SuppressWarnings("unchecked")
    final Map<String, String[]> parameters = super.getParameterMap();
    for (final Map.Entry<String, String[]> entry : parameters.entrySet()) {
      this.parameters.put(entry.getKey(), entry.getValue());
    }
    for (final FileItem item : multipartParameters) {
      if (item.isFormField()) {
        final String[] array = this.parameters.get(item.getFieldName());
        if (array == null) {
          try {
            this.parameters.put(item.getFieldName(),
                new String[] { item.getString("utf-8") });
          } catch (final UnsupportedEncodingException ignore) {
          }
        } else {
          final List<String> larray = new ArrayList<String>(Arrays
              .asList(array));
          try {
            larray.add(item.getString("utf-8"));
          } catch (final UnsupportedEncodingException ignore) {
          }
          this.parameters.put(item.getFieldName(), larray
              .toArray(new String[larray.size()]));
        }
      } else {
        this.files.add(item);
      }
    }
    RequestWrapper.localFiles.set(new WeakReference<List<FileItem>>(
        this.files));
  }

  @Override
  public ServletInputStream getInputStream() throws IOException {
    return new ServletInputStream() {
      @Override
      public int read() throws IOException {
        return -1;
      }
    };
  }

  @Override
  public String getParameter(final String name) {
    final String[] values = this.parameters.get(name);
    return (values != null) && (values.length > 0) ? values[0] : null;
  }

  @Override
  @SuppressWarnings("unchecked")
  public Map getParameterMap() {
    return Collections.unmodifiableMap(this.parameters);
  }

  @Override
  @SuppressWarnings("unchecked")
  public Enumeration getParameterNames() {
    return new Enumeration<String>() {
      Iterator<String> iter = RequestWrapper.this.parameters.keySet()
          .iterator();

      public boolean hasMoreElements() {
        return this.iter.hasNext();
      }

      public String nextElement() {
        return this.iter.next();
      }
    };
  }

  @Override
  public String[] getParameterValues(final String name) {
    return this.parameters.get(name);
  }

  @Override
  public String getQueryString() {
    if (this.queryString == null) {
      try {
        final StringBuilder queryStringBuilder = new StringBuilder();
        for (final Map.Entry<String, String[]> entry : this.parameters
            .entrySet()) {
          for (final String value : entry.getValue()) {
            queryStringBuilder.append(URLEncoder.encode(entry
                .getKey(), "utf-8"));
            queryStringBuilder.append("=");
            queryStringBuilder.append(URLEncoder.encode(value,
                "utf-8"));
            queryStringBuilder.append("&");
          }
        }
        this.queryString = queryStringBuilder.toString();
        if (this.queryString.endsWith("&")) {
          this.queryString = this.queryString.substring(0,
              this.queryString.length() - 1);
        }
      } catch (final Exception e) {
        this.queryString = "";
      }
    }
    return this.queryString;
  }

  @Override
  public BufferedReader getReader() throws IOException {
    return new BufferedReader(new Reader() {
      @Override
      public void close() throws IOException {
      }

      @Override
      public int read(final char[] cbuf, final int off, final int len)
          throws IOException {
        return -1;
      }
    });
  }

}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.