Search in sources :

Example 76 with HttpResponseException

use of org.apache.http.client.HttpResponseException in project android-sms-relay by nyaruka.

the class RelayService method sendMessageToServer.

/**
 * Sends a message to our server.
 * @param msg
 */
public void sendMessageToServer(TextMessage msg) throws IOException {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    String receiveURL = prefs.getString("receive_url", null);
    boolean process_outgoing = prefs.getBoolean("process_outgoing", false);
    TextMessageHelper helper = getHelper();
    Log.d(TAG, "Receive URL: " + receiveURL);
    // no delivery url means we don't do anything
    if (receiveURL == null || receiveURL.length() == 0) {
        return;
    }
    String url = receiveURL + "&sender=" + URLEncoder.encode(msg.number) + "&message=" + URLEncoder.encode(msg.text);
    Log.d(TAG, "Sending: " + url);
    try {
        String content = fetchURL(url);
        if (content.trim().length() > 0) {
            JSONObject json = new JSONObject(content);
            // if we are supposed to process outgoing messages, then read any responses
            if (process_outgoing) {
                JSONArray responses = json.getJSONArray("responses");
                for (int i = 0; i < responses.length(); i++) {
                    JSONObject response = responses.getJSONObject(i);
                    String number = "+" + response.getString("contact");
                    String message = response.getString("text");
                    long serverId = response.getLong("id");
                    if ("O".equals(response.getString("direction")) && "Q".equals(response.getString("status"))) {
                        // if this message doesn't already exist
                        TextMessage existing = helper.withServerId(this.getApplicationContext(), serverId);
                        if (existing == null) {
                            Log.d(TAG, "Got reply: " + serverId + ": " + message);
                            TextMessage toSend = new TextMessage(number, message, serverId);
                            helper.createMessage(toSend);
                            sendMessage(toSend);
                        }
                    }
                }
            }
        }
        msg.status = TextMessage.HANDLED;
        msg.error = null;
        Log.d(TAG, "Msg '" + msg.text + "' handed to server.");
    } catch (HttpResponseException e) {
        Log.d(TAG, "HTTP ERROR Got Error: " + e.getMessage(), e);
        msg.error = e.getClass().getSimpleName() + ": " + e.getMessage();
        msg.status = TextMessage.ERRORED;
    } catch (IOException e) {
        msg.error = e.getClass().getSimpleName() + ": " + e.getMessage();
        msg.status = TextMessage.ERRORED;
        throw e;
    } catch (Throwable t) {
        Log.d(TAG, "THROWABLE Got Error: " + t.getMessage(), t);
        msg.error = t.getClass().getSimpleName() + ": " + t.getMessage();
        msg.status = TextMessage.ERRORED;
    } finally {
        helper.updateMessage(msg);
        MainActivity.updateMessage(msg);
    }
}
Also used : JSONObject(org.json.JSONObject) SharedPreferences(android.content.SharedPreferences) JSONArray(org.json.JSONArray) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) TextMessage(com.nyaruka.androidrelay.data.TextMessage) TextMessageHelper(com.nyaruka.androidrelay.data.TextMessageHelper)

Example 77 with HttpResponseException

use of org.apache.http.client.HttpResponseException in project ArTEMiS by ls1intum.

the class LtiService method onNewBuildResult.

/**
 * This method is pinged on new build results.
 * It sends an message to the LTI consumer with the new score.
 *
 * @param participation
 */
public void onNewBuildResult(Participation participation) {
    // Get the LTI outcome URL
    Optional<LtiOutcomeUrl> ltiOutcomeUrl = ltiOutcomeUrlRepository.findByUserAndExercise(participation.getStudent(), participation.getExercise());
    ltiOutcomeUrl.ifPresent(ltiOutcomeUrl1 -> {
        String score = "0.00";
        // Get the latest result
        Optional<Result> latestResult = resultRepository.findFirstByParticipationIdOrderByCompletionDateDesc(participation.getId());
        if (latestResult.isPresent() && latestResult.get().getScore() != null) {
            // LTI scores needs to be formatted as String between "0.00" and "1.00"
            score = String.format(Locale.ROOT, "%.2f", latestResult.get().getScore().floatValue() / 100);
        }
        log.debug("Reporting to LTI consumer: Score {} for Participation {}", score, participation);
        try {
            // Using PatchedIMSPOXRequest until they fixed the problem: https://github.com/IMSGlobal/basiclti-util-java/issues/27
            HttpPost request = PatchedIMSPOXRequest.buildReplaceResult(ltiOutcomeUrl1.getUrl(), OAUTH_KEY, OAUTH_SECRET, ltiOutcomeUrl1.getSourcedId(), score, null, false);
            HttpClient client = HttpClientBuilder.create().build();
            HttpResponse response = client.execute(request);
            String responseString = new BasicResponseHandler().handleResponse(response);
            log.debug("Response from LTI consumer: {}", responseString);
            if (response.getStatusLine().getStatusCode() >= 400) {
                throw new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
            }
        } catch (Exception e) {
            log.error("Reporting to LTI consumer failed: {}", e);
        }
    });
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpClient(org.apache.http.client.HttpClient) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) HttpResponse(org.apache.http.HttpResponse) HttpResponseException(org.apache.http.client.HttpResponseException) LtiVerificationException(org.imsglobal.lti.launch.LtiVerificationException) InternalAuthenticationServiceException(org.springframework.security.authentication.InternalAuthenticationServiceException) AuthenticationException(org.springframework.security.core.AuthenticationException) HttpResponseException(org.apache.http.client.HttpResponseException) ArtemisAuthenticationException(de.tum.in.www1.artemis.exception.ArtemisAuthenticationException) LtiVerificationResult(org.imsglobal.lti.launch.LtiVerificationResult)

