use of org.apache.http.client.methods.HttpRequestBase in project gocd by gocd.
the class RemoteRegistrationRequesterTest method hasAllParams.
private TypeSafeMatcher<HttpRequestBase> hasAllParams(final String uuid, final String elasticAgentId, final String elasticPluginId) {
return new TypeSafeMatcher<HttpRequestBase>() {
@Override
public boolean matchesSafely(HttpRequestBase item) {
try {
HttpEntityEnclosingRequestBase postMethod = (HttpEntityEnclosingRequestBase) item;
List<NameValuePair> params = URLEncodedUtils.parse(postMethod.getEntity());
assertThat(getParameter(params, "hostname"), is("cruise.com"));
assertThat(getParameter(params, "uuid"), is(uuid));
String workingDir = SystemUtil.currentWorkingDirectory();
assertThat(getParameter(params, "location"), is(workingDir));
assertThat(getParameter(params, "operatingSystem"), not(nullValue()));
assertThat(getParameter(params, "agentAutoRegisterKey"), is("t0ps3cret"));
assertThat(getParameter(params, "agentAutoRegisterResources"), is("linux, java"));
assertThat(getParameter(params, "agentAutoRegisterEnvironments"), is("uat, staging"));
assertThat(getParameter(params, "agentAutoRegisterHostname"), is("agent01.example.com"));
assertThat(getParameter(params, "elasticAgentId"), is(elasticAgentId));
assertThat(getParameter(params, "elasticPluginId"), is(elasticPluginId));
return true;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private String getParameter(List<NameValuePair> params, String paramName) {
for (NameValuePair param : params) {
if (param.getName().equals(paramName)) {
return param.getValue();
}
}
return null;
}
public void describeTo(Description description) {
description.appendText("params containing");
}
};
}
use of org.apache.http.client.methods.HttpRequestBase in project opennms by OpenNMS.
the class HttpCollector method buildHttpMethod.
private static HttpRequestBase buildHttpMethod(final HttpCollectorAgent collectorAgent) throws URISyntaxException {
HttpRequestBase method;
final URI uri = buildUri(collectorAgent);
final Url url = collectorAgent.getUriDef().getUrl();
if ("GET".equals(url.getMethod())) {
method = buildGetMethod(uri, collectorAgent);
} else {
method = buildPostMethod(uri, collectorAgent);
}
if (url.getVirtualHost().isPresent()) {
final String virtualHost = url.getVirtualHost().get();
if (!virtualHost.trim().isEmpty()) {
method.setHeader(HTTP.TARGET_HOST, virtualHost);
}
}
return method;
}
use of org.apache.http.client.methods.HttpRequestBase in project opennms by OpenNMS.
the class HttpUrlConnection method getInputStream.
/* (non-Javadoc)
* @see java.net.URLConnection#getInputStream()
*/
@Override
public InputStream getInputStream() throws IOException {
try {
if (m_clientWrapper == null) {
connect();
}
// Build URL
int port = m_url.getPort() > 0 ? m_url.getPort() : m_url.getDefaultPort();
URIBuilder ub = new URIBuilder();
ub.setPort(port);
ub.setScheme(m_url.getProtocol());
ub.setHost(m_url.getHost());
ub.setPath(m_url.getPath());
if (m_url.getQuery() != null && !m_url.getQuery().trim().isEmpty()) {
final List<NameValuePair> params = URLEncodedUtils.parse(m_url.getQuery(), StandardCharsets.UTF_8);
if (!params.isEmpty()) {
ub.addParameters(params);
}
}
// Build Request
HttpRequestBase request = null;
if (m_request != null && m_request.getMethod().equalsIgnoreCase("post")) {
final Content cnt = m_request.getContent();
HttpPost post = new HttpPost(ub.build());
ContentType contentType = ContentType.create(cnt.getType());
LOG.info("Processing POST request for {}", contentType);
if (contentType.getMimeType().equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
FormFields fields = JaxbUtils.unmarshal(FormFields.class, cnt.getData());
post.setEntity(fields.getEntity());
} else {
StringEntity entity = new StringEntity(cnt.getData(), contentType);
post.setEntity(entity);
}
request = post;
} else {
request = new HttpGet(ub.build());
}
if (m_request != null) {
// Add Custom Headers
for (final Header header : m_request.getHeaders()) {
request.addHeader(header.getName(), header.getValue());
}
}
// Get Response
CloseableHttpResponse response = m_clientWrapper.execute(request);
return response.getEntity().getContent();
} catch (Exception e) {
throw new IOException("Can't retrieve " + m_url.getPath() + " from " + m_url.getHost() + " because " + e.getMessage(), e);
}
}
use of org.apache.http.client.methods.HttpRequestBase in project tdi-studio-se by Talend.
the class DynamicsCRMClient method createAndExecuteRequest.
/**
* Created and executes a request
*
* @param uri the request URI
* @param httpEntity the entity to send.
* @param method HTTP method
*
* @return the response to the request.
* @throws ServiceUnavailableException
*/
protected HttpResponse createAndExecuteRequest(URI uri, HttpEntity httpEntity, HttpMethod method) throws ServiceUnavailableException {
boolean hasRetried = false;
while (true) {
try {
httpClient = (DefaultHttpClient) httpClientFactory.create(null, null);
HttpRequestBase request = null;
if (method == HttpMethod.POST) {
request = new HttpPost(uri);
} else if (method == HttpMethod.PATCH) {
request = new HttpPatch(uri);
} else if (method == HttpMethod.DELETE) {
request = new HttpDelete(uri);
} else {
throw new HttpClientException("Unsupported operation:" + method);
}
request.addHeader(HttpHeader.AUTHORIZATION, "Bearer " + authResult.getAccessToken());
if (request instanceof HttpEntityEnclosingRequestBase) {
((HttpEntityEnclosingRequestBase) request).setEntity(httpEntity);
}
HttpResponse response = httpClient.execute(request);
if (isResponseSuccess(response.getStatusLine().getStatusCode())) {
request.releaseConnection();
EntityUtils.consume(response.getEntity());
return response;
} else {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED && !hasRetried) {
refreshToken();
hasRetried = true;
continue;
}
HttpEntity entity = response.getEntity();
String message = null;
if (entity != null) {
message = odataClient.getDeserializer(ContentType.JSON).toError(entity.getContent()).getMessage();
} else {
message = response.getStatusLine().getReasonPhrase();
}
throw new HttpClientException(message);
}
} catch (Exception e) {
throw new HttpClientException(e);
}
}
}
use of org.apache.http.client.methods.HttpRequestBase in project newsrob by marianokamp.
the class GRAnsweredBadRequestException method getStateChangesFromGR.
private Collection<StateChange> getStateChangesFromGR(long lastUpdated) throws IOException, ParserConfigurationException, SAXException, GRTokenExpiredException, GRAnsweredBadRequestException {
Timing t = new Timing("EntriesRetriever.getStateChangesFromGR()", context);
String url = getGoogleHost() + "/reader/api/0/stream/items/ids";
// &s=deleted/user/-/state/com.google/starred";
url += "?s=user/-/state/com.google/starred";
url += "&s=user/-/state/com.google/read";
url += "&s=" + NEWSROB_PINNED_STATE;
// &s=deleted/user/-/state/com.google/read";
url += "&n=10000&ot=" + lastUpdated;
NewsRobHttpClient httpClient = NewsRobHttpClient.newInstance(false, context);
try {
HttpRequestBase req = createGRRequest(httpClient, url);
HttpResponse response = executeGRRequest(httpClient, req, true);
throwExceptionWhenNotStatusOK(response);
final List<StateChange> stateChanges = new ArrayList<StateChange>(25);
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
SAXParser parser = saxParserFactory.newSAXParser();
DefaultHandler handler = new SimpleStringExtractorHandler() {
private String currentAtomId;
// cache
String googleUserId = null;
@Override
public void receivedString(String localName, String fqn, String s) {
if ("number".equals(localName)) {
long l = Long.parseLong(s);
currentAtomId = TAG_GR_ITEM + U.longToHex(l);
} else if ("string".equals(localName)) {
boolean delete = s.startsWith("delete");
int state = -1;
if (s.endsWith("read"))
state = EntriesRetriever.StateChange.STATE_READ;
else if (s.endsWith("starred"))
state = EntriesRetriever.StateChange.STATE_STARRED;
if (state > -1) {
EntriesRetriever.StateChange sc = new EntriesRetriever.StateChange(currentAtomId, state, delete ? EntriesRetriever.StateChange.OPERATION_REMOVE : EntriesRetriever.StateChange.OPERATION_ADD);
stateChanges.add(sc);
}
}
}
};
parser.parse(NewsRobHttpClient.getUngzippedContent(response.getEntity(), context), handler);
PL.log("Entries Retriever: Number of state changes=" + stateChanges.size(), context);
if (NewsRob.isDebuggingEnabled(context))
PL.log("State Changes: " + stateChanges, context);
return stateChanges;
} finally {
httpClient.close();
t.stop();
}
}
Aggregations