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