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