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