com.github.tomakehurst.wiremock.servlet.HttpServletRequestAdapter.java Source code

Java tutorial

Introduction

Here is the source code for com.github.tomakehurst.wiremock.servlet.HttpServletRequestAdapter.java

Source

/*
 * Copyright (C) 2011 Thomas Akehurst
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.tomakehurst.wiremock.servlet;

import com.github.tomakehurst.wiremock.http.*;
import com.github.tomakehurst.wiremock.jetty.ServletContainerUtils;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.io.ByteStreams.toByteArray;

import java.io.File;
import java.io.IOException;
import static java.util.Collections.list;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class HttpServletRequestAdapter implements Request {

    private final HttpServletRequest request;
    private String cachedBody;
    private Map<String, Request.BodyPart> cachedMultipart;

    public HttpServletRequestAdapter(HttpServletRequest request) {
        this.request = request;
    }

    @Override
    public String getUrl() {
        String url = request.getRequestURI();

        if (!isNullOrEmpty(request.getContextPath())) {
            url = url.replace(request.getContextPath(), "");
        }

        return withQueryStringIfPresent(url);
    }

    @Override
    public String getAbsoluteUrl() {
        return withQueryStringIfPresent(request.getRequestURL().toString());
    }

    private String withQueryStringIfPresent(String url) {
        return url + (isNullOrEmpty(request.getQueryString()) ? "" : "?" + request.getQueryString());
    }

    @Override
    public RequestMethod getMethod() {
        return RequestMethod.valueOf(request.getMethod().toUpperCase());
    }

    @Override
    public String getBodyAsString() {
        if (cachedBody == null) {
            try {
                cachedBody = new String(toByteArray(request.getInputStream()), UTF_8);
            } catch (IOException ioe) {
                throw new RuntimeException(ioe);
            }
        }

        return cachedBody;
    }

    @SuppressWarnings("unchecked")
    @Override
    public String getHeader(String key) {
        List<String> headerNames = list(request.getHeaderNames());
        for (String currentKey : headerNames) {
            if (currentKey.toLowerCase().equals(key.toLowerCase())) {
                return request.getHeader(currentKey);
            }
        }

        return null;
    }

    @Override
    @SuppressWarnings("unchecked")
    public HttpHeader header(String key) {
        List<String> headerNames = list(request.getHeaderNames());
        for (String currentKey : headerNames) {
            if (currentKey.toLowerCase().equals(key.toLowerCase())) {
                List<String> valueList = list(request.getHeaders(currentKey));
                return new HttpHeader(key, valueList);
            }
        }

        return HttpHeader.absent(key);
    }

    @Override
    public ContentTypeHeader contentTypeHeader() {
        return getHeaders().getContentTypeHeader();
    }

    @Override
    public boolean containsHeader(String key) {
        return header(key).isPresent();
    }

    @Override
    public HttpHeaders getHeaders() {
        List<HttpHeader> headerList = newArrayList();
        for (String key : getAllHeaderKeys()) {
            headerList.add(header(key));
        }

        return new HttpHeaders(headerList);
    }

    @SuppressWarnings("unchecked")
    @Override
    public Set<String> getAllHeaderKeys() {
        LinkedHashSet<String> headerKeys = new LinkedHashSet<String>();
        for (Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements();) {
            headerKeys.add(headerNames.nextElement());
        }

        return headerKeys;
    }

    @Override
    public boolean isBrowserProxyRequest() {
        return ServletContainerUtils.isBrowserProxyRequest(request);
    }

    @Override
    public boolean isMultipartRequest() {
        return ServletFileUpload.isMultipartContent(request);
    }

    @Override
    public boolean containsPart(String key) {
        if (!isMultipartRequest())
            return false;
        return getMultipart().containsKey(key);
    }

    @Override
    public String getPartAsString(String key) {
        if (!isMultipartRequest())
            return null;
        return getMultipart().get(key).getBodyAsString();
    }

    @Override
    public Request.BodyPart getPart(String key) {
        if (!isMultipartRequest())
            return null;
        return getMultipart().get(key);
    }

    public Map<String, Request.BodyPart> getMultipart() {
        if (!isMultipartRequest())
            return null;
        if (cachedMultipart == null) {
            DiskFileItemFactory factory = new DiskFileItemFactory();

            File repository = new File(System.getProperty("java.io.tmpdir"));
            factory.setRepository(repository);

            FileUpload fileUpload = new ServletFileUpload(factory);

            List<FileItem> items;
            try {
                items = fileUpload.parseRequest(request);
            } catch (FileUploadException ex) {
                throw new RuntimeException(ex);
            }

            cachedMultipart = new HashMap<String, Request.BodyPart>(items.size());
            for (FileItem item : items) {
                cachedMultipart.put(item.getFieldName(), new HttpServletRequestBodyPart(item));
            }
        }

        return cachedMultipart;
    }

    private static class HttpServletRequestBodyPart implements Request.BodyPart {

        private FileItem fileItem;

        private HttpServletRequestBodyPart(FileItem item) {
            fileItem = item;
        }

        @Override
        public String getFieldName() {
            return fileItem.getFieldName();
        }

        @Override
        public String getName() {
            return fileItem.getName();
        }

        @Override
        public ContentTypeHeader contentTypeHeader() {
            return new ContentTypeHeader(fileItem.getContentType());
        }

        @Override
        public byte[] getBody() {
            return fileItem.get();
        }

        @Override
        public String getBodyAsString() {
            return fileItem.getString();
        }

        @Override
        public String toString() {
            return "HttpServletRequestBodyPart{" + "fileItem=" + fileItem + '}';
        }

    }
}