Guest User

Untitled

a guest
Apr 17th, 2018
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.25 KB | None | 0 0
  1. /**
  2. *
  3. */
  4. package no.altibox.aip.remedy.processor;
  5.  
  6. import static no.altibox.aip.remedy.routebuilder.BaseRouteBuilder.REMEDY;
  7. import static no.altibox.aip.remedy.routebuilder.BaseRouteBuilder.URL;
  8. import static no.altibox.aip.remedy.routebuilder.UpdateWorkInfoRouteBuilder.GET_BILLING_ACCOUNT_ID;
  9. import static no.altibox.aip.remedy.routebuilder.UpdateWorkInfoRouteBuilder.IS_INC_REMEDY_REQUEST;
  10. import static no.altibox.aip.remedy.routebuilder.UpdateWorkInfoRouteBuilder.IS_TASK_REMEDY_REQUEST;
  11. import static no.altibox.aip.remedy.routebuilder.UpdateWorkInfoRouteBuilder.IS_VALID_REQUEST;
  12. import static no.altibox.aip.remedy.routebuilder.UpdateWorkInfoRouteBuilder.RTE_DIRECT_REMEDY_UPDATE_INCIDENT_WORK_INFO;
  13. import static no.altibox.aip.remedy.routebuilder.UpdateWorkInfoRouteBuilder.UPDATE_WORK_INFO;
  14.  
  15. import java.io.IOException;
  16. import java.io.InputStream;
  17. import java.io.UnsupportedEncodingException;
  18. import java.util.Base64;
  19. import java.util.Iterator;
  20. import java.util.List;
  21. import java.util.Map;
  22. import java.util.Map.Entry;
  23. import java.util.regex.Matcher;
  24. import java.util.regex.Pattern;
  25.  
  26. import javax.activation.DataHandler;
  27. import javax.mail.BodyPart;
  28. import javax.mail.MessagingException;
  29. import javax.mail.Multipart;
  30. import javax.mail.internet.MimeUtility;
  31.  
  32. import org.apache.camel.CamelContext;
  33. import org.apache.camel.Exchange;
  34. import org.apache.camel.Processor;
  35. import org.apache.camel.Route;
  36. import org.apache.camel.builder.RouteBuilder;
  37. import org.apache.commons.io.IOUtils;
  38. import org.apache.commons.lang.StringUtils;
  39. import org.jboss.logging.Logger;
  40.  
  41. import no.altibox.aip.common.config.Config;
  42. import no.altibox.aip.common.config.Config.Scope;
  43. import no.altibox.aip.common.exception.AipException;
  44. import no.altibox.aip.remedy.model.updateworkinfo.UpdateWorkInfo;
  45. import no.altibox.aip.remedy.util.SpecialCharacterConverter;
  46.  
  47. /**
  48. * @author VN0070954
  49. *
  50. */
  51. public class UpdateWorkInfoProcessor implements Processor {
  52.  
  53. private static final Logger LOGGER = Logger.getLogger(UpdateWorkInfoProcessor.class);
  54. private static final String INCIDENT_NUMBER = "INC";
  55. private static final String TASK_NUMBER = "TAS";
  56. private static final String GET_PARTNERID = "getPartnerId";
  57. private static final String INBOUND_NOTIFICATION = "inboundNotification";
  58. private static final String URI_POLLING_PROTOCOL = "protocol";
  59. private static final String URI_POLLING_PORT = "port";
  60. private static final String URI_POLLING_USERNAME = "username_imap";
  61. private static final String URI_POLLING_SERVERNAME = "servername";
  62. private static final String URI_POLLING_PASSWD = "password_imap";
  63. private static final String URI_POLLING_DELAY = "delay";
  64. private static final String OSS_CALL = "ossCallForPartnerId";
  65. private static final String FROM = "From";
  66. private static final String SUBJECT = "Subject";
  67. private static final String CC = "Cc";
  68. private static final String BODY = "Body";
  69. private static final String TROUBLE_TICKET = "TroubleTicket";
  70. private static final String CUSTOMER_REPLY = "customer_reply";
  71. private static final String POLLING_ROUTE = "PollingRoute";
  72. private static final String REGULAR_EXPRESSION = "regExp";
  73. private static final String REGULAR_EXPRESSION_R6 = "regExpR6";
  74. private static final String EMPTY = "";
  75.  
  76. @Override
  77. public void process(Exchange exchange) throws Exception {
  78.  
  79. boolean isTaskRemedyRequest = false;
  80. boolean isIncRemedyRequest = false;
  81.  
  82. extractDetails(exchange);
  83.  
  84. UpdateWorkInfo updateWorkInfo = exchange.getProperty(UPDATE_WORK_INFO, UpdateWorkInfo.class);
  85.  
  86. String subject = updateWorkInfo.getSubject();
  87. StringBuilder detailedDescription = new StringBuilder(FROM);
  88. detailedDescription.append(": ").append(updateWorkInfo.getFrom()).append(", ").append(SUBJECT).append(": ").append(subject);
  89.  
  90. if (null != updateWorkInfo.getCc()) {
  91. detailedDescription.append(", ").append(CC).append(": ").append(updateWorkInfo.getCc());
  92. }
  93. detailedDescription.append(",\n").append(BODY).append(":\n").append(processMessageBody(exchange.getIn().getBody(), false));
  94.  
  95. updateWorkInfo.setDetailedDescription(MimeUtility.decodeText(detailedDescription.toString()));
  96.  
  97. updateWorkInfo.setMessageBody(processMessageBody(exchange.getIn().getBody(), true));
  98.  
  99. if (subject.contains(INCIDENT_NUMBER)) {
  100. isIncRemedyRequest = true;
  101. exchange.setProperty(IS_INC_REMEDY_REQUEST, isIncRemedyRequest);
  102. } else if (subject.contains(TASK_NUMBER)) {
  103. isTaskRemedyRequest = true;
  104. exchange.setProperty(IS_TASK_REMEDY_REQUEST, isTaskRemedyRequest);
  105. }
  106.  
  107. if (subject.contains(INCIDENT_NUMBER) || subject.contains(TASK_NUMBER)) {
  108. updateWorkInfo.setNotificationType(TROUBLE_TICKET);
  109. exchange.setProperty(GET_BILLING_ACCOUNT_ID, updateWorkInfo.getBillingAccountID());
  110. } else if (StringUtils.isNotBlank(updateWorkInfo.getBillingAccountID())) {
  111. exchange.setProperty(IS_VALID_REQUEST, true);
  112. updateWorkInfo.setNotificationType(CUSTOMER_REPLY);
  113. exchange.setProperty(GET_BILLING_ACCOUNT_ID, updateWorkInfo.getBillingAccountID());
  114. }
  115. exchange.getOut().setBody(updateWorkInfo);
  116. }
  117.  
  118. /**
  119. * checkSubject method is checking whether request is from Remedy or R6. If subject starts with INC which means request is from Remedy and boolean
  120. * isRemedyRequest is set to true.
  121. *
  122. * @throws UnsupportedEncodingException
  123. **/
  124.  
  125. private void extractDetails(Exchange exchange) throws UnsupportedEncodingException {
  126. UpdateWorkInfo updateWorkInfo = new UpdateWorkInfo();
  127.  
  128. String subject = exchange.getIn().getHeader(SUBJECT, String.class);
  129. String cc = exchange.getIn().getHeader(CC, String.class);
  130. String from = exchange.getIn().getHeader(FROM, String.class);
  131.  
  132. if (StringUtils.isBlank(subject)) {
  133. LOGGER.error("Subject is NULL in Incoming Email");
  134. throw new AipException(400);
  135. } else {
  136.  
  137. updateWorkInfo.setSubject(MimeUtility.decodeText(subject));
  138. extractSubjectDetails(updateWorkInfo);
  139. updateWorkInfo.setCc(cc);
  140. updateWorkInfo.setFrom(SpecialCharacterConverter.convertSpecialCharacterToUTF8String(MimeUtility.decodeText(from)));
  141. exchange.setProperty(UPDATE_WORK_INFO, updateWorkInfo);
  142. }
  143. }
  144.  
  145. /**
  146. * setPartnerId method is used to set PartnerId in InboundNotification object which is used for UpdateNotificationHistory service EAI call.
  147. *
  148. * @param exchange
  149. */
  150.  
  151. public void setPartnerId(Exchange exchange) {
  152. UpdateWorkInfo updateWorkInfo = exchange.getProperty(UPDATE_WORK_INFO, UpdateWorkInfo.class);
  153. updateWorkInfo.setPartnerId(exchange.getProperty(GET_PARTNERID, String.class));
  154. exchange.setProperty(INBOUND_NOTIFICATION, updateWorkInfo);
  155. }
  156.  
  157. /**
  158. * getPartnerId method is used to get PartnerId from OSS, which is used for UpdateNotificationHistory service EAI call.
  159. *
  160. * @param exchange
  161. */
  162.  
  163. public void getPartnerId(Exchange exchange) {
  164. String url = Config.scope(REMEDY, OSS_CALL).get(URL);
  165. String queryParam = (String) exchange.getIn().getBody();
  166. StringBuilder strBuilder = new StringBuilder().append(url).append(queryParam);
  167. exchange.getOut().setBody(strBuilder);
  168. }
  169.  
  170. /**
  171. * removeRoute method is used for remove route processing.
  172. *
  173. * @param exchange
  174. */
  175.  
  176. public void removeRoute(Exchange exchange) {
  177. CamelContext context = exchange.getContext();
  178. // Check if the route exist
  179. // if yes, remove the current route
  180. List<Route> routesList = context.getRoutes();
  181. // Add iterator to get the route with id "pollingRoute" and remove it from context
  182. Iterator<Route> iterator = routesList.iterator();
  183. while (iterator.hasNext()) {
  184. if (LOGGER.isDebugEnabled()) {
  185. LOGGER.debug("routes iterating");
  186. }
  187. Route route = iterator.next();
  188. if (POLLING_ROUTE.equalsIgnoreCase(route.getId())) {
  189. routesList.remove(route);
  190. break;
  191. }
  192. }
  193. }
  194.  
  195. /**
  196. * loadRoute method is used for load route processing.
  197. *
  198. * @param exchange
  199. */
  200.  
  201. public void loadRoute(Exchange exchange) {
  202. Scope workInfo = Config.scope(REMEDY, UPDATE_WORK_INFO);
  203.  
  204. CamelContext context = exchange.getContext();
  205. // Create new route with id as "pollingRoute"
  206. String pollingUrl = (new StringBuilder()).append(workInfo.get(URI_POLLING_PROTOCOL)).append(workInfo.get(URI_POLLING_SERVERNAME)).append(":")
  207. .append(workInfo.get(URI_POLLING_PORT)).append("?password=").append(workInfo.get(URI_POLLING_PASSWD)).append("&username=")
  208. .append(workInfo.get(URI_POLLING_USERNAME)).append("&consumer.delay=").append(workInfo.get(URI_POLLING_DELAY)).toString();
  209. if (LOGGER.isDebugEnabled()) {
  210. LOGGER.debug(String.format("pollingUrl:: %s ", pollingUrl));
  211. }
  212. RouteBuilder pollingRouteBuilder = new RouteBuilder() {
  213. @Override
  214. public void configure() throws Exception {
  215. LOGGER.debug(String.format("pollingUrl in Route:: %s", pollingUrl));
  216. from(pollingUrl).id(POLLING_ROUTE).to(RTE_DIRECT_REMEDY_UPDATE_INCIDENT_WORK_INFO);
  217. }
  218. };
  219. try {
  220. if (LOGGER.isDebugEnabled()) {
  221. LOGGER.debug("Adding pollingRouteBuilder");
  222. }
  223. context.addRoutes(pollingRouteBuilder);
  224. if (LOGGER.isDebugEnabled()) {
  225. LOGGER.debug(String.format("Adding below route definition to bean: %s", pollingUrl));
  226. LOGGER.debug("Added pollingRouteBuilder");
  227. }
  228. } catch (Exception exception) {
  229. LOGGER.error("Error while creation of route", exception);
  230. }
  231. }
  232.  
  233. private void extractSubjectDetails(UpdateWorkInfo updateWorkInfo) {
  234. Pattern pattern = Pattern.compile(Config.scope(REMEDY, UPDATE_WORK_INFO).get(REGULAR_EXPRESSION));
  235. Matcher matcher = pattern.matcher(updateWorkInfo.getSubject());
  236.  
  237. if (matcher.find()) {
  238. if (matcher.group(2).contains(INCIDENT_NUMBER)) {
  239. updateWorkInfo.setIncidentNumber(matcher.group(2));
  240. } else if (matcher.group(2).contains(TASK_NUMBER)) {
  241. updateWorkInfo.setTaskId(matcher.group(2));
  242. }
  243. }
  244.  
  245. pattern = Pattern.compile(Config.scope(REMEDY, UPDATE_WORK_INFO).get(REGULAR_EXPRESSION_R6));
  246.  
  247. matcher = pattern.matcher(updateWorkInfo.getSubject());
  248. if (matcher.find()) {
  249. updateWorkInfo.setBillingAccountID(matcher.group(2));
  250. }
  251. }
  252.  
  253. private String processMessageBody(Object content, boolean msgProcessedFlag) {
  254. try {
  255. String msg = "";
  256. if (content instanceof String) {
  257. msg = (String) content;
  258. } else if (content instanceof Multipart) {
  259. Multipart multiPart = (Multipart) content;
  260. msg = procesMultiPart(multiPart, msgProcessedFlag);
  261. } else if (content instanceof InputStream) {
  262. InputStream inStream = (InputStream) content;
  263. int ch;
  264. StringBuilder msgStrBuilder = new StringBuilder();
  265. while ((ch = inStream.read()) != -1) {
  266. msgStrBuilder.append(ch);
  267. }
  268. msg = msgStrBuilder.toString();
  269. }
  270. return msg;
  271. } catch (IOException exception) {
  272. LOGGER.error("Error while reading message", exception);
  273. throw new AipException(500);
  274. }
  275. }
  276.  
  277. private String procesMultiPart(Multipart content, boolean msgProcessedFlag) {
  278. try {
  279. int multiPartCount = content.getCount();
  280. StringBuilder msgBuilder = new StringBuilder();
  281.  
  282. for (int iCount = 0; iCount < multiPartCount; iCount++) {
  283. BodyPart part = content.getBodyPart(iCount);
  284. Object o = part.getContent();
  285.  
  286. if (!msgProcessedFlag && part.isMimeType("text/plain")) {
  287. msgBuilder.append((String) part.getContent());
  288. } else if (msgProcessedFlag && part.isMimeType("text/html")) {
  289. msgBuilder.append((String) part.getContent());
  290. } else if (o instanceof Multipart) {
  291.  
  292. msgBuilder.append(procesMultiPart((Multipart) o, msgProcessedFlag));
  293. }
  294. }
  295.  
  296. return msgBuilder.toString();
  297.  
  298. } catch (IOException exception) {
  299. LOGGER.error("Error while reading message", exception);
  300. throw new AipException(500);
  301. } catch (MessagingException exception) {
  302. LOGGER.error("Error while reading message", exception);
  303. throw new AipException(500);
  304. }
  305. }
  306.  
  307. /**
  308. * Read the attachments received in the mail. Only 3 attachments will be sent to remedy
  309. *
  310. * @param exchange
  311. */
  312. public void readAttachments(Exchange exchange) {
  313. LOGGER.debug("Reading email attachments " + exchange.getIn().getAttachmentNames().size());
  314. // read attachments with their data handlers
  315. Map<String, DataHandler> mapAttachments = exchange.getIn().getAttachments();
  316. // set attachments in header
  317. if (null != mapAttachments) {
  318. exchange.setProperty("EMAIL_ATTACHMENT", mapAttachments);
  319. }
  320. LOGGER.debug("Reading email attachments end");
  321. }
  322.  
  323. /**
  324. * Set attachment data in header to pass it remedy
  325. *
  326. * @param exchange
  327. * @throws IOException
  328. */
  329. public void setAttachmentData(Exchange exchange) throws IOException {
  330. // read attachments with their data handlers
  331. Map<String, DataHandler> mapAttachments = (Map<String, DataHandler>) exchange.getProperty("EMAIL_ATTACHMENT");
  332. // get the exchange property
  333. UpdateWorkInfo updateWorkInfo = exchange.getProperty(UPDATE_WORK_INFO, UpdateWorkInfo.class);
  334. // counter to read 3 attachments
  335. int count = 0;
  336. for (Entry<String, DataHandler> etyAttachments : mapAttachments.entrySet()) {
  337. // increment counter
  338. count++;
  339. // counter is greater than 3 break the loop
  340. if (count > 3) {
  341. break;
  342. }
  343.  
  344. if(count == 1){
  345. // setting file name
  346. updateWorkInfo.setFileName1(etyAttachments.getKey());
  347. // setting file content
  348. updateWorkInfo.setFileContent1(convertInputStreamToBase64String(etyAttachments.getValue().getInputStream()));
  349. // setting file size default
  350. updateWorkInfo.setFileSize1("0");
  351. } else if (count == 2){
  352. // setting file name
  353. updateWorkInfo.setFileName2(etyAttachments.getKey());
  354. // setting file content
  355. updateWorkInfo.setFileContent2(convertInputStreamToBase64String(etyAttachments.getValue().getInputStream()));
  356. // setting file size default
  357. updateWorkInfo.setFileSize2("0");
  358. } else if (count == 3){
  359. // setting file name
  360. updateWorkInfo.setFileName3(etyAttachments.getKey());
  361. // setting file content
  362. updateWorkInfo.setFileContent3(convertInputStreamToBase64String(etyAttachments.getValue().getInputStream()));
  363. // setting file size default
  364. updateWorkInfo.setFileSize3("0");
  365. }
  366. LOGGER.debug("Attachment : " + count + " : " + etyAttachments.getKey());
  367. LOGGER.debug("AttachmentCount : " + count);
  368. }
  369. // setting the count
  370. exchange.getIn().setHeader("attachmentCount", count>3?3:count);
  371. // setting update work info object
  372. exchange.setProperty(UPDATE_WORK_INFO, updateWorkInfo);
  373. // removing attachments
  374. exchange.removeProperty("EMAIL_ATTACHMENT");
  375. }
  376.  
  377. /** remove the header/exchange properties
  378. *
  379. */
  380. public void removeEmailAttachmentExchangeProperties(Exchange exchange){
  381. // remove attachment count
  382. exchange.getIn().removeHeader("attachmentCount");
  383. }
  384. /**
  385. * Convert file content to Base64String
  386. *
  387. * @param inputStream
  388. * @return base64String
  389. * @throws IOException
  390. */
  391. private String convertInputStreamToBase64String(InputStream inputStream) {
  392. try {
  393. String base64String = Base64.getEncoder().encodeToString(IOUtils.toByteArray(inputStream));
  394. LOGGER.debug("AttachmentData Encoded String " + base64String);
  395. return base64String;
  396. } catch (IOException ioException) {
  397. if(LOGGER.isDebugEnabled())
  398. LOGGER.debug("Exception is being thrown while converting into base64String");
  399. }
  400. return EMPTY;
  401. }
  402. }
Add Comment
Please, Sign In to add comment