001/** 002 * Copyright 2014 Tampere University of Technology, Pori Department 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 core.tut.pori.utils; 017 018import java.io.UnsupportedEncodingException; 019 020import org.apache.commons.codec.binary.Base64; 021import org.apache.commons.lang3.StringUtils; 022import org.apache.http.HttpMessage; 023import org.apache.log4j.Logger; 024 025import core.tut.pori.http.Definitions; 026 027/** 028 * common HTTP parameter utility methods 029 * 030 */ 031public final class HTTPHeaderUtil { 032 private static final Logger LOGGER = Logger.getLogger(HTTPHeaderUtil.class); 033 034 /** 035 * 036 */ 037 private HTTPHeaderUtil(){ 038 // nothing needed 039 } 040 041 /** 042 * Create and set <a href="http://tools.ietf.org/html/rfc2617">HTTP Basic Authentication</a> header based on the given values. 043 * 044 * @param message the message object to set the header to 045 * @param username if null or empty, this method is a no-op 046 * @param password non-null and non-empty password 047 * @throws IllegalArgumentException on bad values 048 */ 049 public static void setHTTPBasicAuthHeader(HttpMessage message, String username, String password) throws IllegalArgumentException { 050 if(StringUtils.isBlank(username)){ 051 LOGGER.debug("Ignored empty username."); 052 return; 053 } 054 if(StringUtils.isBlank(password)){ // the RFC does not exactly mention whether the password can or cannot be an empty string, but for possible compatibility reason we'll reject all empty strings 055 throw new IllegalArgumentException("Invalid password : "+password); 056 } 057 try { 058 message.setHeader("Authorization", "Basic " + new Base64().encodeToString((username+":"+password).getBytes(Definitions.ENCODING_UTF8)).trim()); 059 } catch (UnsupportedEncodingException ex) { // should never happen 060 LOGGER.error(ex, ex); 061 throw new IllegalArgumentException("Failed to process the header using encoding "+Definitions.ENCODING_UTF8); 062 } 063 } 064}