Example usage for org.apache.commons.httpclient.params HttpMethodParams HttpMethodParams

List of usage examples for org.apache.commons.httpclient.params HttpMethodParams HttpMethodParams

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.params HttpMethodParams HttpMethodParams.

Prototype

public HttpMethodParams() 

Source Link

Usage

From source file:org.alfresco.rest.api.tests.util.MultiPartBuilder.java

public MultiPartRequest build() throws IOException {
    List<Part> parts = new ArrayList<>();

    if (fileData != null) {
        FilePart fp = new FilePart("filedata", fileData.getFileName(), fileData.getFile(),
                fileData.getMimetype(), null);
        // Get rid of the default values added upon FilePart instantiation
        fp.setCharSet(fileData.getEncoding());
        fp.setContentType(fileData.getMimetype());
        parts.add(fp);//w  w  w  .  ja  v a 2s .c  o m
        addPartIfNotNull(parts, "name", fileData.getFileName());
    }
    addPartIfNotNull(parts, "relativepath", relativePath);
    addPartIfNotNull(parts, "updatenoderef", updateNodeRef);
    addPartIfNotNull(parts, "description", description);
    addPartIfNotNull(parts, "contenttype", contentTypeQNameStr);
    addPartIfNotNull(parts, "aspects", getCommaSeparated(aspects));
    addPartIfNotNull(parts, "majorversion", majorVersion);
    addPartIfNotNull(parts, "overwrite", overwrite);
    addPartIfNotNull(parts, "autorename", autoRename);
    addPartIfNotNull(parts, "nodetype", nodeType);
    addPartIfNotNull(parts, "renditions", getCommaSeparated(renditionIds));

    if (!properties.isEmpty()) {
        for (Entry<String, String> prop : properties.entrySet()) {
            parts.add(new StringPart(prop.getKey(), prop.getValue()));
        }
    }

    MultipartRequestEntity req = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]),
            new HttpMethodParams());

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    req.writeRequest(os);

    return new MultiPartRequest(os.toByteArray(), req.getContentType(), req.getContentLength());
}

From source file:org.apache.maven.wagon.providers.webdav.HttpMethodConfiguration.java

public HttpMethodParams asMethodParams(HttpMethodParams defaults) {
    if (!hasParams()) {
        return null;
    }/*w  w  w . j  ava2s  .  c o m*/

    HttpMethodParams p = new HttpMethodParams();
    p.setDefaults(defaults);

    fillParams(p);

    return p;
}

From source file:org.eclipse.osee.framework.core.util.HttpProcessor.java

public static boolean isAlive(URL url) {
    boolean isAlive = false;
    boolean recheck = true;
    String key = toIsAliveKey(url);
    Pair<Integer, Long> lastChecked = isAliveMap.get(key);
    if (lastChecked != null) {
        long checkedOffset = System.currentTimeMillis() - lastChecked.getSecond().longValue();
        if (checkedOffset < CHECK_WINDOW) {
            recheck = false;//  w  w w  . j a v a 2 s.c om
            isAlive = lastChecked.getFirst() != -1;
        }
    }

    if (recheck) {
        try {
            GetMethod method = new GetMethod(url.toString());
            try {
                HttpMethodParams params = new HttpMethodParams();
                params.setParameter(HttpMethodParams.RETRY_HANDLER,
                        new DefaultHttpMethodRetryHandler(0, false));
                params.setSoTimeout(1000);
                method.setParams(params);
                int responseCode = executeMethod(url, method);
                if (responseCode == HttpURLConnection.HTTP_NOT_FOUND
                        || responseCode == HttpURLConnection.HTTP_ACCEPTED
                        || responseCode == HttpURLConnection.HTTP_ACCEPTED
                        || responseCode == HttpURLConnection.HTTP_OK) {
                    isAlive = true;
                }
            } finally {
                method.releaseConnection();
            }
        } catch (Exception ex) {
            // Do Nothing
        }
    }
    return isAlive;
}

From source file:org.jboss.test.NamingUtil.java

/**
 * This methods calls servlet which must be deployed at server to create JNDI objects remotely to byepass security.
 * //from www.j  av a 2  s. com
 * @param jndiName
 * @param dataKey
 * @param data
 * @param useHAJNDI
 * @throws Exception
 */
