use of org.apache.http.protocol.BasicHttpContext in project triplea by triplea-game.
the class AxisAndAlliesForumPoster method login.
/**
* Logs into axisandallies.org
* nb: Username and password are posted in clear text
*
* @throws Exception
* if login fails
*/
private HttpContext login(final CloseableHttpClient client) throws Exception {
final HttpPost httpPost = new HttpPost(UrlConstants.AXIS_AND_ALLIES_FORUM + "?action=login2");
final CookieStore cookieStore = new BasicCookieStore();
final HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
HttpProxy.addProxy(httpPost);
httpPost.addHeader("Accept", "*/*");
httpPost.addHeader("Accept-Language", "en-us");
httpPost.addHeader("Cache-Control", "no-cache");
final List<NameValuePair> parameters = new ArrayList<>(2);
parameters.add(new BasicNameValuePair("user", getUsername()));
parameters.add(new BasicNameValuePair("passwrd", getPassword()));
httpPost.setEntity(new UrlEncodedFormEntity(parameters, StandardCharsets.UTF_8));
try (CloseableHttpResponse response = client.execute(httpPost, httpContext)) {
int status = response.getStatusLine().getStatusCode();
if (status == HttpURLConnection.HTTP_OK) {
final String body = EntityUtils.toString(response.getEntity());
if (body.toLowerCase().contains("password incorrect")) {
throw new Exception("Incorrect Password");
}
// site responds with 200, and a refresh header
final Header refreshHeader = response.getFirstHeader("Refresh");
if (refreshHeader == null) {
throw new Exception("Missing refresh header after login");
}
// refresh: 0; URL=http://...
final String value = refreshHeader.getValue();
final Pattern p = Pattern.compile("[^;]*;\\s*url=(.*)", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
final Matcher m = p.matcher(value);
if (m.matches()) {
final String url = m.group(1);
final HttpGet httpGet = new HttpGet(url);
HttpProxy.addProxy(httpGet);
try (CloseableHttpResponse response2 = client.execute(httpGet, httpContext)) {
status = response2.getStatusLine().getStatusCode();
if (status != 200) {
// something is probably wrong, but there is not much we can do about it, we handle errors when we post
}
}
} else {
throw new Exception("The refresh header didn't contain a URL");
}
} else {
throw new Exception("Failed to login to forum, server responded with status code: " + status);
}
}
return httpContext;
}
use of org.apache.http.protocol.BasicHttpContext in project jmeter-plugins-manager by undera.
the class JARSourceHTTP method getJAR.
@Override
public DownloadResult getJAR(final String id, String location, final GenericCallback<String> callback) throws IOException {
URI url = URI.create(location);
log.info("Downloading: " + url);
callback.notify("Downloading " + id + "...");
HttpGet httpget = new HttpGet(url);
HttpContext context = new BasicHttpContext();
HttpResponse response = execute(httpget, context);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
log.error("Error downloading url:" + url + " got response code:" + response.getStatusLine().getStatusCode());
EntityUtils.consumeQuietly(response.getEntity());
throw new IOException(response.getStatusLine().toString());
}
HttpEntity entity = response.getEntity();
File tempFile = File.createTempFile(id, ".jar");
final long size = entity.getContentLength();
try (InputStream inputStream = entity.getContent();
OutputStream fos = new FileOutputStream(tempFile);
BufferedOutputStream bos = new BufferedOutputStream(fos)) {
copyLarge(inputStream, bos, new GenericCallback<Long>() {
@Override
public void notify(Long progress) {
callback.notify(String.format("Downloading %s: %d%%", id, 100 * progress / size));
}
});
callback.notify("Downloaded " + id + "...");
Header cd = response.getLastHeader("Content-Disposition");
String filename;
if (cd != null) {
filename = cd.getValue().split(";")[1].split("=")[1];
if (filename.length() > 2 && filename.startsWith("\"") && filename.endsWith("\"")) {
filename = filename.substring(1, filename.length() - 1);
}
} else {
HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
String currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString() : (currentHost.toURI() + currentReq.getURI());
filename = FilenameUtils.getName(currentUrl);
}
return new DownloadResult(tempFile.getPath(), filename);
}
}
use of org.apache.http.protocol.BasicHttpContext in project joynr by bmwcarit.
the class HttpMessageSender method sendMessage.
public void sendMessage(ChannelAddress address, byte[] serializedMessage, SuccessAction successAction, FailureAction failureAction) {
// check if messageReceiver is ready to receive replies otherwise delay request by at least 100 ms
if (!messageReceiver.isReady()) {
long delay_ms = DELAY_RECEIVER_NOT_STARTED_MS;
failureAction.execute(new JoynrDelayMessageException(delay_ms, RECEIVER_NOT_STARTED_REASON));
}
String sendUrl = urlResolver.getSendUrl(address.getMessagingEndpointUrl());
logger.trace("SENDING: channelId: {} message: {}", sendUrl, serializedMessage);
HttpContext context = new BasicHttpContext();
// execute http command to send
CloseableHttpResponse response = null;
try {
HttpPost httpPost = httpRequestFactory.createHttpPost(URI.create(sendUrl));
httpPost.addHeader(new BasicHeader(httpConstants.getHEADER_CONTENT_TYPE(), httpConstants.getAPPLICATION_JSON() + ";charset=UTF-8"));
httpPost.setEntity(new ByteArrayEntity(serializedMessage));
// Clone the default config
Builder requestConfigBuilder = RequestConfig.copy(defaultRequestConfig);
requestConfigBuilder.setConnectionRequestTimeout(httpConstants.getSEND_MESSAGE_REQUEST_TIMEOUT());
httpPost.setConfig(requestConfigBuilder.build());
response = httpclient.execute(httpPost, context);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
String statusText = statusLine.getReasonPhrase();
switch(statusCode) {
case HttpURLConnection.HTTP_OK:
case HttpURLConnection.HTTP_CREATED:
logger.trace("SENT: channelId {} message: {}", sendUrl, serializedMessage);
successAction.execute();
break;
case HttpURLConnection.HTTP_BAD_REQUEST:
HttpEntity entity = response.getEntity();
if (entity == null) {
failureAction.execute(new JoynrCommunicationException("Error in HttpMessageSender. No further reason found in message body"));
return;
}
String body = EntityUtils.toString(entity, "UTF-8");
JoynrMessagingError error = objectMapper.readValue(body, JoynrMessagingError.class);
JoynrMessagingErrorCode joynrMessagingErrorCode = JoynrMessagingErrorCode.getJoynrMessagingErrorCode(error.getCode());
logger.error(error.toString());
switch(joynrMessagingErrorCode) {
case JOYNRMESSAGINGERROR_CHANNELNOTFOUND:
failureAction.execute(new JoynrChannelMissingException("Channel does not exist. Status: " + statusCode + " error: " + error.getCode() + "reason:" + error.getReason()));
break;
default:
failureAction.execute(new JoynrCommunicationException("Error in HttpMessageSender: " + statusText + body + " error: " + error.getCode() + "reason:" + error.getReason()));
break;
}
break;
default:
failureAction.execute(new JoynrCommunicationException("Unknown Error in HttpMessageSender: " + statusText + " statusCode: " + statusCode));
break;
}
} catch (JoynrShutdownException e) {
failureAction.execute(new JoynrMessageNotSentException("Message not sent to: " + address, e));
} catch (Exception e) {
// An exception occured - this could still be a communication error (e.g Connection refused)
failureAction.execute(new JoynrCommunicationException(e.getClass().getName() + "Exception while communicating. error: " + e.getMessage()));
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
}
}
}
}
use of org.apache.http.protocol.BasicHttpContext in project fuse-karaf by jboss-fuse.
the class Olingo4TestConfiguration method getTestServiceUri.
/*
* Every request to the demo OData 4.0
* (http://services.odata.org/TripPinRESTierService) generates unique
* service URL with postfix like (S(drebz6ik9htrtrnu7tdjlwtv)) for each
* session This method makes request to the base URL and return URL with
* generated postfix
*/
protected String getTestServiceUri(String baseUrl) {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(baseUrl);
HttpContext httpContext = new BasicHttpContext();
try {
httpclient.execute(httpGet, httpContext);
} catch (IOException e) {
throw new RuntimeException("Error getting OData Test service URI using base URL:" + baseUrl);
}
HttpUriRequest currentReq = (HttpUriRequest) httpContext.getAttribute("http.request");
HttpHost currentHost = (HttpHost) httpContext.getAttribute("http.target_host");
String currentUrl = currentHost.toURI() + currentReq.getURI();
return currentUrl;
}
use of org.apache.http.protocol.BasicHttpContext in project ecf by eclipse.
the class HttpClientFileSystemBrowser method runRequest.
/* (non-Javadoc)
* @see org.eclipse.ecf.provider.filetransfer.browse.AbstractFileSystemBrowser#runRequest()
*/
protected void runRequest() throws Exception {
// $NON-NLS-1$
Trace.entering(Activator.PLUGIN_ID, DebugOptions.METHODS_ENTERING, this.getClass(), "runRequest");
setupProxies();
// set timeout
httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);
httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);
String urlString = directoryOrFile.toString();
// setup authentication
setupAuthentication(urlString);
headMethod = new HttpHead(urlString);
// $NON-NLS-1$
int maxAge = Integer.getInteger("org.eclipse.ecf.http.cache.max-age", 0).intValue();
// fix the fix for bug 249990 with bug 410813
if (maxAge == 0) {
// $NON-NLS-1$//$NON-NLS-2$
headMethod.addHeader("Cache-Control", "max-age=0");
} else if (maxAge > 0) {
// $NON-NLS-1$//$NON-NLS-2$
headMethod.addHeader("Cache-Control", "max-age=" + maxAge);
}
long lastModified = 0;
long fileLength = -1;
connectingSockets.clear();
int code = -1;
try {
// $NON-NLS-1$
Trace.trace(Activator.PLUGIN_ID, "browse=" + urlString);
httpContext = new BasicHttpContext();
httpResponse = httpClient.execute(headMethod, httpContext);
code = httpResponse.getStatusLine().getStatusCode();
// $NON-NLS-1$
Trace.trace(Activator.PLUGIN_ID, "browse resp=" + code);
// Check for NTLM proxy in response headers
// This check is to deal with bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=252002
boolean ntlmProxyFound = NTLMProxyDetector.detectNTLMProxy(httpContext);
if (ntlmProxyFound && !hasForceNTLMProxyOption())
// $NON-NLS-1$
throw new BrowseFileTransferException("HttpClient Provider is not configured to support NTLM proxy authentication.", HttpClientOptions.NTLM_PROXY_RESPONSE_CODE);
if (NTLMProxyDetector.detectSPNEGOProxy(httpContext))
// $NON-NLS-1$
throw new BrowseFileTransferException("HttpClient Provider does not support the use of SPNEGO proxy authentication.");
if (code == HttpURLConnection.HTTP_OK) {
Header contentLength = httpResponse.getLastHeader(CONTENT_LENGTH_HEADER);
if (contentLength != null) {
fileLength = Integer.parseInt(contentLength.getValue());
}
lastModified = getLastModifiedTimeFromHeader();
} else if (code == HttpURLConnection.HTTP_NOT_FOUND) {
// $NON-NLS-1$
throw new BrowseFileTransferException(NLS.bind("File not found: {0}", urlString), code);
} else if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
throw new BrowseFileTransferException(Messages.HttpClientRetrieveFileTransfer_Unauthorized, code);
} else if (code == HttpURLConnection.HTTP_FORBIDDEN) {
// $NON-NLS-1$
throw new BrowseFileTransferException("Forbidden", code);
} else if (code == HttpURLConnection.HTTP_PROXY_AUTH) {
throw new BrowseFileTransferException(Messages.HttpClientRetrieveFileTransfer_Proxy_Auth_Required, code);
} else {
throw new BrowseFileTransferException(NLS.bind(Messages.HttpClientRetrieveFileTransfer_ERROR_GENERAL_RESPONSE_CODE, new Integer(code)), code);
}
remoteFiles = new IRemoteFile[1];
remoteFiles[0] = new URLRemoteFile(lastModified, fileLength, fileID);
} catch (Exception e) {
// $NON-NLS-1$
Trace.throwing(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_THROWING, this.getClass(), "runRequest", e);
BrowseFileTransferException ex = (BrowseFileTransferException) ((e instanceof BrowseFileTransferException) ? e : new BrowseFileTransferException(NLS.bind(Messages.HttpClientRetrieveFileTransfer_EXCEPTION_COULD_NOT_CONNECT, urlString), e, code));
throw ex;
}
}
Aggregations