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);
}
}
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);
}
});
}
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;
}
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);
}
}
}
}
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);
}
Aggregations