Exchange Web服务Java APi RESTful推送通知侦听器

Exchange Web服务Java APi RESTful推送通知侦听器,第1张

概述我试图让我的听众使用ews java API,但我不能..我希望你能帮助我! 我已经完成了以下步骤: 1)连接到交换Web服务 ExchangeService newService = new ExchangeService(ExchangeVersion.Exchange2010_SP2); newService.setUrl("https://myurl/ews/Exchange.as 我试图让我的听众使用ews java API,但我不能..我希望你能帮助我!

我已经完成了以下步骤:

1)连接到交换Web服务

ExchangeService newService = new ExchangeService(ExchangeVersion.Exchange2010_SP2);    newService.setUrl("https://myurl/ews/Exchange.asmx");    ExchangeCredentials credentials = new WebCredentials("user","password");    newService.setCredentials(credentials);

2)然后订阅推送通知

@OverrIDepublic PushSubscription subscribetoPushNotifications(){    URI callback = null;    PushSubscription pushSubscription = null;    try{        logger.info("Subscribing to push notifications.. Endpoint Listener URI = " + config.getNotificationListenerURI());        callback = new URI(config.getNotificationListenerURI());        pushSubscription = service.subscribetoPushNotifications(                getFoldersForSubscription(),callback,5,null,EventType.NewMail,EventType.Created,EventType.Deleted,EventType.ModifIEd,EventType.Moved);         logger.info("Done! --> PushSubscription ID= " + pushSubscription.getID());    }catch(URISyntaxException e){        logger.error("EWS ==> InvalID Notification Listener URL = " + config.getNotificationListenerURI() +". Please,verify <integration-modules>");        Throwables.propagate(e);    }catch (Exception e){        logger.error("EWS ==> Error subscribing to push notifications",e);        Throwables.propagate(e);    }    return pushSubscription;}

3)然后开发我的Listener作为一个Restful webservice(我用虚拟方法进行测试,它正在工作)

首先定义servlet:

