Example usage for org.apache.commons.httpclient HttpMethod setDoAuthentication

List of usage examples for org.apache.commons.httpclient HttpMethod setDoAuthentication

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod setDoAuthentication.

Prototype

public abstract void setDoAuthentication(boolean paramBoolean);

Source Link

Usage

From source file:net.sf.ufsc.http.HttpFile.java

protected void execute(HttpMethod method) throws java.io.IOException {
    method.setFollowRedirects(true);/*from  w  ww  .  j a  v  a2  s.  c  o  m*/
    method.setDoAuthentication(true);

    int status = this.client.executeMethod(method);

    if (status != HttpStatus.SC_OK) {
        throw new java.io.IOException(method.getStatusText());
    }
}

From source file:fr.unix_experience.owncloud_sms.engine.OCHttpClient.java

public int execute(HttpMethod req) throws IOException {
    String basicAuth = "Basic "
            + Base64.encodeToString((_username + ":" + _password).getBytes(), Base64.NO_WRAP);
    req.setDoAuthentication(true);
    req.addRequestHeader("Authorization", basicAuth);
    executeMethod(req);/* w ww .j  a v a 2 s  . c  o m*/
    return followRedirections(req);
}

From source file:com.discogs.api.webservice.impl.HttpClientWebService.java

@Override
public Resp doGet(String url) throws WebServiceException {
    HttpMethod method = new GZipCapableGetMethod(url);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    method.setDoAuthentication(true);

    try {//ww  w .  j ava 2  s  .c  o m
        // execute the method
        int statusCode = this.httpClient.executeMethod(method);

        if (logger.isDebugEnabled()) {
            logger.debug(method.getResponseBodyAsString());
        }

        switch (statusCode) {
        case HttpStatus.SC_OK:
            return createResp(method.getResponseBodyAsStream());

        case HttpStatus.SC_NOT_FOUND:
            throw new ResourceNotFoundException("Resource not found.", method.getResponseBodyAsString());

        case HttpStatus.SC_BAD_REQUEST:
            throw new RequestException(method.getResponseBodyAsString());

        case HttpStatus.SC_FORBIDDEN:
            throw new AuthorizationException(method.getResponseBodyAsString());

        case HttpStatus.SC_UNAUTHORIZED:
            throw new AuthorizationException(method.getResponseBodyAsString());

        default:
            String em = "web service returned unknown status '" + statusCode + "', response was: "
                    + method.getResponseBodyAsString();
            logger.error(em);
            throw new WebServiceException(em);
        }
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: " + e.getMessage());
        throw new WebServiceException(e.getMessage(), e);
    } catch (IOException e) {
        logger.error("Fatal transport error: " + e.getMessage());
        throw new WebServiceException(e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.smartitengineering.util.rest.client.jersey.cache.CustomApacheHttpClientResponseResolver.java

private HttpMethod convertRequest(HTTPRequest request) {
    URI requestURI = request.getRequestURI();
    HttpMethod method = getMethod(request.getMethod(), requestURI);
    Headers requestHeaders = request.getAllHeaders();
    addHeaders(requestHeaders, method);/*from w w  w .  j av a2  s .co m*/
    method.setDoAuthentication(true);
    if (method instanceof EntityEnclosingMethod && request.hasPayload()) {
        InputStream payload = request.getPayload().getInputStream();
        EntityEnclosingMethod carrier = (EntityEnclosingMethod) method;
        if (payload != null) {
            carrier.setRequestEntity(new InputStreamRequestEntity(payload));
        }
    }

    return method;
}

From source file:com.sun.jersey.client.apache.DefaultApacheHttpMethodExecutor.java

@Override
public void executeMethod(final HttpMethod method, final ClientRequest cr) {
    final Map<String, Object> props = cr.getProperties();

    method.setDoAuthentication(true);

    final HttpMethodParams methodParams = method.getParams();

    // Set the handle cookies property
    if (!cr.getPropertyAsFeature(ApacheHttpClientConfig.PROPERTY_HANDLE_COOKIES)) {
        methodParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    }//from  ww w .j a v a2s . c  om

    // Set the interactive and credential provider properties
    if (cr.getPropertyAsFeature(ApacheHttpClientConfig.PROPERTY_INTERACTIVE)) {
        CredentialsProvider provider = (CredentialsProvider) props
                .get(ApacheHttpClientConfig.PROPERTY_CREDENTIALS_PROVIDER);
        if (provider == null) {
            provider = DEFAULT_CREDENTIALS_PROVIDER;
        }
        methodParams.setParameter(CredentialsProvider.PROVIDER, provider);
    } else {
        methodParams.setParameter(CredentialsProvider.PROVIDER, null);
    }

    // Set the read timeout
    final Integer readTimeout = (Integer) props.get(ApacheHttpClientConfig.PROPERTY_READ_TIMEOUT);
    if (readTimeout != null) {
        methodParams.setSoTimeout(readTimeout);
    }

    if (method instanceof EntityEnclosingMethod) {
        final EntityEnclosingMethod entMethod = (EntityEnclosingMethod) method;

        if (cr.getEntity() != null) {
            final RequestEntityWriter re = getRequestEntityWriter(cr);
            final Integer chunkedEncodingSize = (Integer) props
                    .get(ApacheHttpClientConfig.PROPERTY_CHUNKED_ENCODING_SIZE);
            if (chunkedEncodingSize != null) {
                // There doesn't seems to be a way to set the chunk size.
                entMethod.setContentChunked(true);

                // It is not possible for a MessageBodyWriter to modify
                // the set of headers before writing out any bytes to
                // the OutputStream
                // This makes it impossible to use the multipart
                // writer that modifies the content type to add a boundary
                // parameter
                writeOutBoundHeaders(cr.getHeaders(), method);

                // Do not buffer the request entity when chunked encoding is
                // set
                entMethod.setRequestEntity(new RequestEntity() {

                    @Override
                    public boolean isRepeatable() {
                        return false;
                    }

                    @Override
                    public void writeRequest(OutputStream out) throws IOException {
                        re.writeRequestEntity(out);
                    }

                    @Override
                    public long getContentLength() {
                        return re.getSize();
                    }

                    @Override
                    public String getContentType() {
                        return re.getMediaType().toString();
                    }
                });

            } else {
                entMethod.setContentChunked(false);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try {
                    re.writeRequestEntity(new CommittingOutputStream(baos) {

                        @Override
                        protected void commit() throws IOException {
                            writeOutBoundHeaders(cr.getMetadata(), method);
                        }
                    });
                } catch (IOException ex) {
                    throw new ClientHandlerException(ex);
                }

                final byte[] content = baos.toByteArray();
                entMethod.setRequestEntity(new RequestEntity() {

                    @Override
                    public boolean isRepeatable() {
                        return true;
                    }

                    @Override
                    public void writeRequest(OutputStream out) throws IOException {
                        out.write(content);
                    }

                    @Override
                    public long getContentLength() {
                        return content.length;
                    }

                    @Override
                    public String getContentType() {
                        return re.getMediaType().toString();
                    }
                });
            }
        } else {
            writeOutBoundHeaders(cr.getHeaders(), method);
        }
    } else {
        writeOutBoundHeaders(cr.getHeaders(), method);

        // Follow redirects
        method.setFollowRedirects(cr.getPropertyAsFeature(ApacheHttpClientConfig.PROPERTY_FOLLOW_REDIRECTS));
    }
    try {
        httpClient.executeMethod(getHostConfiguration(httpClient, props), method, getHttpState(props));
    } catch (Exception e) {
        method.releaseConnection();
        throw new ClientHandlerException(e);
    }
}

From source file:com.zimbra.cs.dav.client.WebDavClient.java

protected HttpMethod executeMethod(HttpMethod m, Depth d, String bodyForLogging) throws IOException {
    HttpMethodParams p = m.getParams();//from   w w  w  .  j a  v a 2s  .c o m
    if (p != null)
        p.setCredentialCharset("UTF-8");

    m.setDoAuthentication(true);
    m.setRequestHeader("User-Agent", mUserAgent);
    String depth = "0";
    switch (d) {
    case one:
        depth = "1";
        break;
    case infinity:
        depth = "infinity";
        break;
    case zero:
        break;
    default:
        break;
    }
    m.setRequestHeader("Depth", depth);
    logRequestInfo(m, bodyForLogging);
    HttpClientUtil.executeMethod(mClient, m);
    logResponseInfo(m);

    return m;
}

From source file:edu.du.penrose.systems.fedora.ResourceIndexUtils.java

/** USED 2-2-12
 * //from  www. j a v  a  2  s  .  com
 * The administrator is just used to get host,port,user,pwd info.
 * The call to the resource index is actually via httpClient and rest call.
 * 
 * @param topCollection such as islandora:top or codu:top
 * @param namespace the names space of collections below the topCollection. <br>
 * <br>
 * For example, to retrieve the collection names for coduDuMaps and coduDuPicture...<br> <br>
 *    islandora:top - use topCollection=islandora:top and namespace=codu <br>
 *  &nbsp;&nbsp&nbsp;codu:duMaps <br>
 *  &nbsp;&nbsp&nbsp;codu:duPictures <br>
 *  &nbsp;&nbsp&nbsp;xxxx:yyyy <br>
 *  &nbsp;&nbsp&nbsp;zzzz:wwww <br><br>
 *      OR <br><br>
 *  islandora:top <br>
 *  &nbsp;&nbsp&nbsp;codu:top - use topCollection=codu:top and namespace=codu <br>
 *  &nbsp;&nbsp&nbsp;&nbsp;&nbsp&nbsp;codu:duMaps <br>
 *  &nbsp;&nbsp&nbsp;&nbsp;&nbsp&nbsp;codu:duPictures  <br> 
 *  
 *  @param administrator  The administrator is just used to get host,port,user,password info.
 *  @param topCollection
 *  @param nameSpace
 *  
 * @return map of collection names and  titles.
 */
public static Map<String, String> getChildCollectionsMap(Administrator administrator, String topCollection,
        String namespace) {
    final String host = administrator.getHost();
    final int port = administrator.getPort();
    String userName = administrator.getUserName();
    String pwd = administrator.getUserPassword();
    String realm = null; // "realm is actually Fedora or Fedora Repository Server"

    Map<String, String> collectionMap = new LinkedHashMap<String, String>();

    String UTF_8_ENCONDING = "UTF-8";

    String type = "tuples";
    String flush = "false"; // optional default false;
    String lang = "itql";
    String format = "CSV";
    String limit = "100"; // optional default unlimited;
    String distinct = "off"; // optional default off;
    String stream = "off"; // optional default off;
    String query = "select $subject $title from <#ri> where ( $subject <fedora-model:label> $title and $subject <fedora-rels-ext:isMemberOfCollection><info:fedora/"
            + topCollection + "> ) order by $title";
    // tbd quick kludge
    String query_2 = "select $subject $title from <#ri> where ( $subject <fedora-model:label> $title and $subject <fedora-rels-ext:isMemberOf><info:fedora/"
            + topCollection + "> ) order by $title";

    String queryEncoded;
    String queryEncoded_2;
    HttpMethod method = null;
    HttpMethod method_2 = null;
    try {
        queryEncoded = URLEncoder.encode(query, UTF_8_ENCONDING);
        queryEncoded_2 = URLEncoder.encode(query_2, UTF_8_ENCONDING);

        HttpClient myClient = new HttpClient();
        method = new GetMethod("http://" + host + ":" + port + "/fedora/risearch?type=" + type + "&lang=" + lang
                + "&format=" + format + "&limit=" + limit + "&distinct=" + distinct + "&stream=" + stream
                + "&query=" + queryEncoded);

        method_2 = new GetMethod("http://" + host + ":" + port + "/fedora/risearch?type=" + type + "&lang="
                + lang + "&format=" + format + "&limit=" + limit + "&distinct=" + distinct + "&stream=" + stream
                + "&query=" + queryEncoded_2);

        myClient.getState().setCredentials(new AuthScope(host, port, realm),
                new UsernamePasswordCredentials(userName, pwd));
        method.setDoAuthentication(true);
        myClient.getParams().setAuthenticationPreemptive(true);

        myClient.executeMethod(method);

        String response = method.getResponseBodyAsString();
        String lines[] = response.split("\n");

        for (int i = 0; i < lines.length; i++) {
            if (!lines[i].contains("islandora") && !lines[i].equalsIgnoreCase("\"subject\",\"title\"")) {

                String singleLine = lines[i].replace("info:fedora/", "");
                if (!singleLine.startsWith(namespace)) {
                    continue;
                }
                String[] pieces = singleLine.split(",");
                String collectionName = pieces[0];
                String collectionTitle = pieces[1];

                if (isCollection(administrator, collectionName)) // collectionName is the pid
                {
                    collectionMap.put(collectionName, collectionTitle);
                }
            }
        }

        myClient.executeMethod(method_2);

        String response_2 = method.getResponseBodyAsString();
        String lines_2[] = response_2.split("\n");

        for (int i = 0; i < lines_2.length; i++) {
            if (!lines_2[i].contains("islandora") && !lines_2[i].equalsIgnoreCase("\"subject\",\"title\"")) {

                String singleLine = lines_2[i].replace("info:fedora/", "");
                if (!singleLine.startsWith(namespace)) {
                    continue;
                }
                String[] pieces = singleLine.split(",");
                String collectionName = pieces[0];
                String collectionTitle = pieces[1];

                if (isCollection(administrator, collectionName)) // collectionName is the pid
                {
                    collectionMap.put(collectionName, collectionTitle);
                }
            }
        }
    } catch (Exception e) {
        collectionMap.put("", "Unable to get Collections:" + e);
        return collectionMap;
    } finally {
        method.releaseConnection();
        method_2.releaseConnection();
    }

    return collectionMap;
}

From source file:com.zimbra.cs.fb.ExchangeFreeBusyProvider.java

private int sendRequest(HttpMethod method, ServerInfo info) throws IOException {
    method.setDoAuthentication(true);
    method.setRequestHeader(HEADER_USER_AGENT, USER_AGENT);
    HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
    HttpProxyUtil.configureProxy(client);
    switch (info.scheme) {
    case basic:/*  w ww .j  av a 2  s  .  c om*/
        basicAuth(client, info);
        break;
    case form:
        formAuth(client, info);
        break;
    }
    return HttpClientUtil.executeMethod(client, method);
}

From source file:edu.du.penrose.systems.fedora.ResourceIndexUtils.java

/**
 * /*w  ww  . j  a  va 2s . c  o  m*/
 * Get a list of all objects in the topCollection. The administrator is just used to get host,port,user, and pwd info.
 * The call to the resource index is actually via httpClient and rest call. 
 * 
 * @see FedoraAppBatchIngestController#getAdministrator()
 * @param administrator  The administrator is just used to get host,port,user,password info.
 * @param topCollection
 * @param onlyCollections =true to return only collection objects
 * 
 * @return all object pids in the topCollection that are also collections
 */
private static ArrayList<String> getChildren(Administrator administrator, String topCollection,
        boolean onlyCollections) {
    final String host = administrator.getHost();
    final int port = administrator.getPort();
    String userName = administrator.getUserName();
    String pwd = administrator.getUserPassword();
    String realm = null; // "realm is actually Fedora or Fedora Repository Server"

    ArrayList<String> children = new ArrayList<String>();

    String UTF_8_ENCONDING = "UTF-8";

    String type = "tuples";
    String flush = "false"; // optional default false;
    String lang = "itql";
    String format = "CSV";
    String limit = "100"; // optional default unlimited; NOT USED
    String distinct = "off"; // optional default off;
    String stream = "off"; // optional default off;
    String query = "select $subject from <#ri> where ( $subject <fedora-rels-ext:isMemberOfCollection><info:fedora/"
            + topCollection + "> )";
    // TBD kludge, I don't have time to do things right.
    String query_2 = "select $subject from <#ri> where ( $subject <fedora-rels-ext:isMemberOf><info:fedora/"
            + topCollection + "> )";

    String queryEncoded;
    String queryEncoded_2;
    HttpClient myClient = null;
    HttpMethod method = null;
    HttpMethod method_2 = null;
    try {
        queryEncoded = URLEncoder.encode(query, UTF_8_ENCONDING);
        queryEncoded_2 = URLEncoder.encode(query_2, UTF_8_ENCONDING);

        myClient = new HttpClient();
        String finalQuery = "http://" + host + ":" + port + "/fedora/risearch?type=" + type + "&lang=" + lang
                + "&format=" + format + "&distinct=" + distinct + "&stream=" + stream + "&query="
                + queryEncoded;
        String finalQuery_2 = "http://" + host + ":" + port + "/fedora/risearch?type=" + type + "&lang=" + lang
                + "&format=" + format + "&distinct=" + distinct + "&stream=" + stream + "&query="
                + queryEncoded_2;
        method = new GetMethod(finalQuery);
        method_2 = new GetMethod(finalQuery_2);

        myClient.getState().setCredentials(new AuthScope(host, port, realm),
                new UsernamePasswordCredentials(userName, pwd));
        method.setDoAuthentication(true);
        myClient.getParams().setAuthenticationPreemptive(true);

        myClient.executeMethod(method);

        String response = method.getResponseBodyAsString();
        String lines[] = response.split("\n");

        for (int i = 0; i < lines.length; i++) {
            if (!lines[i].contains("islandora") && !lines[i].equalsIgnoreCase("\"subject\"")) {
                String collectionPid = lines[i].replace("info:fedora/", "");
                if (onlyCollections) {
                    if (isCollection(administrator, collectionPid)) {
                        children.add(collectionPid);
                    }
                } else {
                    children.add(collectionPid);
                }
            }
        }

        myClient.executeMethod(method_2);

        String response_2 = method_2.getResponseBodyAsString();
        String lines_2[] = response_2.split("\n");

        for (int i = 0; i < lines_2.length; i++) {
            if (!lines_2[i].contains("islandora") && !lines_2[i].equalsIgnoreCase("\"subject\"")) {
                String collectionPid = lines_2[i].replace("info:fedora/", "");
                if (onlyCollections) {
                    if (isCollection(administrator, collectionPid)) {
                        children.add(collectionPid);
                    }
                } else {
                    children.add(collectionPid);
                }
            }
        }

    } catch (Exception e) {
        children.add("Unable to get Collections:" + e);
        return children;
    } finally {
        method.releaseConnection();
        method_2.releaseConnection();
    }

    return children;
}

From source file:com.twinsoft.convertigo.engine.proxy.translated.HttpClient.java

private int doExecuteMethod(HttpMethod method, HttpConnector connector, String resourceUrl,
        ParameterShuttle infoShuttle) throws ConnectionException, URIException, MalformedURLException {
    int statuscode = -1;

    HostConfiguration hostConfiguration = connector.hostConfiguration;

    // Tells the method to automatically handle authentication.
    method.setDoAuthentication(true);

    // Tells the method to automatically handle redirection.
    method.setFollowRedirects(false);/*from ww w.java  2s  .  c  o  m*/

    try {
        // Display the cookies
        if (handleCookie) {
            Cookie[] cookies = httpState.getCookies();
            if (Engine.logEngine.isTraceEnabled())
                Engine.logEngine.trace("(HttpClient) request cookies:" + Arrays.asList(cookies).toString());
        }

        Engine.logEngine.debug("(HttpClient) executing method...");
        statuscode = Engine.theApp.httpClient.executeMethod(hostConfiguration, method, httpState);
        Engine.logEngine.debug("(HttpClient) end of method successfull");

        // Display the cookies
        if (handleCookie) {
            Cookie[] cookies = httpState.getCookies();
            if (Engine.logEngine.isTraceEnabled())
                Engine.logEngine.trace("(HttpClient) response cookies:" + Arrays.asList(cookies).toString());
        }
    } catch (IOException e) {
        try {
            Engine.logEngine.warn("(HttpClient) connection error to " + resourceUrl + ": " + e.getMessage()
                    + "; retrying method");
            statuscode = Engine.theApp.httpClient.executeMethod(hostConfiguration, method, httpState);
            Engine.logEngine.debug("(HttpClient) end of method successfull");
        } catch (IOException ee) {
            throw new ConnectionException("Connection error to " + resourceUrl, ee);
        }
    }
    return statuscode;
}