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();
}
}
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();
}
}
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);
}
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;
}
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();
}
Aggregations