List of usage examples for org.apache.commons.httpclient.params HttpMethodParams setCookiePolicy
public void setCookiePolicy(String paramString)
From source file:org.eclipse.smila.connectivity.framework.crawler.web.http.HttpResponse.java
/** * Sets the http parameters./*from w w w. ja v a2 s. c o m*/ * * @param http * the http * @param httpMethod * the http method */ private void setHttpParameters(HttpBase http, HttpMethodBase httpMethod) { httpMethod.setFollowRedirects(false); httpMethod.setRequestHeader("User-Agent", http.getUserAgent()); httpMethod.setRequestHeader("Referer", http.getReferer()); httpMethod.setDoAuthentication(true); for (Header header : http.getHeaders()) { httpMethod.addRequestHeader(header); } final HttpMethodParams params = httpMethod.getParams(); if (http.getUseHttp11()) { params.setVersion(HttpVersion.HTTP_1_1); } else { params.setVersion(HttpVersion.HTTP_1_0); } params.makeLenient(); params.setContentCharset("UTF-8"); if (http.isCookiesEnabled()) { params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); } else { params.setCookiePolicy(CookiePolicy.IGNORE_COOKIES); } params.setBooleanParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, true); // the default is to retry 3 times; if // the request body was sent the method is not retried, so there is // little danger in retrying // retries are handled on the higher level params.setParameter(HttpMethodParams.RETRY_HANDLER, null); }
From source file:org.ofbiz.passport.event.GitHubEvents.java
/** * Parse GitHub login response and login the user if possible. * /* w w w. java2 s . co m*/ * @return */ public static String parseGitHubResponse(HttpServletRequest request, HttpServletResponse response) { String authorizationCode = request.getParameter(PassportUtil.COMMON_CODE); String state = request.getParameter(PassportUtil.COMMON_STATE); if (!state.equals(request.getSession().getAttribute(SESSION_GITHUB_STATE))) { String errMsg = UtilProperties.getMessage(resource, "GitHubFailedToMatchState", UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } if (UtilValidate.isEmpty(authorizationCode)) { String error = request.getParameter(PassportUtil.COMMON_ERROR); String errorDescpriton = request.getParameter(PassportUtil.COMMON_ERROR_DESCRIPTION); String errMsg = null; try { errMsg = UtilProperties.getMessage(resource, "FailedToGetGitHubAuthorizationCode", UtilMisc.toMap(PassportUtil.COMMON_ERROR, error, PassportUtil.COMMON_ERROR_DESCRIPTION, URLDecoder.decode(errorDescpriton, "UTF-8")), UtilHttp.getLocale(request)); } catch (UnsupportedEncodingException e) { errMsg = UtilProperties.getMessage(resource, "GetGitHubAuthorizationCodeError", UtilHttp.getLocale(request)); } request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } Debug.logInfo("GitHub authorization code: " + authorizationCode, module); GenericValue oauth2GitHub = getOAuth2GitHubConfig(request); if (UtilValidate.isEmpty(oauth2GitHub)) { String errMsg = UtilProperties.getMessage(resource, "GetOAuth2GitHubConfigError", UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } String clientId = oauth2GitHub.getString(PassportUtil.COMMON_CLIENT_ID); String secret = oauth2GitHub.getString(PassportUtil.COMMON_CLIENT_SECRET); String returnURI = oauth2GitHub.getString(PassportUtil.COMMON_RETURN_RUL); // Grant token from authorization code and oauth2 token // Use the authorization code to obtain an access token String accessToken = null; String tokenType = null; HttpClient jsonClient = new HttpClient(); PostMethod postMethod = new PostMethod(TokenEndpoint + TokenServiceUri); try { HttpMethodParams params = new HttpMethodParams(); String queryString = "client_id=" + clientId + "&client_secret=" + secret + "&code=" + authorizationCode + "&redirect_uri=" + URLEncoder.encode(returnURI, "UTF-8"); // Debug.logInfo("GitHub get access token query string: " + queryString, module); postMethod.setQueryString(queryString); params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); postMethod.setParams(params); postMethod.setRequestHeader(PassportUtil.ACCEPT_HEADER, "application/json"); jsonClient.executeMethod(postMethod); // Debug.logInfo("GitHub get access token response code: " + postMethod.getStatusCode(), module); // Debug.logInfo("GitHub get access token response content: " + postMethod.getResponseBodyAsString(1024), module); if (postMethod.getStatusCode() == HttpStatus.SC_OK) { // Debug.logInfo("Json Response from GitHub: " + postMethod.getResponseBodyAsString(1024), module); JSON jsonObject = JSON.from(postMethod.getResponseBodyAsString(1024)); JSONToMap jsonMap = new JSONToMap(); Map<String, Object> userMap = jsonMap.convert(jsonObject); accessToken = (String) userMap.get("access_token"); tokenType = (String) userMap.get("token_type"); // Debug.logInfo("Generated Access Token : " + accessToken, module); // Debug.logInfo("Token Type: " + tokenType, module); } else { String errMsg = UtilProperties.getMessage(resource, "GetOAuth2GitHubAccessTokenError", UtilMisc.toMap("error", postMethod.getResponseBodyAsString()), UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } } catch (UnsupportedEncodingException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (HttpException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (IOException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (ConversionException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } finally { postMethod.releaseConnection(); } // Get User Profile GetMethod getMethod = new GetMethod(ApiEndpoint + UserApiUri); Map<String, Object> userInfo = null; try { userInfo = GitHubAuthenticator.getUserInfo(getMethod, accessToken, tokenType, UtilHttp.getLocale(request)); } catch (HttpException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (IOException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (AuthenticatorException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } finally { getMethod.releaseConnection(); } // Debug.logInfo("GitHub User Info:" + userInfo, module); // Store the user info and check login the user return checkLoginGitHubUser(request, userInfo, accessToken); }
From source file:org.ofbiz.passport.event.LinkedInEvents.java
/** * Parse LinkedIn login response and login the user if possible. * /*from w w w .j ava 2s . c o m*/ * @return */ public static String parseLinkedInResponse(HttpServletRequest request, HttpServletResponse response) { String authorizationCode = request.getParameter(PassportUtil.COMMON_CODE); String state = request.getParameter(PassportUtil.COMMON_STATE); if (!state.equals(request.getSession().getAttribute(SESSION_LINKEDIN_STATE))) { String errMsg = UtilProperties.getMessage(resource, "LinkedInFailedToMatchState", UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } if (UtilValidate.isEmpty(authorizationCode)) { String error = request.getParameter(PassportUtil.COMMON_ERROR); String errorDescpriton = request.getParameter(PassportUtil.COMMON_ERROR_DESCRIPTION); String errMsg = null; try { errMsg = UtilProperties.getMessage(resource, "FailedToGetLinkedInAuthorizationCode", UtilMisc.toMap(PassportUtil.COMMON_ERROR, error, PassportUtil.COMMON_ERROR_DESCRIPTION, URLDecoder.decode(errorDescpriton, "UTF-8")), UtilHttp.getLocale(request)); } catch (UnsupportedEncodingException e) { errMsg = UtilProperties.getMessage(resource, "GetLinkedInAuthorizationCodeError", UtilHttp.getLocale(request)); } request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } // Debug.logInfo("LinkedIn authorization code: " + authorizationCode, module); GenericValue oauth2LinkedIn = getOAuth2LinkedInConfig(request); if (UtilValidate.isEmpty(oauth2LinkedIn)) { String errMsg = UtilProperties.getMessage(resource, "GetOAuth2LinkedInConfigError", UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } String clientId = oauth2LinkedIn.getString(PassportUtil.ApiKeyLabel); String secret = oauth2LinkedIn.getString(PassportUtil.SecretKeyLabel); String returnURI = oauth2LinkedIn.getString(envPrefix + PassportUtil.ReturnUrlLabel); // Grant token from authorization code and oauth2 token // Use the authorization code to obtain an access token String accessToken = null; HttpClient jsonClient = new HttpClient(); PostMethod postMethod = new PostMethod(TokenEndpoint + TokenServiceUri); try { HttpMethodParams params = new HttpMethodParams(); String queryString = "client_id=" + clientId + "&client_secret=" + secret + "&grant_type=authorization_code" + "&code=" + authorizationCode + "&redirect_uri=" + URLEncoder.encode(returnURI, "UTF-8"); // Debug.logInfo("LinkedIn get access token query string: " + queryString, module); postMethod.setQueryString(queryString); params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); postMethod.setParams(params); jsonClient.executeMethod(postMethod); // Debug.logInfo("LinkedIn get access token response code: " + postMethod.getStatusCode(), module); // Debug.logInfo("LinkedIn get access token response content: " + postMethod.getResponseBodyAsString(1024), module); if (postMethod.getStatusCode() == HttpStatus.SC_OK) { // Debug.logInfo("Json Response from LinkedIn: " + postMethod.getResponseBodyAsString(1024), module); JSON jsonObject = JSON.from(postMethod.getResponseBodyAsString(1024)); JSONToMap jsonMap = new JSONToMap(); Map<String, Object> userMap = jsonMap.convert(jsonObject); accessToken = (String) userMap.get("access_token"); // Debug.logInfo("Generated Access Token : " + accessToken, module); } else { String errMsg = UtilProperties.getMessage(resource, "GetOAuth2LinkedInAccessTokenError", UtilMisc.toMap("error", postMethod.getResponseBodyAsString()), UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } } catch (UnsupportedEncodingException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (HttpException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (IOException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (ConversionException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } finally { postMethod.releaseConnection(); } // Get User Profile GetMethod getMethod = new GetMethod(TokenEndpoint + UserApiUri + "?oauth2_access_token=" + accessToken); Document userInfo = null; try { userInfo = LinkedInAuthenticator.getUserInfo(getMethod, UtilHttp.getLocale(request)); } catch (HttpException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (IOException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (AuthenticatorException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (SAXException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (ParserConfigurationException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } finally { getMethod.releaseConnection(); } // Debug.logInfo("LinkedIn User Info:" + userInfo, module); // Store the user info and check login the user return checkLoginLinkedInUser(request, userInfo, accessToken); }
From source file:org.ofbiz.passport.user.GitHubAuthenticator.java
public static Map<String, Object> getUserInfo(GetMethod getMethod, String accessToken, String tokenType, Locale locale) throws HttpException, IOException, AuthenticatorException { JSON userInfo = null;/*from ww w . j ava2 s. c o m*/ HttpClient jsonClient = new HttpClient(); HttpMethodParams params = new HttpMethodParams(); params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); getMethod.setParams(params); getMethod.setRequestHeader(PassportUtil.AUTHORIZATION_HEADER, tokenType + " " + accessToken); getMethod.setRequestHeader(PassportUtil.ACCEPT_HEADER, "application/json"); jsonClient.executeMethod(getMethod); if (getMethod.getStatusCode() == HttpStatus.SC_OK) { Debug.logInfo("Json Response from GitHub: " + getMethod.getResponseBodyAsString(), module); userInfo = JSON.from(getMethod.getResponseBodyAsString()); } else { String errMsg = UtilProperties.getMessage(resource, "GetOAuth2AccessTokenError", UtilMisc.toMap("error", getMethod.getResponseBodyAsString()), locale); throw new AuthenticatorException(errMsg); } JSONToMap jsonMap = new JSONToMap(); Map<String, Object> userMap; try { userMap = jsonMap.convert(userInfo); } catch (ConversionException e) { throw new AuthenticatorException(e.getMessage()); } return userMap; }
From source file:org.ofbiz.passport.user.LinkedInAuthenticator.java
public static Document getUserInfo(GetMethod getMethod, Locale locale) throws HttpException, IOException, AuthenticatorException, SAXException, ParserConfigurationException { Document userInfo = null;//from w w w . j av a 2 s. c o m HttpClient jsonClient = new HttpClient(); HttpMethodParams params = new HttpMethodParams(); params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); getMethod.setParams(params); jsonClient.executeMethod(getMethod); if (getMethod.getStatusCode() == HttpStatus.SC_OK) { Debug.logInfo("Json Response from LinkedIn: " + getMethod.getResponseBodyAsString(), module); userInfo = UtilXml.readXmlDocument(getMethod.getResponseBodyAsString()); } else { String errMsg = UtilProperties.getMessage(resource, "GetOAuth2AccessTokenError", UtilMisc.toMap("error", getMethod.getResponseBodyAsString()), locale); throw new AuthenticatorException(errMsg); } return userInfo; }
From source file:org.opencms.applet.upload.FileUploadApplet.java
/** * Uploads the zipfile to the OpenCms.<p> * /*from w w w. j a v a 2s .co m*/ * @param uploadFile the zipfile to upload */ private void uploadZipFile(File uploadFile) { m_action = m_actionOutputUpload; repaint(); PostMethod post = new PostMethod(m_targetUrl); try { Part[] parts = new Part[5]; parts[0] = new FilePart(uploadFile.getName(), uploadFile); parts[1] = new StringPart("action", "submitform"); parts[2] = new StringPart("unzipfile", "true"); parts[3] = new StringPart("uploadfolder", m_uploadFolder); parts[4] = new StringPart("clientfolder", m_fileSelector.getCurrentDirectory().getAbsolutePath()); HttpMethodParams methodParams = post.getParams(); methodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); MultipartRequestEntity request = new MultipartRequestEntity(parts, methodParams); post.setRequestEntity(request); // add jsessionid query string String sessionId = getParameter("sessionId"); String query = ";" + C_JSESSIONID.toLowerCase() + "=" + sessionId; post.setQueryString(query); post.addRequestHeader(C_JSESSIONID, sessionId); HttpClient client = new HttpClient(); HttpConnectionParams connectionParams = client.getHttpConnectionManager().getParams(); connectionParams.setConnectionTimeout(5000); // add the session cookie client.getState(); client.getHostConfiguration().getHost(); HttpState initialState = new HttpState(); URI uri = new URI(m_targetUrl, false); Cookie sessionCookie = new Cookie(uri.getHost(), C_JSESSIONID, sessionId, "/", null, false); initialState.addCookie(sessionCookie); client.setState(initialState); // no execute the file upload int status = client.executeMethod(post); if (status == HttpStatus.SC_OK) { //return to the specified url and frame target getAppletContext().showDocument(new URL(m_redirectUrl), m_redirectTargetFrame); } else { // create the error text String error = m_errorLine1 + "\n" + post.getStatusLine(); //JOptionPane.showMessageDialog(this, error, "Error!", JOptionPane.ERROR_MESSAGE); getAppletContext().showDocument(new URL(m_errorUrl + "?action=showerror&uploaderror=" + error), "explorer_files"); } } catch (RuntimeException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { post.releaseConnection(); // finally delete the zipFile on the harddisc uploadFile.delete(); } }