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