<servlet>    <servlet-name>jersey-serlvet</servlet-name>    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>      <init-param>        <param-name>com.sun.jersey.config.property.packages</param-name>        <param-value>com.rest</param-value>    </init-param>    <load-on-startup>1</load-on-startup></servlet><servlet-mapping>    <servlet-name>jersey-serlvet</servlet-name>     <url-pattern>/rest/*</url-pattern></servlet-mapping>

之后,创建Listener类以映射servlet中定义的url(我传递给ExchangeService的url)

@Path("/emailnotification")public class ExchangeNotificationListener {    private static final Log logger = LogFactory.getLog(ExchangeNotificationListener.class);    @Path("/incomingevent")    @POST()    @Produces(MediaType.TEXT_XML)    public Response onNotificationReceived() throws Exception {        logger.info("Received EWS notification !!!");    return Response.ok().build();    }    @GET    @Path("/{param}")    public Response getMsg(@PathParam("param") String msg) {        String output = "Jersey say : " + msg;        return Response.status(200).entity(output).build();    }}

但我设置了断点,然后给我发了一封电子邮件,但没有发生..我做错了什么/失踪???请帮忙 !

P.S:虚方法getMsg()有效,所以其余服务正在工作

提前致谢 !!

解决方法 问题是防火墙阻止传入的EWS消息进入我的开发环境.

这是监听器的最终版本.我希望有人能发现它很有用

@Path("/emailnotification")public class ExchangeNotificationListener {private static final Log logger = LogFactory.getLog(ExchangeNotificationListener.class);private static final String OK = "OK";private static final String UNSUBSCRIBE = "Unsubscribe";/** * This method receives a SOAP message from Microsoft Exchange Web Services,parses it into a ExchangeNotification object,* do some business logic and sends an ACK response to keep the subscription alive. *  * @param request *            EWS Push Notification request * @param response * @throws Exception */@Path("/incomingevent")@POST()@Consumes(MediaType.TEXT_XML)public voID onNotificationReceived(@Context httpServletRequest request,@Context httpServletResponse response)        throws Exception {    // Establish the start time so we can report total elapsed time to execute the call later.    long startTime = GregorianCalendar.getInstance().getTimeInMillis();    long endTime;    // RetrIEve the EWS Notification message as an XML document    document notificationXML = loadXML(IoUtils.toString(request.getinputStream()));    // Deserialize the document    ExchangeNotification notif = new ExchangeNotification(notificationXML);    // We need the subscription ID in order to proceed    String subscriptionID = notif.getSubscriptionID();    if (isBlank(subscriptionID)) {        logger.error("SOAP Envelope MUST contains the subscriptionID");        // If we dID not successfully parse the XML document,tell Exchange that we got a bad request.        response.sendError(httpServletResponse.SC_BAD_REQUEST);    }    if (!ExchangeSubscriptionMap.getInstance().getSubscriptionsMap().containsKey(subscriptionID)) {        logger.warn("SubscriptionID = " + subscriptionID                + " was not found in the subscriptions map. Unsubscribing...");        sendResponse(response,UNSUBSCRIBE);        return;    }    // Do some logic here depending on the current EventType    businessLogic(notif,response);    // Flush the buffer and report the total time taken to execute for this notification.    response.flushBuffer();    endTime = GregorianCalendar.getInstance().getTimeInMillis();    logger.deBUG(String.format("Total execution time: %1$s (ms)",(Long) (endTime - startTime)));}/** * Sends an ACK response to the Exchange Web Service *  * @param response * @param msg *            the content of the response message */private voID sendResponse(httpServletResponse response,String msg) {    try {        // Build the http response        String str = ExchangeUtils.getResponseXML(msg);        response.setCharacterEnCoding("UTF-8");        response.setStatus(httpServletResponse.SC_OK);        response.setContentType("text/xml; charset=UTF-8");        response.setContentLength(str.length());        // Send the response.        PrintWriter w = response.getWriter();        w.print(str);        w.flush();    } catch (IOException e) {        logger.error("Error getting the response writer");        Throwables.propagate(e);    }}/** * Process the incoming notification,do some business logic and send an ACK response to Exchange *  * @param notification *            to be processed * @param response *            to be returned */@SuppressWarnings("unchecked")private voID businessLogic(ExchangeNotification notification,httpServletResponse response) {    try {        // Iterate the notification events        for (SubscriptionEvent event : notification.getEvents()) {            // Only take care of the ModifIEd event            switch (event.getEventType()) {            case MODIFIED:                // logic here                // Get the ExchangeService instance this user use for Subscribing                MSExchangeServiceManager service = ExchangeSubscriptionMap.getInstance().getSubscriptionsMap().get(notification.getSubscriptionID()).getService();               //e.g: service.getUnreadMessages(WellKNownFoldername.InBox));                break;            default:                logger.deBUG("SkipPing: " + event.getEventType());                break;            }        }        // Finally,send the response.        sendResponse(response,OK);    } catch (Exception e) {        logger.error("EWS ==> Error processing request",e.getCause());        Throwables.propagate(e);    }}/** * Create a XML document using a raw xml string *  * @param rawXML *            the raw xml string to be converted * @return XML EWS Nofitication document */private document loadXML(String rawXML) {    document doc = null;    try {        logger.deBUG("Incoming request input stream : " + rawXML);        documentBuilderFactory domFactory = documentBuilderFactory.newInstance();        // turn on this flag in order to resolve manually the namespaces of the document        domFactory.setnamespaceAware(true);        documentBuilder builder = domFactory.newdocumentBuilder();        doc = builder.parse(new inputSource(new ByteArrayinputStream(rawXML.getBytes("UTF-8"))));    } catch (ParserConfigurationException e) {        logger.error("Unable to create a new documentBuilder");        Throwables.propagate(e);    } catch (UnsupportedEnCodingException e) {        logger.error("Unsupported EnCoding: UTF-8");        Throwables.propagate(e);    } catch (SAXException e) {        logger.error("Error parsing XML");        Throwables.propagate(e);    } catch (IOException e) {        logger.error("IOException");        Throwables.propagate(e);    }    return doc;  }}
总结

以上是内存溢出为你收集整理的Exchange Web服务Java APi RESTful推送通知侦听器全部内容,希望文章能够帮你解决Exchange Web服务Java APi RESTful推送通知侦听器所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1104385.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-28
下一篇2022-05-28

发表评论

登录后才能评论

评论列表(0条)

    保存