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