Search in sources :

Example 41 with ClientProtocolException

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();
    }
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) HttpPost(org.apache.http.client.methods.HttpPost) Blob(org.apache.stanbol.enhancer.servicesapi.Blob) PrivilegedActionException(java.security.PrivilegedActionException) PlainLiteralImpl(org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl) EngineException(org.apache.stanbol.enhancer.servicesapi.EngineException) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) IOException(java.io.IOException) EngineException(org.apache.stanbol.enhancer.servicesapi.EngineException) URISyntaxException(java.net.URISyntaxException) ConfigurationException(org.osgi.service.cm.ConfigurationException) HttpException(org.apache.http.HttpException) ClientProtocolException(org.apache.http.client.ClientProtocolException) PrivilegedActionException(java.security.PrivilegedActionException) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) InputStreamEntity(org.apache.http.entity.InputStreamEntity) ClientProtocolException(org.apache.http.client.ClientProtocolException) Graph(org.apache.clerezza.commons.rdf.Graph) TripleImpl(org.apache.clerezza.commons.rdf.impl.utils.TripleImpl) Map(java.util.Map) HashMap(java.util.HashMap)

Example 42 with ClientProtocolException

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!");
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpEntity(org.apache.http.HttpEntity) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) BufferedReader(java.io.BufferedReader)

Example 43 with ClientProtocolException

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);
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpEntity(org.apache.http.HttpEntity) GeneralSecurityException(java.security.GeneralSecurityException) HttpGet(org.apache.http.client.methods.HttpGet) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) URI(java.net.URI) ClientProtocolException(org.apache.http.client.ClientProtocolException) HttpResponseRange(org.opennms.core.utils.HttpResponseRange) StringEntity(org.apache.http.entity.StringEntity) NorthbounderException(org.opennms.netmgt.alarmd.api.NorthbounderException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HttpClientWrapper(org.opennms.core.web.HttpClientWrapper) HttpVersion(org.apache.http.HttpVersion)

Example 44 with ClientProtocolException

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());
}
Also used : HttpRequest(org.apache.http.HttpRequest) ScheduledExecutorServiceMock(org.jowidgets.util.mock.ScheduledExecutorServiceMock) AtomicReference(java.util.concurrent.atomic.AtomicReference) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) JUnitLogger(org.jowidgets.logging.tools.JUnitLogger) IMessageReceiver(org.jowidgets.message.api.IMessageReceiver) IExceptionCallback(org.jowidgets.message.api.IExceptionCallback) Test(org.junit.Test)

Example 45 with ClientProtocolException

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);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) HttpResponse(org.apache.http.HttpResponse) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Aggregations

ClientProtocolException (org.apache.http.client.ClientProtocolException)92 IOException (java.io.IOException)80 HttpResponse (org.apache.http.HttpResponse)49 HttpPost (org.apache.http.client.methods.HttpPost)37 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)30 HttpClient (org.apache.http.client.HttpClient)29 HttpGet (org.apache.http.client.methods.HttpGet)25 HttpEntity (org.apache.http.HttpEntity)23 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)20 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)19 InputStreamReader (java.io.InputStreamReader)18 ArrayList (java.util.ArrayList)18 UnsupportedEncodingException (java.io.UnsupportedEncodingException)17 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)14 BufferedReader (java.io.BufferedReader)13 InputStream (java.io.InputStream)13 NameValuePair (org.apache.http.NameValuePair)13 StringEntity (org.apache.http.entity.StringEntity)12 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)11 URI (java.net.URI)10