use of org.apache.commons.httpclient.Header in project sling by apache.
the class AuthenticationResponseCodeTest method testValidatingIncorrectCookie.
@Test
public void testValidatingIncorrectCookie() throws Exception {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new NameValuePair("j_validate", "true"));
List<Header> headers = new ArrayList<Header>();
headers.add(new Header("Cookie", "sling.formauth=garbage"));
HttpMethod post = assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check", HttpServletResponse.SC_FORBIDDEN, params, headers, null);
assertXReason(post);
}
use of org.apache.commons.httpclient.Header in project sling by apache.
the class RedirectOnLogoutTest method testRedirectToResourceAfterLogout.
/**
* Test SLING-1847
* @throws Exception
*/
@Test
public void testRedirectToResourceAfterLogout() throws Exception {
//login
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new NameValuePair("j_username", "admin"));
params.add(new NameValuePair("j_password", "admin"));
H.assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check", HttpServletResponse.SC_MOVED_TEMPORARILY, params, null);
//...and then...logout with a resource redirect
String locationAfterLogout = HttpTest.SERVLET_CONTEXT + "/system/sling/info.sessionInfo.json";
final GetMethod get = new GetMethod(HttpTest.HTTP_BASE_URL + "/system/sling/logout");
NameValuePair[] logoutParams = new NameValuePair[1];
logoutParams[0] = new NameValuePair("resource", locationAfterLogout);
get.setQueryString(logoutParams);
get.setFollowRedirects(false);
final int status = H.getHttpClient().executeMethod(get);
assertEquals("Expected redirect", HttpServletResponse.SC_MOVED_TEMPORARILY, status);
Header location = get.getResponseHeader("Location");
assertEquals(HttpTest.HTTP_BASE_URL + locationAfterLogout, location.getValue());
}
use of org.apache.commons.httpclient.Header in project zeppelin by apache.
the class AbstractTestRestApi method getCookie.
private static String getCookie(String user, String password) throws IOException {
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(url + "/login");
postMethod.addRequestHeader("Origin", url);
postMethod.setParameter("password", password);
postMethod.setParameter("userName", user);
httpClient.executeMethod(postMethod);
LOG.info("{} - {}", postMethod.getStatusCode(), postMethod.getStatusText());
Pattern pattern = Pattern.compile("JSESSIONID=([a-zA-Z0-9-]*)");
Header[] setCookieHeaders = postMethod.getResponseHeaders("Set-Cookie");
for (Header setCookie : setCookieHeaders) {
java.util.regex.Matcher matcher = pattern.matcher(setCookie.toString());
if (matcher.find()) {
return matcher.group(1);
}
}
return StringUtils.EMPTY;
}
use of org.apache.commons.httpclient.Header 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.Header in project openhab1-addons by openhab.
the class Telegram method sendTelegram.
@ActionDoc(text = "Sends a Telegram via Telegram REST API - direct message")
public static boolean sendTelegram(@ParamDoc(name = "group") String group, @ParamDoc(name = "message") String message) {
if (groupTokens.get(group) == null) {
logger.error("Bot '{}' not defined, action skipped", group);
return false;
}
String url = String.format(TELEGRAM_URL, groupTokens.get(group).getToken());
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(url);
postMethod.getParams().setContentCharset("UTF-8");
postMethod.getParams().setSoTimeout(HTTP_TIMEOUT);
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
NameValuePair[] data = { new NameValuePair("chat_id", groupTokens.get(group).getChatId()), new NameValuePair("text", message) };
postMethod.setRequestBody(data);
try {
int statusCode = client.executeMethod(postMethod);
if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
return true;
}
if (statusCode != HttpStatus.SC_OK) {
logger.warn("Method failed: {}", postMethod.getStatusLine());
return false;
}
InputStream tmpResponseStream = postMethod.getResponseBodyAsStream();
Header encodingHeader = postMethod.getResponseHeader("Content-Encoding");
if (encodingHeader != null) {
for (HeaderElement ehElem : encodingHeader.getElements()) {
if (ehElem.toString().matches(".*gzip.*")) {
tmpResponseStream = new GZIPInputStream(tmpResponseStream);
logger.debug("GZipped InputStream from {}", url);
} else if (ehElem.toString().matches(".*deflate.*")) {
tmpResponseStream = new InflaterInputStream(tmpResponseStream);
logger.debug("Deflated InputStream from {}", url);
}
}
}
String responseBody = IOUtils.toString(tmpResponseStream);
if (!responseBody.isEmpty()) {
logger.debug(responseBody);
}
} catch (HttpException e) {
logger.error("Fatal protocol violation: {}", e.toString());
return false;
} catch (IOException e) {
logger.error("Fatal transport error: {}", e.toString());
return false;
} finally {
postMethod.releaseConnection();
}
return true;
}
Aggregations