1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * The contents of this file are subject to the terms of the Liferay Enterprise
5    * Subscription License ("License"). You may not use this file except in
6    * compliance with the License. You can obtain a copy of the License by
7    * contacting Liferay, Inc. See the License for the specific language governing
8    * permissions and limitations under the License, including but not limited to
9    * distribution rights of the Software.
10   *
11   *
12   *
13   */
14  
15  package com.liferay.portal.spring.remoting;
16  
17  import com.liferay.portal.PwdEncryptorException;
18  import com.liferay.portal.kernel.util.GetterUtil;
19  import com.liferay.portal.kernel.util.StringPool;
20  import com.liferay.portal.security.pwd.PwdEncryptor;
21  
22  import java.io.IOException;
23  
24  import java.net.HttpURLConnection;
25  
26  import org.apache.commons.codec.binary.Base64;
27  
28  import org.springframework.remoting.httpinvoker.SimpleHttpInvokerRequestExecutor;
29  
30  /**
31   * <a href="AuthenticatingHttpInvokerRequestExecutor.java.html"><b><i>View
32   * Source</i></b></a>
33   *
34   * <p>
35   * An HttpInvoker request executor for Spring Remoting that provides HTTP BASIC
36   * authentication information for service invocations.
37   * </p>
38   *
39   * @author Joel Kozikowski
40   */
41  public class AuthenticatingHttpInvokerRequestExecutor
42      extends SimpleHttpInvokerRequestExecutor {
43  
44      public AuthenticatingHttpInvokerRequestExecutor() {
45          super();
46      }
47  
48      public long getUserId() {
49          return _userId;
50      }
51  
52      public void setUserId(long userId) {
53          _userId = userId;
54      }
55  
56      public String getPassword() {
57          return _password;
58      }
59  
60      public void setPassword(String password) throws PwdEncryptorException {
61          _password = PwdEncryptor.encrypt(password);
62      }
63  
64      /**
65       * Called every time a HTTP invocation is made. This implementation allows
66       * the parent to setup the connection, and then adds an
67       * <code>Authorization</code> HTTP header property for BASIC authentication.
68       */
69      protected void prepareConnection(HttpURLConnection con, int contentLength)
70          throws IOException {
71  
72          super.prepareConnection(con, contentLength);
73  
74          if (getUserId() > 0) {
75              String password = GetterUtil.getString(getPassword());
76  
77              String base64 = getUserId() + StringPool.COLON + password;
78  
79              con.setRequestProperty(
80                  "Authorization",
81                  "Basic " + new String(Base64.encodeBase64(base64.getBytes())));
82          }
83      }
84  
85      private long _userId;
86      private String _password;
87  
88  }