Example 78 with HttpResponseException

use of org.apache.http.client.HttpResponseException in project cloudstack by apache.

the class SspClient method executeMethod.

private String executeMethod(HttpRequestBase req, String path) {
    try {
        URI base = new URI(apiUrl);
        req.setURI(new URI(base.getScheme(), base.getUserInfo(), base.getHost(), base.getPort(), path, null, null));
    } catch (URISyntaxException e) {
        s_logger.error("invalid API URL " + apiUrl + " path " + path, e);
        return null;
    }
    try {
        String content = null;
        try {
            content = getHttpClient().execute(req, new BasicResponseHandler());
            s_logger.info("ssp api call: " + req);
        } catch (HttpResponseException e) {
            s_logger.info("ssp api call failed: " + req, e);
            if (e.getStatusCode() == HttpStatus.SC_UNAUTHORIZED && login()) {
                req.reset();
                content = getHttpClient().execute(req, new BasicResponseHandler());
                s_logger.info("ssp api retry call: " + req);
            }
        }
        return content;
    } catch (ClientProtocolException e) {
        // includes HttpResponseException
        s_logger.error("ssp api call failed: " + req, e);
    } catch (IOException e) {
        s_logger.error("ssp api call failed: " + req, e);
    }
    return null;
}
Also used : BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) HttpResponseException(org.apache.http.client.HttpResponseException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 79 with HttpResponseException

use of org.apache.http.client.HttpResponseException in project Libraries-for-Android-Developers by eoecn.

the class AsyncHttpResponseHandler method sendResponseMessage.

@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    // do not process if request has been cancelled
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        byte[] responseBody;
        responseBody = getResponseData(response.getEntity());
        // additional cancellation check as getResponseData() can take non-zero time to process
        if (!Thread.currentThread().isInterrupted()) {
            if (status.getStatusCode() >= 300) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
            } else {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
            }
        }
    }
}
Also used : StatusLine(org.apache.http.StatusLine) HttpResponseException(org.apache.http.client.HttpResponseException)

Example 80 with HttpResponseException

use of org.apache.http.client.HttpResponseException in project Libraries-for-Android-Developers by eoecn.

the class BinaryHttpResponseHandler method sendResponseMessage.

@Override
public final void sendResponseMessage(HttpResponse response) throws IOException {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    if (contentTypeHeaders.length != 1) {
        // malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), "None, or more than one, Content-Type Header found!"));
        return;
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : getAllowedContentTypes()) {
        try {
            if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
                foundAllowedContentType = true;
            }
        } catch (PatternSyntaxException e) {
            Log.e("BinaryHttpResponseHandler", "Given pattern is not valid: " + anAllowedContentType, e);
        }
    }
    if (!foundAllowedContentType) {
        // Content-Type not in allowed list, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"));
        return;
    }
    super.sendResponseMessage(response);
}
Also used : StatusLine(org.apache.http.StatusLine) Header(org.apache.http.Header) HttpResponseException(org.apache.http.client.HttpResponseException) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Aggregations

HttpResponseException (org.apache.http.client.HttpResponseException)82 IOException (java.io.IOException)32 StatusLine (org.apache.http.StatusLine)30 HttpEntity (org.apache.http.HttpEntity)25 HttpGet (org.apache.http.client.methods.HttpGet)14 HttpResponse (org.apache.http.HttpResponse)13 BasicResponseHandler (org.apache.http.impl.client.BasicResponseHandler)11 Header (org.apache.http.Header)9 ClientProtocolException (org.apache.http.client.ClientProtocolException)9 URISyntaxException (java.net.URISyntaxException)8 ArrayList (java.util.ArrayList)8 URI (java.net.URI)7 Document (org.jsoup.nodes.Document)7 Test (org.junit.Test)7 InputStream (java.io.InputStream)6 Expectations (mockit.Expectations)5 HttpClient (org.apache.http.client.HttpClient)5 Element (org.jsoup.nodes.Element)5 SubstitutionSchedule (me.vertretungsplan.objects.SubstitutionSchedule)4 HttpPost (org.apache.http.client.methods.HttpPost)4