use of org.apache.http.client.ClientProtocolException in project stanbol by apache.
the class RestfulLangidentEngine method computeEnhancements.
/**
* Compute enhancements for supplied ContentItem. The results of the process
* are expected to be stored in the metadata of the content item.
* <p/>
* The client (usually an {@link org.apache.stanbol.enhancer.servicesapi.EnhancementJobManager}) should take care of
* persistent storage of the enhanced {@link org.apache.stanbol.enhancer.servicesapi.ContentItem}.
* <p/>
* This method creates a new POSContentPart using {@link org.apache.stanbol.enhancer.engines.pos.api.POSTaggerHelper#createContentPart} from a text/plain part and
* stores it as a new part in the content item. The metadata is not changed.
*
* @throws org.apache.stanbol.enhancer.servicesapi.EngineException
* if the underlying process failed to work as
* expected
*/
@Override
public void computeEnhancements(final ContentItem ci) throws EngineException {
//get the plain text Blob
Map.Entry<IRI, Blob> textBlob = getPlainText(this, ci, false);
Blob blob = textBlob.getValue();
//send the text to the server
final HttpPost request = new HttpPost(serviceUrl);
request.setEntity(new InputStreamEntity(blob.getStream(), blob.getContentLength(), ContentType.create(blob.getMimeType(), blob.getParameter().get("charset"))));
//execute the request
List<LangSuggestion> detected;
try {
detected = AccessController.doPrivileged(new PrivilegedExceptionAction<List<LangSuggestion>>() {
public List<LangSuggestion> run() throws ClientProtocolException, IOException {
return httpClient.execute(request, new LangIdentResponseHandler(ci, objectMapper));
}
});
} catch (PrivilegedActionException pae) {
Exception e = pae.getException();
if (e instanceof ClientProtocolException) {
throw new EngineException(this, ci, "Exception while executing Request " + "on RESTful Language Identification Service at " + serviceUrl, e);
} else if (e instanceof IOException) {
throw new EngineException(this, ci, "Exception while executing Request " + "on RESTful Language Identification Service at " + serviceUrl, e);
} else {
throw RuntimeException.class.cast(e);
}
}
Graph metadata = ci.getMetadata();
log.debug("Detected Languages for ContentItem {} and Blob {}");
ci.getLock().writeLock().lock();
try {
//write TextAnnotations for the detected languages
for (LangSuggestion suggestion : detected) {
// add a hypothesis
log.debug(" > {}@{}", suggestion.getLanguage(), suggestion.hasProbability() ? suggestion.getProbability() : "-,--");
IRI textEnhancement = EnhancementEngineHelper.createTextEnhancement(ci, this);
metadata.add(new TripleImpl(textEnhancement, DC_LANGUAGE, new PlainLiteralImpl(suggestion.getLanguage())));
metadata.add(new TripleImpl(textEnhancement, DC_TYPE, DCTERMS_LINGUISTIC_SYSTEM));
if (suggestion.hasProbability()) {
metadata.add(new TripleImpl(textEnhancement, ENHANCER_CONFIDENCE, literalFactory.createTypedLiteral(suggestion.getProbability())));
}
}
} finally {
ci.getLock().writeLock().unlock();
}
}
use of org.apache.http.client.ClientProtocolException in project geode by apache.
the class RestAPIsAndInterOpsDUnitTest method fetchRestServerEndpoints.
public void fetchRestServerEndpoints(String restEndpoint) {
HttpGet get = new HttpGet(restEndpoint + "/servers");
get.addHeader("Content-Type", "application/json");
get.addHeader("Accept", "application/json");
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response;
try {
response = httpclient.execute(get);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
StringBuffer str = new StringBuffer();
while ((line = reader.readLine()) != null) {
str.append(line);
}
// validate the satus code
assertEquals(response.getStatusLine().getStatusCode(), 200);
if (response.getStatusLine().getStatusCode() == 200) {
JSONArray jsonArray = new JSONArray(str.toString());
// verify total number of REST service endpoints in DS
assertEquals(jsonArray.length(), 2);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
fail(" Rest Request should not have thrown ClientProtocolException!");
} catch (IOException e) {
e.printStackTrace();
fail(" Rest Request should not have thrown IOException!");
} catch (JSONException e) {
e.printStackTrace();
fail(" Rest Request should not have thrown JSONException!");
}
}
use of org.apache.http.client.ClientProtocolException in project opennms by OpenNMS.
the class HttpNorthbounder method forwardAlarms.
/* (non-Javadoc)
* @see org.opennms.netmgt.alarmd.api.support.AbstractNorthbounder#forwardAlarms(java.util.List)
*/
@Override
public void forwardAlarms(List<NorthboundAlarm> alarms) throws NorthbounderException {
LOG.info("Forwarding {} alarms", alarms.size());
// Need a configuration bean for these
int connectionTimeout = 3000;
int socketTimeout = 3000;
Integer retryCount = Integer.valueOf(3);
URI uri = m_config.getURI();
final HttpClientWrapper clientWrapper = HttpClientWrapper.create().setConnectionTimeout(connectionTimeout).setSocketTimeout(socketTimeout).setRetries(retryCount).useBrowserCompatibleCookies();
if (m_config.getVirtualHost() != null && !m_config.getVirtualHost().trim().isEmpty()) {
clientWrapper.setVirtualHost(m_config.getVirtualHost());
}
if (m_config.getUserAgent() != null && !m_config.getUserAgent().trim().isEmpty()) {
clientWrapper.setUserAgent(m_config.getUserAgent());
}
if ("https".equals(uri.getScheme())) {
try {
clientWrapper.useRelaxedSSL("https");
} catch (final GeneralSecurityException e) {
throw new NorthbounderException("Failed to configure HTTP northbounder for relaxed SSL.", e);
}
}
HttpUriRequest method = null;
if (HttpMethod.POST == (m_config.getMethod())) {
HttpPost postMethod = new HttpPost(uri);
// TODO: need to configure these
List<NameValuePair> postParms = new ArrayList<>();
// FIXME:do this for now
NameValuePair p = new BasicNameValuePair("foo", "bar");
postParms.add(p);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParms, StandardCharsets.UTF_8);
postMethod.setEntity(formEntity);
HttpEntity entity = null;
try {
// I have no idea what I'm doing here ;)
entity = new StringEntity("XML HERE");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
postMethod.setEntity(entity);
method = postMethod;
} else if (HttpMethod.GET == m_config.getMethod()) {
// TODO: need to configure these
// List<NameValuePair> getParms = null;
method = new HttpGet(uri);
}
HttpVersion httpVersion = determineHttpVersion(m_config.getHttpVersion());
clientWrapper.setVersion(httpVersion);
HttpResponse response = null;
try {
response = clientWrapper.execute(method);
int code = response.getStatusLine().getStatusCode();
HttpResponseRange range = new HttpResponseRange("200-399");
if (!range.contains(code)) {
LOG.debug("response code out of range for uri:{}. Expected {} but received {}", uri, range, code);
throw new NorthbounderException("response code out of range for uri:" + uri + ". Expected " + range + " but received " + code);
}
LOG.debug("HTTP Northbounder received response: {}", response.getStatusLine().getReasonPhrase());
} catch (final ClientProtocolException e) {
throw new NorthbounderException(e);
} catch (final IOException e) {
throw new NorthbounderException(e);
} finally {
IOUtils.closeQuietly(clientWrapper);
}
}
use of org.apache.http.client.ClientProtocolException in project jo-client-platform by jo-source.
the class MessageBrokerTest method testPostWithServerError.
@Test
public void testPostWithServerError() throws ClientProtocolException, IOException, InterruptedException {
final String expectedResultMessage = "RESULT_MESSAGE";
final MessageStub requestMessage = new MessageStub(expectedResultMessage);
final int postErrorCount = 5;
final int messageCount = 5;
final HttpClientStub httpClient = new HttpClientStub(messageCount, 0);
httpClient.setPostStatus(HttpClientStub.INTERNAL_SERVER_ERROR_STATUS_LINE);
final ScheduledExecutorServiceMock executor = new ScheduledExecutorServiceMock();
final AtomicReference<JUnitLogger> senderThreadLoggerRef = new AtomicReference<JUnitLogger>(null);
final AtomicReference<JUnitLogger> receiverThreadLoggerRef = new AtomicReference<JUnitLogger>(null);
final MessageBrokerBuilder builder = new MessageBrokerBuilder(BROKER_ID);
builder.setUrl(DEFAULT_URL);
builder.setHttpClient(httpClient);
builder.setIncommingMessageExecutor(executor);
builder.setSleepDurationMillisAfterIoException(0);
builder.setHttpRequestInitializer(new IHttpRequestInitializer() {
@Override
public void initialize(final HttpRequest httpRequest) {
if (Thread.currentThread().getName().contains("messageSender")) {
prepareLoggerForThreadAndDisableConsole(senderThreadLoggerRef);
} else {
prepareLoggerForThreadAndDisableConsole(receiverThreadLoggerRef);
}
}
});
final IMessageBroker messageBroker = builder.build();
final IMessageReceiver receiver = Mockito.mock(IMessageReceiver.class);
messageBroker.setReceiver(receiver);
for (int i = 0; i < postErrorCount; i++) {
messageBroker.getChannel().send(requestMessage, null);
}
while (httpClient.getPostInvocationCount() < postErrorCount) {
// do nothing
}
final IExceptionCallback exceptionCallback = Mockito.mock(IExceptionCallback.class);
for (int i = 0; i < postErrorCount; i++) {
messageBroker.getChannel().send(requestMessage, exceptionCallback);
}
while (httpClient.getPostInvocationCount() < postErrorCount * 2) {
// do nothing
}
// now fix error and send some messages with success
httpClient.setPostStatus(HttpClientStub.OK_STATUS_LINE);
for (int i = 0; i < messageCount; i++) {
messageBroker.getChannel().send(requestMessage, exceptionCallback);
}
Assert.assertTrue(httpClient.awaitMessagesConsumed(SYNC_TIMEOUT, TimeUnit.MILLISECONDS));
executor.executeEvents();
Mockito.verify(receiver, Mockito.times(messageCount)).onMessage(expectedResultMessage, messageBroker.getChannel());
Assert.assertTrue(messageBroker.shutdown(SYNC_TIMEOUT));
Mockito.verify(httpClient.getConnectionManager(), Mockito.times(1)).shutdown();
Assert.assertEquals(2 * postErrorCount + messageCount, httpClient.getPostInvocationCount());
Assert.assertEquals(postErrorCount, senderThreadLoggerRef.get().getMessageCount());
Mockito.verify(exceptionCallback, Mockito.times(postErrorCount)).exception(Mockito.any(Exception.class));
Assert.assertEquals(0, receiverThreadLoggerRef.get().getMessageCount());
}
use of org.apache.http.client.ClientProtocolException in project vcell by virtualcell.
the class VCellApiClient method sendLostPassword.
public void sendLostPassword(String userid) throws ClientProtocolException, IOException {
HttpPost httppost = new HttpPost("https://" + httpHost.getHostName() + ":" + httpHost.getPort() + "/lostpassword");
StringEntity input = new StringEntity(userid);
input.setContentType(ContentType.TEXT_PLAIN.getMimeType());
httppost.setEntity(input);
if (lg.isLoggable(Level.INFO)) {
lg.info("Executing request to send lost password " + httppost.getRequestLine());
}
ResponseHandler<String> handler = new ResponseHandler<String>() {
public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_ACCEPTED) {
HttpEntity entity = response.getEntity();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()))) {
String message = reader.lines().collect(Collectors.joining());
return message;
}
} else {
HttpEntity entity = response.getEntity();
String message = null;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()))) {
message = reader.lines().collect(Collectors.joining());
}
throw new ClientProtocolException("Failed to request lost password, response status: " + status + "\nreason: " + message);
}
}
};
String message = httpclient.execute(httppost, handler, httpClientContext);
if (lg.isLoggable(Level.INFO)) {
lg.info("requested lost password for user " + userid + ", server returned " + message);
}
}
Aggregations