Search in sources :

Example 56 with Credentials

use of org.apache.commons.httpclient.Credentials in project sling by apache.

the class ListChildrenCommand method execute.

@Override
public Result<ResourceProxy> execute() {
    GetMethod get = new GetMethod(getPath());
    try {
        httpClient.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials(repositoryInfo.getUsername(), repositoryInfo.getPassword());
        httpClient.getState().setCredentials(new AuthScope(repositoryInfo.getHost(), repositoryInfo.getPort(), AuthScope.ANY_REALM), defaultcreds);
        int responseStatus = httpClient.executeMethod(get);
        //return EncodingUtil.getString(rawdata, m.getResponseCharSet());
        if (!isSuccessStatus(responseStatus))
            return failureResultForStatusCode(responseStatus);
        ResourceProxy resource = new ResourceProxy(path);
        Gson gson = new Gson();
        try (JsonReader jsonReader = new JsonReader(new InputStreamReader(get.getResponseBodyAsStream(), get.getResponseCharSet()))) {
            jsonReader.beginObject();
            while (jsonReader.hasNext()) {
                String name = jsonReader.nextName();
                JsonToken token = jsonReader.peek();
                if (token == JsonToken.BEGIN_OBJECT) {
                    ResourceProxy child = new ResourceProxy(PathUtil.join(path, name));
                    ResourceWithPrimaryType resourceWithPrimaryType = gson.fromJson(jsonReader, ResourceWithPrimaryType.class);
                    // evaluate its jcr:primaryType as well!
                    child.addProperty(Repository.JCR_PRIMARY_TYPE, resourceWithPrimaryType.getPrimaryType());
                    resource.addChild(child);
                } else if (token == JsonToken.STRING) {
                    if (Repository.JCR_PRIMARY_TYPE.equals(name)) {
                        String primaryType = jsonReader.nextString();
                        if (primaryType != null) {
                            // TODO - needed?
                            resource.addProperty(Repository.JCR_PRIMARY_TYPE, primaryType);
                        }
                    }
                } else {
                    jsonReader.skipValue();
                }
            }
            jsonReader.endObject();
        }
        return AbstractResult.success(resource);
    } catch (Exception e) {
        return AbstractResult.failure(new RepositoryException(e));
    } finally {
        get.releaseConnection();
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) Gson(com.google.gson.Gson) RepositoryException(org.apache.sling.ide.transport.RepositoryException) ResourceProxy(org.apache.sling.ide.transport.ResourceProxy) RepositoryException(org.apache.sling.ide.transport.RepositoryException) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) GetMethod(org.apache.commons.httpclient.methods.GetMethod) AuthScope(org.apache.commons.httpclient.auth.AuthScope) JsonReader(com.google.gson.stream.JsonReader) JsonToken(com.google.gson.stream.JsonToken) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials)

Example 57 with Credentials

use of org.apache.commons.httpclient.Credentials in project openhab1-addons by openhab.

the class Connection method sendCommand.

/**
     * Send a command to the Particle REST API (convenience function).
     *
     * @param device
     *            the device context, or <code>null</code> if not needed for this command.
     * @param funcName
     *            the function name to call, or variable/field to retrieve if <code>command</code> is
     *            <code>null</code>.
     * @param user
     *            the user name to use in Basic Authentication if the funcName would require Basic Authentication.
     * @param pass
     *            the password to use in Basic Authentication if the funcName would require Basic Authentication.
     * @param command
     *            the command to send to the API.
     * @param proc
     *            a callback object that receives the status code and response body, or <code>null</code> if not
     *            needed.
     */
public void sendCommand(AbstractDevice device, String funcName, String user, String pass, String command, HttpResponseHandler proc) {
    String url = null;
    String httpMethod = null;
    String content = null;
    String contentType = null;
    Properties headers = new Properties();
    logger.trace("sendCommand: funcName={}", funcName);
    switch(funcName) {
        case "createToken":
            httpMethod = HTTP_POST;
            url = TOKEN_URL;
            content = command;
            contentType = APPLICATION_FORM_URLENCODED;
            break;
        case "deleteToken":
            httpMethod = HTTP_DELETE;
            url = String.format(ACCESS_TOKENS_URL, tokens.accessToken);
            break;
        case "getDevices":
            httpMethod = HTTP_GET;
            url = String.format(GET_DEVICES_URL, tokens.accessToken);
            break;
        default:
            url = String.format(DEVICE_FUNC_URL, device.getId(), funcName, tokens.accessToken);
            if (command == null) {
                // retrieve a variable
                httpMethod = HTTP_GET;
            } else {
                // call a function
                httpMethod = HTTP_POST;
                content = command;
                contentType = APPLICATION_JSON;
            }
            break;
    }
    HttpClient client = new HttpClient();
    if (!url.contains("access_token=")) {
        Credentials credentials = new UsernamePasswordCredentials(user, pass);
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, credentials);
    }
    HttpMethod method = createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(timeout);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    for (String httpHeaderKey : headers.stringPropertyNames()) {
        method.addRequestHeader(new Header(httpHeaderKey, headers.getProperty(httpHeaderKey)));
        logger.trace("Header key={}, value={}", httpHeaderKey, headers.getProperty(httpHeaderKey));
    }
    try {
        // add content if a valid method is given ...
        if (method instanceof EntityEnclosingMethod && content != null) {
            EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
            eeMethod.setRequestEntity(new StringRequestEntity(content, contentType, null));
            logger.trace("content='{}', contentType='{}'", content, contentType);
        }
        if (logger.isDebugEnabled()) {
            try {
                logger.debug("About to execute '{}'", method.getURI());
            } catch (URIException e) {
                logger.debug(e.getMessage());
            }
        }
        int statusCode = client.executeMethod(method);
        if (statusCode >= HttpStatus.SC_BAD_REQUEST) {
            logger.debug("Method failed: " + method.getStatusLine());
        }
        String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
        if (!responseBody.isEmpty()) {
            logger.debug("Body of response: {}", responseBody);
        }
        if (proc != null) {
            proc.handleResponse(statusCode, responseBody);
        }
    } catch (HttpException he) {
        logger.warn("{}", he);
    } catch (IOException ioe) {
        logger.debug("{}", ioe);
    } finally {
        method.releaseConnection();
    }
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) IOException(java.io.IOException) Properties(java.util.Properties) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) URIException(org.apache.commons.httpclient.URIException) Header(org.apache.commons.httpclient.Header) HttpClient(org.apache.commons.httpclient.HttpClient) HttpException(org.apache.commons.httpclient.HttpException) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 58 with Credentials

