001/* 002 * The contents of this file are subject to the license and copyright 003 * detailed in the LICENSE and NOTICE files at the root of the source 004 * tree. 005 */ 006package org.fcrepo.client; 007 008import static org.slf4j.LoggerFactory.getLogger; 009import static org.fcrepo.client.FedoraHeaderConstants.LINK; 010 011import java.net.URI; 012 013import org.apache.http.client.methods.HttpRequestBase; 014import org.apache.http.util.Args; 015import org.slf4j.Logger; 016 017/** 018 * Base RequestBuilder class for constructing requests to the Fedora API 019 * 020 * @author bbpennel 021 */ 022public abstract class RequestBuilder { 023 024 private static final Logger LOGGER = getLogger(RequestBuilder.class); 025 026 // Fedora client which will make this request 027 protected FcrepoClient client; 028 029 // URL this request will be executed against 030 protected URI targetUri; 031 032 // The request being built 033 protected HttpRequestBase request; 034 035 /** 036 * Instantiate builder. Throws an IllegalArgumentException if either the uri or client are null. 037 * 038 * @param uri uri of the resource this request is being made to 039 * @param client the client 040 */ 041 protected RequestBuilder(final URI uri, final FcrepoClient client) { 042 Args.notNull(uri, "uri"); 043 Args.notNull(client, "client"); 044 045 this.targetUri = uri; 046 this.client = client; 047 this.request = createRequest(); 048 } 049 050 /** 051 * Creates the HTTP request object for this builder 052 * 053 * @return HTTP request object for this builder 054 */ 055 protected abstract HttpRequestBase createRequest(); 056 057 /** 058 * Performs the request constructed in this builder and returns the response 059 * 060 * @return the repository response 061 * @throws FcrepoOperationFailedException when the underlying HTTP request results in an error 062 */ 063 public FcrepoResponse perform() throws FcrepoOperationFailedException { 064 LOGGER.debug("Fcrepo {} request to {} with headers: {}", request.getMethod(), targetUri, 065 request.getAllHeaders()); 066 067 return client.executeRequest(targetUri, request); 068 } 069 070 /** 071 * Add a header with the given name and value to the request. 072 * 073 * @param name name of the header 074 * @param value value of the header 075 * @return this builder 076 */ 077 protected RequestBuilder addHeader(final String name, final String value) { 078 request.addHeader(name, value); 079 return this; 080 } 081 082 /** 083 * Add a link header to the request 084 * 085 * @param linkHeader link header value represented as a FcrepoLink 086 * @return this builder 087 */ 088 protected RequestBuilder addLinkHeader(final FcrepoLink linkHeader) { 089 request.addHeader(LINK, linkHeader.toString()); 090 return this; 091 } 092}