001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.util.test;
016    
017    import com.liferay.portal.kernel.exception.PortalException;
018    import com.liferay.portal.kernel.test.util.RandomTestUtil;
019    import com.liferay.portal.kernel.test.util.TestPropsValues;
020    import com.liferay.portal.kernel.upload.FileItem;
021    import com.liferay.portal.kernel.util.FileUtil;
022    import com.liferay.portal.kernel.util.ProgressTracker;
023    import com.liferay.portal.kernel.util.StringUtil;
024    import com.liferay.portal.kernel.util.WebKeys;
025    import com.liferay.portal.model.Company;
026    import com.liferay.portal.model.Group;
027    import com.liferay.portal.model.Layout;
028    import com.liferay.portal.service.CompanyLocalServiceUtil;
029    import com.liferay.portal.theme.ThemeDisplay;
030    import com.liferay.portal.theme.ThemeDisplayFactory;
031    import com.liferay.portal.upload.LiferayFileItem;
032    import com.liferay.portal.upload.LiferayFileItemFactory;
033    import com.liferay.portal.upload.LiferayServletRequest;
034    import com.liferay.portal.upload.UploadServletRequestImpl;
035    import com.liferay.portlet.PortletURLFactoryUtil;
036    
037    import java.io.IOException;
038    import java.io.InputStream;
039    import java.io.OutputStream;
040    
041    import java.net.HttpURLConnection;
042    import java.net.URL;
043    
044    import java.util.ArrayList;
045    import java.util.Collections;
046    import java.util.HashMap;
047    import java.util.List;
048    import java.util.Map;
049    
050    import javax.portlet.PortletRequest;
051    import javax.portlet.PortletURL;
052    
053    import javax.servlet.http.HttpServletRequest;
054    
055    import org.apache.commons.httpclient.Header;
056    import org.apache.commons.httpclient.HttpClient;
057    import org.apache.commons.httpclient.StatusLine;
058    import org.apache.commons.httpclient.methods.PostMethod;
059    import org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource;
060    import org.apache.commons.httpclient.methods.multipart.FilePart;
061    import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
062    import org.apache.commons.httpclient.methods.multipart.Part;
063    
064    import org.springframework.mock.web.MockHttpServletRequest;
065    import org.springframework.mock.web.MockHttpSession;
066    import org.springframework.mock.web.MockMultipartFile;
067    import org.springframework.mock.web.MockMultipartHttpServletRequest;
068    
069    /**
070     * @author Manuel de la Pe??a
071     */
072    public class PortletContainerTestUtil {
073    
074            public static Map<String, FileItem[]> getFileParameters(
075                            int size, byte[] bytes)
076                    throws Exception {
077    
078                    return getFileParameters(size, null, bytes);
079            }
080    
081            public static Map<String, FileItem[]> getFileParameters(
082                            int size, String namespace, byte[] bytes)
083                    throws Exception {
084    
085                    Map<String, FileItem[]> fileParameters = new HashMap<>();
086    
087                    LiferayFileItemFactory fileItemFactory = new LiferayFileItemFactory(
088                            UploadServletRequestImpl.getTempDir());
089    
090                    for (int i = 0; i < size; i++) {
091                            String fileParameter = "fileParameter" + i;
092    
093                            if (namespace != null) {
094                                    fileParameter = namespace.concat(fileParameter);
095                            }
096    
097                            LiferayFileItem[] liferayFileItems = new LiferayFileItem[2];
098    
099                            for (int j = 0; j < liferayFileItems.length; j++) {
100                                    liferayFileItems[j] = fileItemFactory.createItem(
101                                            RandomTestUtil.randomString(),
102                                            RandomTestUtil.randomString(), true,
103                                            RandomTestUtil.randomString());
104    
105                                    try (OutputStream outputStream =
106                                                    liferayFileItems[j].getOutputStream()) {
107    
108                                            outputStream.write(bytes);
109                                    }
110                            }
111    
112                            fileParameters.put(fileParameter, liferayFileItems);
113                    }
114    
115                    return fileParameters;
116            }
117    
118            public static HttpServletRequest getHttpServletRequest(
119                            Group group, Layout layout)
120                    throws PortalException {
121    
122                    HttpServletRequest httpServletRequest = new MockHttpServletRequest();
123    
124                    httpServletRequest.setAttribute(WebKeys.LAYOUT, layout);
125    
126                    ThemeDisplay themeDisplay = ThemeDisplayFactory.create();
127    
128                    Company company = CompanyLocalServiceUtil.getCompany(
129                            layout.getCompanyId());
130    
131                    themeDisplay.setCompany(company);
132    
133                    themeDisplay.setLayout(layout);
134                    themeDisplay.setPlid(layout.getPlid());
135                    themeDisplay.setPortalURL(TestPropsValues.PORTAL_URL);
136                    themeDisplay.setRequest(httpServletRequest);
137                    themeDisplay.setScopeGroupId(group.getGroupId());
138                    themeDisplay.setSiteGroupId(group.getGroupId());
139                    themeDisplay.setUser(TestPropsValues.getUser());
140    
141                    httpServletRequest.setAttribute(WebKeys.THEME_DISPLAY, themeDisplay);
142    
143                    return httpServletRequest;
144            }
145    
146            public static LiferayServletRequest getMultipartRequest(
147                    String fileNameParameter, byte[] bytes) {
148    
149                    MockMultipartHttpServletRequest mockMultipartHttpServletRequest =
150                            new MockMultipartHttpServletRequest();
151    
152                    mockMultipartHttpServletRequest.addFile(
153                            new MockMultipartFile(fileNameParameter, bytes));
154                    mockMultipartHttpServletRequest.setContent(bytes);
155                    mockMultipartHttpServletRequest.setContentType(
156                            "multipart/form-data;boundary=" + System.currentTimeMillis());
157                    mockMultipartHttpServletRequest.setCharacterEncoding("UTF-8");
158    
159                    MockHttpSession mockHttpSession = new MockHttpSession();
160    
161                    mockHttpSession.setAttribute(ProgressTracker.PERCENT, new Object());
162    
163                    mockMultipartHttpServletRequest.setSession(mockHttpSession);
164    
165                    return new LiferayServletRequest(mockMultipartHttpServletRequest);
166            }
167    
168            public static Response getPortalAuthentication(
169                            HttpServletRequest httpServletRequest, Layout layout,
170                            String portletId)
171                    throws Exception {
172    
173                    // Get the portal authentication token by making a resource request
174    
175                    PortletURL portletURL = PortletURLFactoryUtil.create(
176                            httpServletRequest, portletId, layout.getPlid(),
177                            PortletRequest.RESOURCE_PHASE);
178    
179                    return request(portletURL.toString());
180            }
181    
182            public static Map<String, List<String>> getRegularParameters(int size) {
183                    Map<String, List<String>> regularParameters = new HashMap<>();
184    
185                    for (int i = 0; i < size; i++) {
186                            List<String> items = new ArrayList<>();
187    
188                            for (int j = 0; j < 10; j++) {
189                                    items.add(RandomTestUtil.randomString());
190                            }
191    
192                            regularParameters.put("regularParameter" + i, items);
193                    }
194    
195                    return regularParameters;
196            }
197    
198            public static Response postMultipart(
199                            String url,
200                            MockMultipartHttpServletRequest mockMultipartHttpServletRequest,
201                            String fileNameParameter)
202                    throws IOException {
203    
204                    if (mockMultipartHttpServletRequest.getInputStream() == null) {
205                            throw new IllegalStateException("Input stream is null");
206                    }
207    
208                    String[] cookies = mockMultipartHttpServletRequest.getParameterValues(
209                            "Cookie");
210    
211                    if ((cookies == null) || (cookies.length == 0)) {
212                            throw new IllegalStateException("Cookie is null");
213                    }
214    
215                    HttpClient httpClient = new HttpClient();
216    
217                    PostMethod postMethod = new PostMethod(url);
218    
219                    for (String cookie : cookies) {
220                            postMethod.addRequestHeader(new Header("Cookie", cookie));
221                    }
222    
223                    byte[] bytes = FileUtil.getBytes(
224                            mockMultipartHttpServletRequest.getInputStream());
225    
226                    Part[] parts = {
227                            new FilePart(
228                                    fileNameParameter,
229                                    new ByteArrayPartSource(fileNameParameter, bytes))
230                    };
231    
232                    MultipartRequestEntity multipartRequestEntity =
233                            new MultipartRequestEntity(parts, postMethod.getParams());
234    
235                    postMethod.setRequestEntity(multipartRequestEntity);
236    
237                    httpClient.executeMethod(postMethod);
238    
239                    StatusLine statusLine = postMethod.getStatusLine();
240    
241                    return new Response(
242                            statusLine.getStatusCode(), postMethod.getResponseBodyAsString(),
243                            null);
244            }
245    
246            public static Response request(String url) throws IOException {
247                    return request(url, Collections.<String, List<String>>emptyMap());
248            }
249    
250            public static Response request(
251                            String url, Map<String, List<String>> headers)
252                    throws IOException {
253    
254                    URL urlObject = new URL(url);
255    
256                    HttpURLConnection httpURLConnection =
257                            (HttpURLConnection)urlObject.openConnection();
258    
259                    httpURLConnection.setConnectTimeout(1500 * 1000);
260                    httpURLConnection.setInstanceFollowRedirects(true);
261                    httpURLConnection.setReadTimeout(1500 * 1000);
262    
263                    for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
264                            String key = entry.getKey();
265    
266                            for (String value : entry.getValue()) {
267                                    if (key.equals("Cookie")) {
268                                            httpURLConnection.addRequestProperty(
269                                                    key, value.split(";", 2)[0]);
270                                    }
271                                    else {
272                                            httpURLConnection.setRequestProperty(key, value);
273                                    }
274                            }
275                    }
276    
277                    try (InputStream inputStream = httpURLConnection.getInputStream()) {
278                            Map<String, List<String>> headerFields =
279                                    httpURLConnection.getHeaderFields();
280    
281                            return new Response(
282                                    httpURLConnection.getResponseCode(),
283                                    StringUtil.read(inputStream), headerFields.get("Set-Cookie"));
284                    }
285                    catch (IOException ioe) {
286                            try (InputStream inputStream = httpURLConnection.getErrorStream()) {
287                                    if (inputStream != null) {
288                                            while (inputStream.read() != -1);
289                                    }
290                            }
291    
292                            return new Response(
293                                    httpURLConnection.getResponseCode(), null, null);
294                    }
295                    finally {
296                            httpURLConnection.disconnect();
297                    }
298            }
299    
300            public static class Response {
301    
302                    public String getBody() {
303                            return _body;
304                    }
305    
306                    public int getCode() {
307                            return _code;
308                    }
309    
310                    public List<String> getCookies() {
311                            return _cookies;
312                    }
313    
314                    private Response(int code, String body, List<String> cookies) {
315                            _code = code;
316                            _body = body;
317                            _cookies = cookies;
318                    }
319    
320                    private final String _body;
321                    private final int _code;
322                    private final List<String> _cookies;
323    
324            }
325    
326    }