1
22
23 package com.liferay.portal.service.http;
24
25 import java.io.EOFException;
26 import java.io.IOException;
27 import java.io.ObjectInputStream;
28 import java.io.ObjectOutputStream;
29 import java.net.HttpURLConnection;
30 import java.net.URL;
31
32 import javax.servlet.http.HttpServletRequest;
33
34 import com.liferay.portal.kernel.servlet.HttpHeaders;
35 import com.liferay.portal.kernel.util.Base64;
36 import com.liferay.portal.kernel.util.MethodWrapper;
37 import com.liferay.portal.kernel.util.ObjectValuePair;
38 import com.liferay.portal.kernel.util.StringPool;
39 import com.liferay.portal.security.auth.HttpPrincipal;
40 import com.liferay.portal.security.auth.PrincipalException;
41
42
48 public class TunnelUtil {
49
50 public static Object invoke(
51 HttpPrincipal httpPrincipal, MethodWrapper methodWrapper)
52 throws Exception {
53
54 HttpURLConnection urlc = _getConnection(httpPrincipal);
55
56 ObjectOutputStream oos = new ObjectOutputStream(urlc.getOutputStream());
57
58 oos.writeObject(
59 new ObjectValuePair<HttpPrincipal, MethodWrapper>(
60 httpPrincipal, methodWrapper));
61
62 oos.flush();
63 oos.close();
64
65 Object returnObj = null;
66
67 try {
68 ObjectInputStream ois =
69 new ObjectInputStream(urlc.getInputStream());
70
71 returnObj = ois.readObject();
72
73 ois.close();
74 }
75 catch (EOFException eofe) {
76 }
77 catch (IOException ioe) {
78 String ioeMessage = ioe.getMessage();
79
80 if ((ioeMessage != null) &&
81 (ioeMessage.indexOf("HTTP response code: 401") != -1)) {
82
83 throw new PrincipalException(ioeMessage);
84 }
85 else {
86 throw ioe;
87 }
88 }
89
90 if ((returnObj != null) && returnObj instanceof Exception) {
91 throw (Exception)returnObj;
92 }
93
94 return returnObj;
95 }
96
97 private static HttpURLConnection _getConnection(HttpPrincipal httpPrincipal)
98 throws IOException {
99
100 if (httpPrincipal == null || httpPrincipal.getUrl() == null) {
101 return null;
102 }
103
104 URL url = null;
105
106 if ((httpPrincipal.getUserId() <= 0) ||
107 (httpPrincipal.getPassword() == null)) {
108
109 url = new URL(httpPrincipal.getUrl() + "/tunnel-web/liferay/do");
110 }
111 else {
112 url = new URL(
113 httpPrincipal.getUrl() + "/tunnel-web/secure/liferay/do");
114 }
115
116 HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
117
118 urlc.setDoInput(true);
119 urlc.setDoOutput(true);
120 urlc.setUseCaches(false);
121
122 urlc.setRequestMethod("POST");
123
124 if ((httpPrincipal.getUserId() > 0) &&
125 (httpPrincipal.getPassword() != null)) {
126
127 String userNameAndPassword =
128 httpPrincipal.getUserId() + "@uid:" +
129 httpPrincipal.getPassword();
130
131 urlc.setRequestProperty(
132 HttpHeaders.AUTHORIZATION,
133 HttpServletRequest.BASIC_AUTH + StringPool.SPACE +
134 Base64.encode(userNameAndPassword.getBytes()));
135 }
136
137 return urlc;
138 }
139
140 }