org.getwheat.harvest.library.RequestProcessor.java Source code

Java tutorial

Introduction

Here is the source code for org.getwheat.harvest.library.RequestProcessor.java

Source

package org.getwheat.harvest.library;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.getwheat.harvest.library.model.ThrottleException;
import org.getwheat.harvest.library.model.UnexpectedHttpStatusException;
import org.getwheat.harvest.library.model.UserCredentials;
import org.getwheat.harvest.library.request.Request;
import org.xml.sax.SAXException;

/*
 * Copyright 2011 by Christopher Smith
 * 
 * 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.
 */

/**
 * RequestProcessor processes the various Request implementations.
 * 
 * @author Christopher Smith
 */
public class RequestProcessor {
    private static final String KEY_AUTHORIZATION = "Authorization";
    private static final String VALUE_BASIC = "Basic ";
    private static final String VALUE_RETRY_AFTER = "retry-after";
    private static final String VALUE_SCHEME = "https";
    private static final String VALUE_USER_AGENT = "GetWheat Java Library 2.0";
    private static final String VALUE_UTF8 = "UTF-8";
    private transient final RequestManager manager;

    /**
     * Default constructor.
     * 
     * @param manager the Request Manager
     */
    public RequestProcessor(final RequestManager manager) {
        this.manager = manager;
    }

    /**
     * Processes the Request.
     * 
     * @param request the Request
     * @param credentials the User Credentials for this Request
     * @throws ClientProtocolException
     * @throws IOException
     * @throws IllegalStateException
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws URISyntaxException
     * @throws ThrottleException if too many requests are made to the Harvest Timer API
     * @throws UnexpectedHttpStatusException if an expected HTTP Status Code is encountered
     */
    public void process(final Request<?> request, final UserCredentials credentials)
            throws ClientProtocolException, IOException, IllegalStateException, ParserConfigurationException,
            SAXException, URISyntaxException, ThrottleException, UnexpectedHttpStatusException {
        HttpEntity entity = null;
        try {
            request.clearResults();
            final HttpClient client = manager.getHttpClient();
            final HttpResponse response = client.execute(buildRequest(request, credentials));
            if (!request.getHttpMethod().isExpectedHttpStatus(response.getStatusLine().getStatusCode())) {
                validateHttpStatus(response.getStatusLine(), response.getHeaders(VALUE_RETRY_AFTER));
            }
            entity = response.getEntity();
            if (entity != null) {
                request.process(response, entity);
            }
        } finally {
            EntityUtils.consume(entity);
        }
    }

    private HttpUriRequest buildRequest(final Request<?> request, final UserCredentials credentials)
            throws URISyntaxException, UnsupportedEncodingException {
        final HttpUriRequest uriRequest = request.getHttpMethod().getRequest(
                URIUtils.createURI(VALUE_SCHEME, manager.getHostname(), -1, request.getResourcePath(),
                        URLEncodedUtils.format(request.getParameters(), VALUE_UTF8), null).toString(),
                request.getRequestContent());
        request.getTransformer().addContentTypeHeaders(uriRequest);
        addBasicAuthHeaders(uriRequest, credentials);
        return uriRequest;
    }

    private void addBasicAuthHeaders(final HttpUriRequest request, final UserCredentials credentials) {
        request.addHeader(KEY_AUTHORIZATION, VALUE_BASIC + credentials.getBase64Value());
        HttpProtocolParams.setUserAgent(request.getParams(), VALUE_USER_AGENT);
    }

    private void validateHttpStatus(final StatusLine status, final Header[] headers)
            throws UnexpectedHttpStatusException, ThrottleException {
        if (status.getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE) {
            int seconds = 5;
            if (headers.length > 0) {
                final Header header = headers[0];
                seconds = Integer.valueOf(header.getValue());
            }
            throw new ThrottleException(status.getStatusCode(), status.getReasonPhrase(), seconds);
        }
        throw new UnexpectedHttpStatusException(status.getStatusCode(), status.getReasonPhrase());
    }
}