public static void createRemoteTestJNDIBinding(String jndiName, String dataKey, Object data, String serverHost,
        boolean useHAJNDI) throws Exception {

    HttpClient httpClient = new HttpClient();
    String url = "http://" + serverHost + ":8080/naming-util/naming-util-servlet";

    HttpMethodParams params = new HttpMethodParams();
    params.setParameter("jndiName", jndiName);
    if (data != null) {
        params.setParameter("dataKey", dataKey);
        params.setParameter("data", data);
    }
    params.setBooleanParameter("useHAJndi", useHAJNDI);

    url = url + "?jndiName=" + jndiName;
    url = url + "&dataKey=" + dataKey;
    url = url + "&data=" + data;
    url = url + "&useHAJndi=" + Boolean.toString(useHAJNDI);

    GetMethod jndiGet = new GetMethod(url);
    //jndiGet.setParams(params);
    int responseCode = httpClient.executeMethod(jndiGet);
    String body = jndiGet.getResponseBodyAsString();

    if (responseCode != HttpURLConnection.HTTP_OK || !body.contains("OK")) {
        throw new Exception(body);
    }

}

From source file:org.jetbrains.tfsIntegration.webservice.WebServiceHelper.java

public static void setupStub(final @NotNull Stub stub, final @NotNull Credentials credentials,
        final @NotNull URI serverUri) {
    Options options = stub._getServiceClient().getOptions();

    // http params
    options.setProperty(HTTPConstants.CHUNKED, Constants.VALUE_FALSE);
    options.setProperty(HTTPConstants.MC_ACCEPT_GZIP, Boolean.TRUE);
    options.setProperty(HTTPConstants.SO_TIMEOUT, SOCKET_TIMEOUT);
    if (Registry.is("tfs.set.connection.timeout", false)) {
        options.setProperty(HTTPConstants.CONNECTION_TIMEOUT, SOCKET_TIMEOUT);
    }/*from   w ww  .  j  a v a  2 s .  co m*/

    // credentials
    if (credentials.getType() == Credentials.Type.Alternate) {
        String basicAuth = BasicScheme.authenticate(
                new UsernamePasswordCredentials(credentials.getUserName(), credentials.getPassword()), "UTF-8");
        Map<String, String> headers = new HashMap<String, String>();
        headers.put(HTTPConstants.HEADER_AUTHORIZATION, basicAuth);
        options.setProperty(HTTPConstants.HTTP_HEADERS, headers);
    } else {
        HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
        auth.setUsername(credentials.getUserName());
        auth.setPassword(credentials.getPassword() != null ? credentials.getPassword() : "");
        auth.setDomain(credentials.getDomain());
        auth.setHost(serverUri.getHost());
        options.setProperty(HTTPConstants.AUTHENTICATE, auth);

        HttpMethodParams params = new HttpMethodParams();
        params.setBooleanParameter(USE_NATIVE_CREDENTIALS,
                credentials.getType() == Credentials.Type.NtlmNative);
        options.setProperty(HTTPConstants.HTTP_METHOD_PARAMS, params);
    }

    // proxy
    final HttpTransportProperties.ProxyProperties proxyProperties;
    final HTTPProxyInfo proxy = HTTPProxyInfo.getCurrent();
    if (proxy.host != null) {
        proxyProperties = new HttpTransportProperties.ProxyProperties();
        Pair<String, String> domainAndUser = getDomainAndUser(proxy.user);
        proxyProperties.setProxyName(proxy.host);
        proxyProperties.setProxyPort(proxy.port);
        proxyProperties.setDomain(domainAndUser.first);
        proxyProperties.setUserName(domainAndUser.second);
        proxyProperties.setPassWord(proxy.password);
    } else {
        proxyProperties = null;
    }

    options.setProperty(HTTPConstants.PROXY, proxyProperties);
}

From source file:org.ngrinder.agent.controller.AgentManagerRestAPIControllerTest.java

@Ignore
@Test//ww  w.ja  va 2 s . c om
public void testRestAPI() throws IOException {
    HttpClient client = new HttpClient();
    // To be avoided unless in debug mode
    Credentials defaultcreds = new UsernamePasswordCredentials("admin", "111111");
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, defaultcreds);
    PutMethod method = new PutMethod("http://localhost:8080/agent/api/36");
    final HttpMethodParams params = new HttpMethodParams();
    params.setParameter("action", "approve");
    method.setParams(params);
    final int i = client.executeMethod(method);
    System.out.println(method.getResponseBodyAsString());
}

From source file:org.ofbiz.passport.event.GitHubEvents.java

/**
 * Parse GitHub login response and login the user if possible.
 * //from w  w w. j  a v a 2s.  c  o  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 ww. j a  v a 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;/* w w  w  . ja  v a2 s .com*/
    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 a  va  2  s.  c om*/
    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;
}