use of org.apache.commons.httpclient.Credentials in project zm-mailbox by Zimbra.

the class WebDavClient method setCredential.

public void setCredential(String user, String pass) {
    mUsername = user;
    mPassword = pass;
    HttpState state = new HttpState();
    Credentials cred = new UsernamePasswordCredentials(mUsername, mPassword);
    state.setCredentials(AuthScope.ANY, cred);
    mClient.setState(state);
    ArrayList<String> authPrefs = new ArrayList<String>();
    authPrefs.add(AuthPolicy.BASIC);
    mClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    mClient.getParams().setAuthenticationPreemptive(true);
}
Also used : HttpState(org.apache.commons.httpclient.HttpState) ArrayList(java.util.ArrayList) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials)

Example 59 with Credentials

use of org.apache.commons.httpclient.Credentials in project oxCore by GluuFederation.

the class HTTPFileDownloader method createHttpClientWithBasicAuth.

private static HttpClient createHttpClientWithBasicAuth(String userid, String password) {
    Credentials credentials = new UsernamePasswordCredentials(userid, password);
    HttpClient httpClient = new HttpClient();
    httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    httpClient.getParams().setAuthenticationPreemptive(true);
    return httpClient;
}
Also used : HttpClient(org.apache.commons.httpclient.HttpClient) Credentials(org.apache.commons.httpclient.Credentials) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials)

Example 60 with Credentials

use of org.apache.commons.httpclient.Credentials in project sling by apache.

the class HttpTestBase method setUp.

@Override
protected void setUp() throws Exception {
    super.setUp();
    MDC.put("testclass", getClass().getName());
    MDC.put("testcase", getName());
    // assume http and webdav are on the same host + port
    URL url = null;
    try {
        url = new URL(HTTP_BASE_URL);
    } catch (MalformedURLException mfe) {
        // MalformedURLException doesn't tell us the URL by default
        throw new IOException("MalformedURLException: " + HTTP_BASE_URL);
    }
    // setup HTTP client, with authentication (using default Jackrabbit credentials)
    httpClient = new TestInfoPassingClient();
    httpClient.getParams().setAuthenticationPreemptive(true);
    Credentials defaultcreds = getDefaultCredentials();
    httpClient.getState().setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), defaultcreds);
    testClient = new SlingIntegrationTestClient(httpClient);
    testClient.setFolderExistsTestExtension(readinessCheckExtension);
    waitForSlingStartup();
}
Also used : MalformedURLException(java.net.MalformedURLException) AuthScope(org.apache.commons.httpclient.auth.AuthScope) IOException(java.io.IOException) URL(java.net.URL) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials)

Aggregations

Credentials (org.apache.commons.httpclient.Credentials)102 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)102 ArrayList (java.util.ArrayList)64 NameValuePair (org.apache.commons.httpclient.NameValuePair)64 JsonObject (javax.json.JsonObject)52 HttpTest (org.apache.sling.commons.testing.integration.HttpTest)51 Test (org.junit.Test)51 JsonArray (javax.json.JsonArray)19 AuthScope (org.apache.commons.httpclient.auth.AuthScope)17 HashSet (java.util.HashSet)14 GetMethod (org.apache.commons.httpclient.methods.GetMethod)12 HttpClient (org.apache.commons.httpclient.HttpClient)11 URL (java.net.URL)9 HttpMethod (org.apache.commons.httpclient.HttpMethod)5 IOException (java.io.IOException)4 HttpState (org.apache.commons.httpclient.HttpState)4 After (org.junit.After)4 InputStream (java.io.InputStream)3 Header (org.apache.commons.httpclient.Header)3 HttpException (org.apache.commons.httpclient.HttpException)3