Skip to content

Instantly share code, notes, and snippets.

@oluies
Last active August 29, 2015 14:05
Show Gist options
  • Save oluies/35e28c06279530d97018 to your computer and use it in GitHub Desktop.
Save oluies/35e28c06279530d97018 to your computer and use it in GitHub Desktop.
package se.cehis.efsob.integration.sms;
import com.google.common.base.Ascii;
import com.google.common.base.Charsets;
import com.google.common.base.Throwables;
import com.google.common.escape.Escaper;
import com.google.common.net.UrlEscapers;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import se.cehis.efsob.common.configuration.EfsobApplicationConfiguration;
import se.cehis.efsob.integration.exception.IntegrationException;
import javax.annotation.PostConstruct;
import javax.ejb.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.soap.Node;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import se.cehis.efsob.integration.integrationentities.SMSReplyIntegrationEntity;
import java.io.IOException;
import java.io.StringReader;
import java.lang.String;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.concurrent.Future;
/**
* Created by orjan on W24140608.
*/
@Singleton
@DependsOn("EfsobApplicationConfiguration")
@Startup
@Lock(LockType.READ)
public class SMSEngine {
private static final Logger LOG = LoggerFactory.getLogger(SMSEngine.class);
@EJB
private EfsobApplicationConfiguration config;
private String host;
private String scheme;
private String path;
private int port;
private String username;
private String password;
private final Escaper pathSegmentEscaper = UrlEscapers.urlPathSegmentEscaper();
// https://sms.cg.teliasonera.com/smsextended?destinationAddress=46702020304&userData=Testmeddelande&originatingAddress=TEST&correlationId=987235723
@PostConstruct
public void init(){
String name = this.getClass().getSimpleName();
LOG.info(name + ":init");
try {
// http://localhost:8080/mockservices/rest/smsplus/smsextended
// https://sms.cg.teliasonera.com
host = config.getStringProperty(EfsobApplicationConfiguration.SMS_ENGINE_HOST,"localhost");
scheme = config.getStringProperty(EfsobApplicationConfiguration.SMS_ENGINE_SCHEME,"http");
port = Integer.parseInt(config.getStringProperty(EfsobApplicationConfiguration.SMS_ENGINE_PORT,"8080"));
path = config.getStringProperty(EfsobApplicationConfiguration.SMS_ENGINE_PATH,"/mockservices/rest/smsplus/smsextended");
username = config.getStringProperty(EfsobApplicationConfiguration.SMS_ENGINE_USERNAME,"HSF-user");
password = config.getStringProperty(EfsobApplicationConfiguration.SMS_ENGINE_PASSWORD,"test");
LOG.info(name + ":initend");
} catch (Exception e) {
LOG.error(Throwables.getStackTraceAsString(e));
}
}
/**
*
* @param toMSISDN
* @param message max length 260 chars
* @return
*/
@Asynchronous
public Future<SMSReplyIntegrationEntity> sendMessage(String toMSISDN, String message, String originatingAddress, String correlationId) throws IntegrationException {
LOG.debug("sendMessage: ...");
String reply;
try {
//https://sms.ccs.teliasonera.com/smsplus/smsextended
URIBuilder builder = new URIBuilder();
final URIBuilder uriBuilder = builder.setHost(host)
.setScheme(scheme)
.setPath(path)
.setPort(port);
DefaultHttpClient client = new DefaultHttpClient();
client.getCredentialsProvider().setCredentials(
new AuthScope(host, port),
new UsernamePasswordCredentials(username, password));
HttpPost httpPost = new HttpPost(uriBuilder.build());
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
StringBuffer entity = new StringBuffer(255);
entity.append("destinationAddress=").append(toMSISDN).append('&');
entity.append("originatingAddress=").append(originatingAddress).append('&');
entity.append("correlationId=").append(correlationId).append('&');
entity.append("userData=").append(pathSegmentEscaper.escape(message));
httpPost.setEntity(new StringEntity(entity.toString()));
LOG.debug("requestline: {}", httpPost.getRequestLine());
LOG.debug("body: {}", entity.toString());
final HttpResponse response = client.execute(httpPost);
// https://softronic.atlassian.net/wiki/display/EFSOB/Avisering+personal
int statusCode = response.getStatusLine().getStatusCode();
LOG.error("Statuscode: {}",statusCode);
if (statusCode != 200) {
throw new IntegrationException(IntegrationException.IntegrationExceptionType.INTERNAL_ERROR, "Failed with HTTP error code : " + statusCode);
}
//Get the user object from entity
final HttpEntity replyXML = response.getEntity();
reply = EntityUtils.toString(replyXML);
LOG.error("Reply {}", reply);
} catch (Exception ex){
LOG.error("HttpPost",ex);
throw new IntegrationException(IntegrationException.IntegrationExceptionType.INTERNAL_ERROR, "Failed with HTTP call " + ex.getMessage());
}
SMSReplyIntegrationEntity entity;
try {
entity = getSMSServiceReply(reply);
} catch ( Exception ex ){
LOG.error("xmlparse",ex);
throw new IntegrationException(IntegrationException.IntegrationExceptionType.INTERNAL_ERROR, "Failed with XML parse " + ex.getMessage());
}
return new AsyncResult<SMSReplyIntegrationEntity>(entity);
}
/*
*
* "<SendResponse>" +
* "<correlationId>987235723</correlationId>" +
* "<messageId>172926119</messageId>" +
* "<responseCode>0</responseCode>" +
* "<responseMessage>Success</responseMessage>" +
* "<temporaryError>false</temporaryError>" +
* "</SendResponse>";
*/
private SMSReplyIntegrationEntity getSMSServiceReply(String reply) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(reply)));
String correlationId = getValue("/SendResponse/correlationId/text()",document);
String messageId = getValue("/SendResponse/messageId/text()",document);
String responseCode = getValue("/SendResponse/responseCode/text()",document);
String responseMessage = getValue("/SendResponse/responseMessage/text()",document);
String temporaryError = getValue("/SendResponse/temporaryError/text()",document);
return new SMSReplyIntegrationEntity(correlationId,messageId,responseCode,responseMessage,temporaryError);
}
private String getValue(String path,Document document) throws Exception {
XPath xPath = XPathFactory.newInstance().newXPath();
return (String) xPath.evaluate(path, document, XPathConstants.STRING);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment