001/** 002 * Copyright 2015 DuraSpace, Inc. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.fcrepo.client; 017 018import static org.apache.commons.lang3.StringUtils.isBlank; 019import static org.slf4j.LoggerFactory.getLogger; 020 021import org.apache.http.HttpHost; 022import org.apache.http.auth.AuthScope; 023import org.apache.http.auth.UsernamePasswordCredentials; 024import org.apache.http.client.CredentialsProvider; 025import org.apache.http.impl.client.BasicCredentialsProvider; 026import org.apache.http.impl.client.CloseableHttpClient; 027import org.apache.http.impl.client.HttpClients; 028import org.slf4j.Logger; 029 030/** 031 * A utility class for building an httpclient for interacting with a Fedora repository 032 * 033 * @author Aaron Coburn 034 * @since March 9, 2015 035 */ 036public class FcrepoHttpClientBuilder { 037 038 private String username; 039 040 private String password; 041 042 private String host; 043 044 private static final Logger LOGGER = getLogger(FcrepoHttpClientBuilder.class); 045 046 /** 047 * Create a FcrepoHttpClientBuilder object with which it is possible to create 048 * an HttpClient object 049 * 050 * @param username an optional username for authentication 051 * @param password an optional password for authentication 052 * @param host an optional realm for authentication 053 */ 054 public FcrepoHttpClientBuilder(final String username, final String password, final String host) { 055 this.username = username; 056 this.password = password; 057 this.host = host; 058 } 059 060 /** 061 * Build an HttpClient 062 * 063 * @return an HttpClient 064 */ 065 public CloseableHttpClient build() { 066 067 if (isBlank(username) || isBlank(password)) { 068 return HttpClients.createDefault(); 069 } else { 070 LOGGER.debug("Accessing fcrepo with user credentials"); 071 072 final CredentialsProvider credsProvider = new BasicCredentialsProvider(); 073 AuthScope scope = null; 074 075 if (isBlank(host)) { 076 scope = new AuthScope(AuthScope.ANY); 077 } else { 078 scope = new AuthScope(new HttpHost(host)); 079 } 080 credsProvider.setCredentials( 081 scope, 082 new UsernamePasswordCredentials(username, password)); 083 return HttpClients.custom() 084 .setDefaultCredentialsProvider(credsProvider) 085 .build(); 086 } 087 } 088}