locked
Exchange 2007 Web Services: Generate the JAVA interface RRS feed

  • Question

  • Hi,

     

    I am developping a JAVA client for consuming Exchange 2k7 web services and I am facing a major issue: which tool should I use to generate a JAVA package that works ?? Without modifying the WSDL file ??

     

    I tried using Axis2 but it requires an item <service> in the WSDL file, so it fails.

     

    I also tried using Axis 1.4 and this time the package was generated, but I had to fix many things in the generated package to make it works simply as it is working on a .Net platform. And I am still facing a few bugs with it.

     

    I would highly appreciate that someone explains me (us) the right process for generating a JAVA package from exchange web services WSDL file.

     

    Thanks,

    Thursday, September 27, 2007 12:23 PM

Answers

  • Hum... It seems that this situation does not inspire much people out there.

     

    Let me explain you a solution to generate a JAVA package using Axis 1.4 to consume the Echange 2k7 web services using a similar interface as the one generated on .Net C#:

     

    This solution requires some modifications in the generated source code to make the package fully compatible with the web service and even if it's not the best way to do it, it can gives you some :

    • First, generate the package with axis 1.4 and the wsdl file corresponding to the web service (requires message.xsd and types.xsd)
    • Import the generated package in a new project from your IDE and correct the problems of compilation: some constructors are missing, so you'll just have to had them in the different classes .

    Now that you have a package that you can compile and export as a jar file, you'll quickly notice that you still cannot use it to consume the web service . You will notice that the methods contained in the class ExchangeServiceBindingStub contains many parameters that you don't really know how to deal with : ExchangeImpersonationType and SerializedSecurityContextType.

    • Look at the references on the msdn web site to see the parameters that are required for executing a SOAP request. You will quickly conclude that these parameters are unusefull for most of the request.
    • What you got to do is to remove these two parameters from the declaration statement and the method signature , and things will start working better ! (Update ExchangeServiceBindingStub.java file).

    Now, you can start consuming the Exchange Web Services, and it should work with a similar interface than the one in C#. It will be quite simple to migrate a sample code from C# to java.

     

    BUT IT S NOT DONE YET, you will notice that the package does not give full statisfaction and still requires some tricky customizations.

     

    Here we go!! Let's modify the following files and rename the variables ("value1" will become "itemInternetMessageHeader") to get them more convenient to use:

    • UnindexedFieldURIType.java
    • DictionaryURIType.java
    • ExceptionPropertyURIType.java

    At last, let's deal with the last problem that we have with this package: DEALING WITH OBJECT COLLECTION!! Indeed, you will quickly notice that the generated package cannot retrieve collection of objects like the list of folders, or the list of items in a folder, or the list of attachments in an item, IT ONLY RETURNS ONE ELEMENT  !

     

    Well, let's modify the class that should handle these collections of objects and add an ArrayList field in them:

    • ArrayOfAttachmentsType.java
    • ArrayOfAttendeeConflictData.java
    • ArrayOfBaseItemIdsType.java
    • ArrayOfFoldersType.java
    • ArrayOfGroupItemsType.java
    • ArrayRealItemsType.java
    • ArrayOfRecipientsType.java

    example:

     

    private ArrayList<com.microsoft.schemas.exchange.services._2006.types.MessageType> messages;

     

    public ArrayOfRealItemsType()

    {

    this.messages = new ArrayList<MessageType>;

    }

     

    Add the getter and setter methods that will let you manipulate this collection and the job is done  !!

     

    I hope that this post will give you some good ideas about getting a JAVA package fully compatible with Exchange 2007 web services.

     

    I bet there are some points that I am still missing, like the management of restrictions when filtering a request: I have not solved this yet.

    Monday, October 1, 2007 8:07 AM
  • An other update about how to generate a valid Java package for EWS using Axis 1.4

     

    the major issue that we are facing when generating the package is to get classes that handle objects array correctly. This will require to modify the file types.xsd and messages.xsd to add parameters in object arrays'elements:

    It misses the following param: maxOccurs="unbounded". This param should be added to every elements of an array object that should contain multiple objects.

     

    For example, modify the type ArrayOfFoldersType this way :

     

    Code Block

    <xs:complexType name="ArrayOfFoldersType">
        <xs:choice minOccurs="0" maxOccurs="unbounded">
          <xs:element name="Folder" type="t:FolderType" maxOccurs="unbounded"/>
          <xs:element name="CalendarFolder" type="t:CalendarFolderType" maxOccurs="unbounded"/>
          <xs:element name="ContactsFolder" type="t:ContactsFolderType" maxOccurs="unbounded"/>
          <xs:element name="SearchFolder" type="t:SearchFolderType" maxOccurs="unbounded"/>
          <xs:element name="TasksFolder" type="t:TasksFolderType" maxOccurs="unbounded"/>
        </xs:choice>
    </xs:complexType>

     

     

    Repeat this for every types labelled with "ArrayOf..." and "NonEmpyArrayOf..."

    Friday, October 19, 2007 12:29 PM

All replies

  • You should be able to copy the services.wsdl file and xsd files locally, add the wsdlTongue Tiedervice element yourself and then generate your axis proxy classes against the modified wsdl file.

    Thursday, September 27, 2007 3:32 PM
  • Hi David,

     

    Thanks for this tip, but it 's not really what I am looking for. I read the forum about this topic, and until now no solution has been found to generate a valid JAVA package with any tools, without having to modify the wsdl file.

     

    I already have a package that I can use to perform SOAP requests using the EWS interface, but it does not work correctly:

    • unable to retrieve more than one item or one attachment

    • unable to set a restriction on a request
    • unable to get the list of folders in a directory

    Well, anytime that I want to retrieve a collection of object, it only returns the first item found.

    I think that this problem come from the generation of the JAVA package, that's why I am looking for a solution to generate a package that do work without having to modify it.

     

    Have you, guys, performed any tests consuming the Exchange 2007 web services through a JAVA client ?

     

    Thanks for your help.

    Thursday, September 27, 2007 3:55 PM
  • Hum... It seems that this situation does not inspire much people out there.

     

    Let me explain you a solution to generate a JAVA package using Axis 1.4 to consume the Echange 2k7 web services using a similar interface as the one generated on .Net C#:

     

    This solution requires some modifications in the generated source code to make the package fully compatible with the web service and even if it's not the best way to do it, it can gives you some :

    • First, generate the package with axis 1.4 and the wsdl file corresponding to the web service (requires message.xsd and types.xsd)
    • Import the generated package in a new project from your IDE and correct the problems of compilation: some constructors are missing, so you'll just have to had them in the different classes .

    Now that you have a package that you can compile and export as a jar file, you'll quickly notice that you still cannot use it to consume the web service . You will notice that the methods contained in the class ExchangeServiceBindingStub contains many parameters that you don't really know how to deal with : ExchangeImpersonationType and SerializedSecurityContextType.

    • Look at the references on the msdn web site to see the parameters that are required for executing a SOAP request. You will quickly conclude that these parameters are unusefull for most of the request.
    • What you got to do is to remove these two parameters from the declaration statement and the method signature , and things will start working better ! (Update ExchangeServiceBindingStub.java file).

    Now, you can start consuming the Exchange Web Services, and it should work with a similar interface than the one in C#. It will be quite simple to migrate a sample code from C# to java.

     

    BUT IT S NOT DONE YET, you will notice that the package does not give full statisfaction and still requires some tricky customizations.

     

    Here we go!! Let's modify the following files and rename the variables ("value1" will become "itemInternetMessageHeader") to get them more convenient to use:

    • UnindexedFieldURIType.java
    • DictionaryURIType.java
    • ExceptionPropertyURIType.java

    At last, let's deal with the last problem that we have with this package: DEALING WITH OBJECT COLLECTION!! Indeed, you will quickly notice that the generated package cannot retrieve collection of objects like the list of folders, or the list of items in a folder, or the list of attachments in an item, IT ONLY RETURNS ONE ELEMENT  !

     

    Well, let's modify the class that should handle these collections of objects and add an ArrayList field in them:

    • ArrayOfAttachmentsType.java
    • ArrayOfAttendeeConflictData.java
    • ArrayOfBaseItemIdsType.java
    • ArrayOfFoldersType.java
    • ArrayOfGroupItemsType.java
    • ArrayRealItemsType.java
    • ArrayOfRecipientsType.java

    example:

     

    private ArrayList<com.microsoft.schemas.exchange.services._2006.types.MessageType> messages;

     

    public ArrayOfRealItemsType()

    {

    this.messages = new ArrayList<MessageType>;

    }

     

    Add the getter and setter methods that will let you manipulate this collection and the job is done  !!

     

    I hope that this post will give you some good ideas about getting a JAVA package fully compatible with Exchange 2007 web services.

     

    I bet there are some points that I am still missing, like the management of restrictions when filtering a request: I have not solved this yet.

    Monday, October 1, 2007 8:07 AM
  • Here is an update about using AXIS 1.4 generated JAVA interface to consume Exchange 2007 web services.

     

    The package requires few modifications to be fully compatible with the web services, and here is a solution to use restrictions on SOAP request, and solve the problem of "Invalid Restiction". See this post:

     

    http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=2233013&SiteID=17

     

    Hope that this information can help you in your development.

    Monday, October 8, 2007 12:29 PM
  • An other update about how to generate a valid Java package for EWS using Axis 1.4

     

    the major issue that we are facing when generating the package is to get classes that handle objects array correctly. This will require to modify the file types.xsd and messages.xsd to add parameters in object arrays'elements:

    It misses the following param: maxOccurs="unbounded". This param should be added to every elements of an array object that should contain multiple objects.

     

    For example, modify the type ArrayOfFoldersType this way :

     

    Code Block

    <xs:complexType name="ArrayOfFoldersType">
        <xs:choice minOccurs="0" maxOccurs="unbounded">
          <xs:element name="Folder" type="t:FolderType" maxOccurs="unbounded"/>
          <xs:element name="CalendarFolder" type="t:CalendarFolderType" maxOccurs="unbounded"/>
          <xs:element name="ContactsFolder" type="t:ContactsFolderType" maxOccurs="unbounded"/>
          <xs:element name="SearchFolder" type="t:SearchFolderType" maxOccurs="unbounded"/>
          <xs:element name="TasksFolder" type="t:TasksFolderType" maxOccurs="unbounded"/>
        </xs:choice>
    </xs:complexType>

     

     

    Repeat this for every types labelled with "ArrayOf..." and "NonEmpyArrayOf..."

    Friday, October 19, 2007 12:29 PM
  • Hi ,

     

    We tried using  the following point from your post for handling collection -

     

    modifying the class that should handle  collections of objects and add an ArrayList field in them:

    • ArrayOfAttachmentsType.java
    • ArrayOfAttendeeConflictData.java
    • ArrayOfBaseItemIdsType.java
    • ArrayOfFoldersType.java
    • ArrayOfGroupItemsType.java
    • ArrayRealItemsType.java
    • ArrayOfRecipientsType.java

    example:

     

    private ArrayList<com.microsoft.schemas.exchange.services._2006.types.MessageType> messages;

     

    public ArrayOfRealItemsType()

    {

    this.messages = new ArrayList<MessageType>;

    }

     

    We have put the setter and getter method for the arraylist. But we are getting  null for the Arraylist which we have declared as above.

     

    Am I missing something? Kindly help.

     

    Regards

    Informed

     

    Monday, October 29, 2007 6:14 AM
  • Hi,

     

    Adding an ArrayList directly in the Java file was the first test that I performed to  be able to retrieve from Exchange the list of folders or items in a mailbox. But it is not the most convenient way to do it.

     

    Try to update the files types.xsd and messages.xsd directly by adding maxOccurs="unbounded" as described in my previous post. This way the java will be correctly generated to handle list of objects, like folders or items.

     

    Regards,

     

    Monday, October 29, 2007 8:15 AM
  •  

    Hi,

     

    We tried modifying types.xsd and messages.xsd as guided by the post. We  regenerated the java(proxy) classes .

    Then made changes to few java classes for successful compilation . The ExchangeServiceBinding stub is modified for removing ExchangeImpersonationType, SerializedSecurityContextType references .

    All the java files are successfully compiled.

    But when we run our client java prgram, accessing the exchange Java classes, we get the following error, the trace for which is as follows:

     

    Exception in thread "main" AxisFault
     faultCode: Client
     faultSubcode:
     faultString: The request failed schema validation.
     faultActor:
     faultNode:
     faultDetail:
     {http://schemas.microsoft.com/exchange/services/2006/errors}ResponseCode:ErrorSchemaValidation
     {http://schemas.microsoft.com/exchange/services/2006/errors}Message:The required attribute 'Id' is missing.
     {http://schemas.microsoft.com/exchange/services/2006/errors}Line:1
     {http://schemas.microsoft.com/exchange/services/2006/errors}Position:628

    The request failed schema validation.
     at org.apache.axis.message.SOAPFaultBuilder.createFault(SOAPFaultBuilder.java:222)
     at org.apache.axis.message.SOAPFaultBuilder.endElement(SOAPFaultBuilder.java:129)
     at org.apache.axis.encoding.DeserializationContext.endElement(DeserializationContext.java:1087)
     at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.endElement(AbstractSAXParser.java:633)
     at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanEndElement(XMLNSDocumentScannerImpl.java:719)
     at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(XMLDocumentFragmentScannerImpl.java:1685)
     at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:368)
     at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:834)
     at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
     at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:148)
     at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1242)
     at javax.xml.parsers.SAXParser.parse(SAXParser.java:375)
     at org.apache.axis.encoding.DeserializationContext.parse(DeserializationContext.java:227)
     at org.apache.axis.SOAPPart.getAsSOAPEnvelope(SOAPPart.java:696)
     at org.apache.axis.Message.getSOAPEnvelope(Message.java:435)
     at org.apache.axis.handlers.soap.MustUnderstandChecker.invoke(MustUnderstandChecker.java:62)
     at org.apache.axis.client.AxisClient.invoke(AxisClient.java:206)
     at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
     at org.apache.axis.client.Call.invoke(Call.java:2767)
     at org.apache.axis.client.Call.invoke(Call.java:2443)
     at org.apache.axis.client.Call.invoke(Call.java:2366)
     at org.apache.axis.client.Call.invoke(Call.java:1812)
     at com.microsoft.schemas.exchange.services._2006.messages.ExchangeServiceBindingStub.findItem(ExchangeServiceBindingStub.java:3508)
     at demo.EWSService.main(EWSService.java:122)
     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
     at java.lang.reflect.Method.invoke(Method.java:585)
     at com.intellij.rt.execution.application.AppMain.main(AppMain.java:78)

    Process finished with exit code 1

     

    Please note,

    1. with the old XSDs the proxy java classes generated, were able to get only one object(item) successfully.

    2. Later, we added maxOccurs="unbounded" parameter, for every types labelled with "ArrayOf..." and "NonEmpyArrayOf..."  in tyeps and messages.xsd.

     

    Please help us in solving  this.

     

    If it is possible, could you please share the code snippet of the proxy classes jar with us?

     

    Thanks,

    Regards

    Informed

    Monday, October 29, 2007 1:39 PM
  •  

    From the error message:

     

    Message:The required attribute 'Id' is missing.

     

    Looks like you specified an itemId, distinguishedFolderid, FolderId, AttachmentId, etc... without an Id element.  Are you setting all the required properties on your proxy class before sending?

     

    Monday, October 29, 2007 2:08 PM
  • Hi,

     

    this is a sample of code that you can used to retrieve items from a folder with your Java package generated with Axis 1.4:

    it uses the string folderId and the string itemClass ("IPM.NOTE")

    Code Block

    public ArrayOfRealItemsType getFolderItems(String parentFolderId, String itemClass) throws Exception
     {
      if(exchangeService == null)
       throw(new Exception("EWS has not been initialized"));

      if (parentFolderId == null)
       return null;

      logger.debug("getFolderItems in folder: " + parentFolderId);

      // Declare the parent folder where the search will be performed
      NonEmptyArrayOfBaseFolderIdsType sourceFolder = new NonEmptyArrayOfBaseFolderIdsType();
      FolderIdType[] folderIds = new FolderIdType[1];
      folderIds[0] = new FolderIdType();
      folderIds[0].setId(parentFolderId);
      
      sourceFolder.setFolderId(folderIds);

      // Specify the properties that should be returned
      ItemResponseShapeType itemShape = new ItemResponseShapeType();
      itemShape.setBaseShape(DefaultShapeNamesType.AllProperties);

      // Specify a restriction for filtering the result
      RestrictionType restriction = new IsEqualToRestrictionType();
      IsEqualToType searchExpression = new IsEqualToType();

      // Constant to filter the result:
      FieldURIOrConstantType constant = new FieldURIOrConstantType();
      ConstantValueType value = new ConstantValueType();
      value.setValue(itemClass);
      constant.setConstant(value);

      // Field to filter the result:
      PathToUnindexedFieldType MsgClassField = new PathToUnindexedFieldType();
      MsgClassField.setFieldURI(UnindexedFieldURIType.itemItemClass);

      searchExpression.setFieldURIOrConstant(constant);
      searchExpression.setPath(MsgClassField);
      restriction.setSearchExpression(searchExpression);

      // Set FindItem request attributes
      FindItemType request = new FindItemType();
      request.setParentFolderIds(sourceFolder);
      request.setItemShape(itemShape);
      request.setTraversal(ItemQueryTraversalType.Shallow);// type of search

      FindItemResponseTypeHolder response = new FindItemResponseTypeHolder();

      try {
       exchangeService.findItem(request, response, serverVersion);
      } catch (RemoteException e) {
       e.printStackTrace();
      }

      FindItemResponseMessageType[] message = response.value.getResponseMessages().getFindItemResponseMessage();
      if (message.length > 0)
      {
       logger.info("getFolderItems: " + message[0].getResponseClass().getValue().toString() + " - " + message[0].getResponseCode().getValue());
       if (message[0].getResponseClass().equals(ResponseClassType.Success))
       {
        ArrayOfRealItemsType allItems = message[0].getRootFolder().getItems();
        MessageType[] items = allItems.getMessage();
        if (items != null)
        {
         for(MessageType tmp:items)
         {
          logger.debug("\t- item: " + tmp.getSubject() + " - " + tmp.getItemClass());
         }
        }
        return allItems;
       }
       else
       {
        logger.debug("\t- message: " + message[0].getMessageText());
        throw(new Exception("EWSConnector: error retrieving items from folder.\n mess.getMessageText()"));
       }
      }
      return null;
     }

     

    Hope this help.

    Monday, October 29, 2007 2:10 PM
  • Hi GP , David,

     

    Thanks a lot . Your code and explanations helped a lot. Now, I am able to retieve collection of objects successfully.

     

    We have mails with outlook forms. These forms data(which is a value pair- LABEL -VALUE) , we need  to retrieve. But the getItem() which gets the body of the message does not get the forms data.

     

    Do you have any idea about accessing out look forms  from the exchange webservices?

     

    Kindly let me know.

     

    Regards

    Lakshmi

     

    Tuesday, October 30, 2007 7:25 AM
  • Hi Lads! Hi G.P, hope you are doing good!

    I've faced following problems. How to specify suffix and prefix (like Mrs, Mr Ph.D. and so on). I've found this options in CompleteName class, but when I tryed to add completeName.setSuffix("SomthingHere"); there were ErrorInvalidPropertySet.

    The Second problem is to specify composite restriction. i mean in one restriction specify two or more different kind of it. Like this:
    <restriction>
    <And>
    <IsGreaterThen>
    </>
    <IsEqualTo>
    </And>

    For now (i'm doing the same way like G.P does) I change tag name in class MultipleOperandBooleanExpressionType from "SearchExpression" to what ever IsEqualTo or IsGreaterThen and so on. And add it to OrRestrictionType object. But because of SOAP is composed using tag name not from class directly, but from it general superclass (MultipleOperandBooleanExpressionType) we have only one restriction type that could be added to this. Thats mean that we are able to recieve something like this

    <restriction>
    <And>
    <IsGreaterThen>
    </>
    <IsGreaterThen>
    </>
    <IsGreaterThen>
    </>
    and so on...
    </And>
     But not like in previous example. Do you know how to beat it? Thanks!
     
    Monday, November 12, 2007 1:52 PM
  •  

    G.P. thanks for you solution,I get the generated a JAVA package using Axis 1.4. But Generated a JAVA package cotains many erorrs of constracotor.Some condtracotors were added ,but i worry about them.You say that ExchangeImpersonationType and SerializedSecurityContextType are not important.I give them up.The createItem and createfolder work well,but the updateItem does not do good job.

     

    When doing updateItem (replacing the message body ),Are you successed to do this ?If you have done this as befor please give me more helps.If it is ok ,your codes of updateItem are very helpful !

     

    impersonation, s2SAuth, mailboxCulture, requestVersion were given up in updateItem of ExchangeServiceBindingStub,do it right?Or that is the reason why update Item fails ?

     

    YoungSpring

     

     

    Tuesday, December 4, 2007 12:09 PM
  • You only need the impersonation property if you are doing Exchange Impersonation.  The S2SAuth header you should ignore as that is used by Exchange server to talk to each other.  The MailboxCulture allows you to specify the culture to use when opening a mailbox.  if you are fine with using the default culture of the Exchange server, then you can omit that header.  The RequestVersion is necessary IF you are going to use any of the new SP1 features (public folder access, post items, new props, delegate management, etc...)  Otherwise, EWS will consider your request an RTM request and will not allow you to access any of the new functions.

     

    Wednesday, December 5, 2007 5:52 PM
  • Java codes generated by Exchange Server 2007 and Exchange Server 2007 sp1 are not the same.I modified the codes generated by Exchange Server 2007 and give up the impersonation,S2SAuth,MailboxCulture in UpdateItem and got the axis fault.The CreateItem which also omit impersonation,S2SAuth,MailboxCulture goes well I do not kown why?Yes, maybe EWS consider my request an RTM request and not allow me to access it. Request,impersonation,RequestVersion ,MailboxCulture were keep in the codes generated by Exchange Server 2007 sp1.I hope it will be ok. The details of the EWS differences between Exchange Server 2007 and Exchange Server 2007 sp1 are needly.

    Big thanks for David.

    YoungSpring

    Thursday, December 6, 2007 3:17 PM
  • Hi,

     

    Please send some sample wsdl file and java class for accessing Ms exchange server and if possible pls tell me deployment procedure

     

     

    Thanks

    sri

     

    Thursday, February 28, 2008 4:37 AM
  • Hi G.P

     

    I need your help to know some sample for accessing ms exchange server through soap if possible pls could you send me a mail which contains sample and any developer guide you have, it will useful or me to start ms exchange server soap service.

     

    thanks

    sri

    Thursday, February 28, 2008 4:40 AM
  • Hi,

    I am trying to use getItem Request to retrieve occurrences of a recurring appointment from Exchange Store.i am working in C#.In this process, I am facing an error like

    "The required attribute  'Id' is missing"

    I am setting all the properties required before sendig the request.I am not able to trace where I am worng.Can u help me out in this issue?

     

    GetItemType secondrequest = new GetItemType();

    ItemResponseShapeType secondshape = new ItemResponseShapeType();

    secondshape.BodyType = BodyTypeResponseType.Text;

    secondshape.BodyTypeSpecified = true;

    secondshape.BaseShape = DefaultShapeNamesType.AllProperties;

    secondrequest.ItemShape = secondshape;

    secondrequest.ItemIds = recurID2;

    //I am adding Id s to recurID2 in a for loop before the declaration f the getItem Request.

     

     

    Thanks

    Friday, February 29, 2008 6:18 AM
  • Hi,

    I answer to this post cause G.P was my colleague, he left my company, but before he transfers to me his code and experience.

    G.P generated a package using AXIS and wsdl2java -adb (AxisDataBinding).

    we noticed some errors while compiling and correct the erros in the generated code.
    Then I found other problem:
    for example  the type.xsd defines some attributes that must not be set , use="prohibited", and my package analyse it as a  use="required" attribute ...and some other problem again.

    After a while, it started to be  difficult to remember all the modification we made in the generated code...
    and if in case of wsdl update... you can imagie the problem.

    So I try to generated the code differently.

    Now I am using a java package generated with wsdl2java -d xmlbeans

    And I've no more problem.
    Today my application can get, find, update and send item.

    Code generated is a bit different and youwill need to re-develop some piece of code but principle is stil the same and your application will be much more maintainable in my opinion.


    Hervé
    Friday, February 29, 2008 9:13 AM
  • Hi Herve,

    Thanks for the reply.I figured out my problem..The problem was that the ID field of the last item of the group returned by GetItem ws being assigned to null.I fixed the issue.

    Thanks for the reply anyways!

     

    Friday, February 29, 2008 9:19 AM
  • hi david,

     

    I need you help to understand the java interface Stub created by service.wsdl file, Could you send some example for understand to create new mail or to create new contact using the STUB

     

     

    regards

    Sri

     

    Monday, March 3, 2008 5:29 AM
  • Hi G.P

     

    Thanks for the details and it really worth to work. But i am new for soap service. I have create the stub followed your instructuion and i have made the change also still i could not able to conncet the web server. I know i dont know how to configure the Ms exchange server with tomcat Axis soap service.

     

    Please give me the instruction to do it........ i excepting you replay for this post ......

     

    "i dont know how to configure the ms exchange server in to axis" i formed the java code like given below

     

    The code is to create new mail into exchange server ( please help me )

     

    Error while running the code

     

    log4j:WARN No appenders could be found for logger (org.apache.axis.i18n.ProjectResourceBundle).

    log4j:WARN Please initialize the log4j system properly.

    status : ; nested exception is:

    java.net.UnknownHostException: null

     

     

    // Code used

    public String processCreateEmailItem()

    {

    String createStatus = null;

    try

    {

    url = new URL("https://" + msExchangeDomainProperty.getDomainName()

    + "/EWS/Exchange.asmx");

    }

    catch (MalformedURLException e1)

    {

    e1.printStackTrace();

    }

    // Identify the service binding and the user.

    try

    {

    exService = new ExchangeServiceBindingStub(url, null);

    }

    catch (AxisFault e)

    {

    e.printStackTrace();

    }

    // for test purpose i have given

    exService.setUsername(msExchangeDomainProperty.getUserName());

    exService.setPassword(msExchangeDomainProperty.getPassWord());

     

    // Create the CreateItem request.

    CreateItemType createEmailRequest = new CreateItemType();

    // Specifiy how the e-mail will be handled.

    createEmailRequest

    .setMessageDisposition(MessageDispositionType.SaveOnly);

    // createEmailRequest.setMessageDispositionSpecified = true;

    // Specify the location of sent items.

    createEmailRequest.setSavedItemFolderId(new TargetFolderIdType());

    DistinguishedFolderIdType sentitems = new DistinguishedFolderIdType();

    sentitems.setId(DistinguishedFolderIdNameType.sentitems);

    createEmailRequest.getSavedItemFolderId().setDistinguishedFolderId(

    sentitems);

    // Create the array of items.

    createEmailRequest.setItems(new NonEmptyArrayOfAllItemsType());

    // Create a single e-mail message.

    MessageType message = new MessageType();

    message.setSubject(msExchangeEmailProperty.getSubject());

    message.setBody(new BodyType());

    message.getBody().setBodyType(BodyTypeType.Text);

    message.getBody().set_value(

    msExchangeEmailProperty.getBodyText().toString());

    message.setSender(new SingleRecipientType());

    message.getSender().setMailbox(new EmailAddressType());

    message.getSender().getMailbox().setEmailAddress(

    msExchangeEmailProperty.getFrom());

    EmailAddressType em = new EmailAddressType();

    ArrayOfRecipientsType arr = new ArrayOfRecipientsType();

    arr.setMailbox(em);

    message.setToRecipients(arr);

    String[] obj = msExchangeEmailProperty.getTo();

    String objValue = "";

    for (int i = 0; i < obj.length; i++)

    objValue += objIdea + ";";

    message.getToRecipients().getMailbox().setEmailAddress(objValue);

    message.setSensitivity(SensitivityChoicesType.Normal);

    message.setCcRecipients(arr);

    obj = msExchangeEmailProperty.getCC();

    objValue = "";

    for (int i = 0; i < obj.length; i++)

    objValue += objIdea + ";";

    message.getCcRecipients().getMailbox().setEmailAddress(objValue);

    message.setBccRecipients(arr);

    obj = msExchangeEmailProperty.getBCC();

    objValue = "";

    for (int i = 0; i < obj.length; i++)

    objValue += objIdea + ";";

    message.getBccRecipients().getMailbox().setEmailAddress(objValue);

    // Add the message to the array of items to be created.

    createEmailRequest.getItems().setItem(message);

    ConnectingSIDType sidt = new ConnectingSIDType();

    sidt.setPrimarySmtpAddress("administrator@adapitme.net");

    sidt.setSID("administrator");

    sidt.setPrincipalName("UPN");

     

    Language mailboxCulture = new Language();

    mailboxCulture.setValue("en-US");

    RequestServerVersion requestVersion = new RequestServerVersion();

    CreateItemResponseTypeHolder createItemResult = new CreateItemResponseTypeHolder();

    ServerVersionInfoHolder serverVersion = new ServerVersionInfoHolder();

    try

    {

    // Send a CreateItem request and get the CreateItem

    // response.

    exService.createItem(createEmailRequest, mailboxCulture, requestVersion, createItemResult, serverVersion);

     

    CreateItemResponseType createItemResponse = new CreateItemResponseType();

    ArrayOfResponseMessagesType responses = createItemResponse

    .getResponseMessages();

    ResponseMessageType responseMessages = responses

    .getSendItemResponseMessage();

    System.out.println("rM :: " + responseMessages.getMessageText());

    createStatus = responseMessages.getMessageText();

    }

    catch (Exception ex)

    {

    createStatus = ex.getMessage();

    }

    return createStatus;

    }

     

     

     

    Thursday, March 6, 2008 6:09 AM
  • Hi,
    as I told before G.P does work anymore on Exchange Web Service. However he's fine ;-)

    Here is a code I made for you, I test it, it works.
    It uses the stub and classes generated with axis2 1.3, wsdl2java -d xmlbean ...
    I really advise you to use xmlbeans framework too. the adb framework gave me too many troubles.

    make sure host, domaine, user, password are correct.
    make sure user has right to access mailbox

    in this example, the FQDN of my host is frbrj210.eccdevr5.atabrest.fr
    I use the NTLM authentication
    user has full access on "p00001.n00001@eccdevr5.atabrest.fr" mailbox
    we are trying to retrieve the inbox folder ID of the
    p00001.n00001@eccdevr5.atabrest.fr mailbox.
    with the user "user" who have specific right set on the exchange server.


    May the force be with you ...



        public static void main(String args []) {
           
                String m_user = "user"; // you must grant this user the rights to access mailbox you want to inspect
                String m_password = "passwword";

                m_EWSservice = null;
                String ewsUrl = "https://frbrj210/EWS/exchange.asmx";

                String host = "frbrj210";
                String domain = "eccdevr5.atabrest.fr";

                // Register protocol handler for Https to accept self-signed SSL certificate.
                Protocol AlcHttpsProtocol = new Protocol("https", new AlcSSLSocketFactory(), 443);
                Protocol.registerProtocol("https", AlcHttpsProtocol);

                    try {
                        m_EWSservice = new ExchangeWebServiceStub(null, ewsUrl );
                    }
                    catch ( RemoteException e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }
                    Options options = m_EWSservice._getServiceClient().getOptions();

                    HttpTransportProperties.Authenticator authenticator = new HttpTransportProperties.Authenticator();
                    List<String> authScheme = new ArrayList<String>();
                    authScheme.add(HttpTransportProperties.Authenticator.NTLM);

                    authenticator.setAuthSchemes(authScheme);
                    authenticator.setUsername(m_user);
                    authenticator.setPassword(m_password);
                    authenticator.setHost(host);
                    if (domain != null) {
                        authenticator.setDomain(domain);
                    }
                    authenticator.setPort(443);

                    options.setProperty(HTTPConstants.AUTHENTICATE, authenticator);
                   
                    m_EWSservice._getServiceClient().setOptions(options);
                   
                    // now invoke a simple method
                    try {
                    String resultId = getInboxId(m_EWSservice, "p00001.n00001@eccdevr5.atabrest.fr");
                    System.out.println("inbox folder id:" + resultId);
                    }
                    catch(RemoteException e){
                        e.printStackTrace();
                    }
            }
           
       
        private static String getInboxId(ExchangeWebServiceStub m_EWSservice, String strAddress) throws RemoteException{
           
            GetFolderDocument request = GetFolderDocument.Factory.newInstance();
            GetFolderType getFolder = GetFolderType.Factory.newInstance();
           
         
           
            // set shape of the response
            FolderResponseShapeType shape = FolderResponseShapeType.Factory.newInstance();
            shape.setBaseShape(DefaultShapeNamesType.ID_ONLY);
            getFolder.setFolderShape(shape);
           
            // ash for inbox folder
            DistinguishedFolderIdType distinguishedFolderId = DistinguishedFolderIdType.Factory.newInstance();
            distinguishedFolderId.setId(DistinguishedFolderIdNameType.INBOX);
           
            EmailAddressType emailAddress = EmailAddressType.Factory.newInstance();
            emailAddress.setEmailAddress(strAddress); // this must me an exsiting mailbox
            distinguishedFolderId.setMailbox(emailAddress);
           
            NonEmptyArrayOfBaseFolderIdsType folderIds = NonEmptyArrayOfBaseFolderIdsType.Factory.newInstance();
            folderIds.setDistinguishedFolderIdArray(new DistinguishedFolderIdType [] {distinguishedFolderId} );
           
            // finally
            getFolder.setFolderIds(folderIds);
           
            request.setGetFolder(getFolder);
           
            // invoke stub method now
            GetFolderResponseDocument response = m_EWSservice.GetFolder(request, null, null, null, null);
           
            // TODO: analyse response
            FolderInfoResponseMessageType folderInfo =
                response.getGetFolderResponse().getResponseMessages().getGetFolderResponseMessageArray(0);
           
            if (folderInfo.getResponseCode().equals(ResponseCodeType.NO_ERROR)){
               
                // only id is in the response cause ID_ONLY was set
                return folderInfo.getFolders().getFolderArray(0).getFolderId().getId();
            }
            else {
                return null;
            }
        }


    Hervé
    Thursday, March 6, 2008 9:01 AM
  • Hi I used JAXWS to generate the java Exchange stub.  I don't have Exchange Impersonation or Delegation enabled, and the systems guys don't want me to do that.  The EWS is setup with Basic authentication.  

     

    I have a servlet perform the basic authentication to EWS with a logged in user's credentials, then make calls to the ExchangeServiceBinding for getItem, updateItem, etc--this works for the first user to hit the servlet.  The second user to hit the servlet makes calls to do the basic authentication to EWS, and there are no errors but he gets the first user's info.

     

    I have added "no-cache" headers, etc to the servlet--this doesn't appear to do anything.  It seems that whoever is the first to hit the servlet with credentials and the servlet does the basic authentication that stays for any other user hitting the servlet. 

     

    I need this to be a multi-user web application--what am I doing wrong?

     

    Wednesday, March 12, 2008 9:12 PM
  •  

    Hi Herve,

     

    Thanks for the sample, i have tried your sample but i could able to use your example to get the solution and some of the class are not found in my created stub package

     

    Example : the class "ExchangeWebServiceStub" is not found in package instead of that i have "ExchangeServiceBindingStub" So please if possible mail your stub package to use it here

     

    My mail id is sridhar@adaptime.net or sridhar_keystone2004@yahoo.com

     

    Please help me to start work in Exchange server 

     

    here is my work done :

     

     

    I have done the following way to communicated the Exchange server using web service


    Step 1:

    I have generated Exchange server client stub using services.wsdl, Message.xsd and type.xsd by using the command


    (java org.apache.axis.wsdl.WSDL2Java -d "Application" -s -o ews -u Services.wsdl)


    After that i have corrected the package using eclipse IDE to create the class file.



    Step 2:

    The stub given deploy.wsdd and undeploy.wsdd files for enable the exchange web service in tomcat


    Deployed using the command

    java -Dhttp.proxyHost=192.168.2.93 -Dhttp.proxyPort=8080 org.apache.axis.client.AdminClient deploy.wsdd


    Step 3:

    We confirmed that the Exchange service enabled in Tomcat Axis ( but i am not sure

     

    Step 4:

    We have tried Some examples to get some response from the web service and I have attached the sample which we have tried here. Still we don't any response from service end.


    The service throws the error like


    ex : AxisFault

    faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException

    faultSubcode:

    faultString: org.xml.sax.SAXException: Invalid element in com.microsoft.schemas.exchange.services._2006.messages.CreateItemType - CreateItem

    faultActor:

    faultNode:

    faultDetail:

    {http://xml.apache.org/axis/}hostname:adaptime


    ex : [Lorg.w3c.dom.Element;@a4488

    Fault :: ns1:hostname, null, adaptime

    status : org.xml.sax.SAXException: Invalid element in com.microsoft.schemas.exchange.services._2006.messages.CreateItemType - CreateItem


    And i have posted my sample in your another post


    http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=2233013&SiteID=17

     

    and i have following your last post instruction and i am using Axis1.4 for the web service. is this the correct one i am using ?

    Thursday, March 13, 2008 5:35 AM
  • Hello,

    I use Axis2 1.3

    the command line I use to generate my package is :
    wsdl2java -d xmlbeans -s -ss -g -o ews -uri Services.wsdl

    the generated package compile without code modifications.

    You should manage to create your own valid packahe using axis.

    Hervé


    Thursday, March 13, 2008 9:09 AM
  •  

    Hi Hervé

     

    Thanks for the reply and it help me lot that we have use Axis2 1.3 version for creating the Exchange server stub

    I have created the stub and compiled abd i have implemented your example post perviously.

     

    Please let me know the step to enable the Excahnge service in tomcat. I have installed the axis in Tomcat

     

     

    sri

    Wednesday, March 19, 2008 9:12 AM
  • Hi Sri,

    I am not sure I understand your question.

    You don't need to install tomcat to use the exchange web service.
    once your EWS package is generated, you could make a JAR and use it as any other package in a java project. (I did that)
    However during execution you will need some AXIS jar to make it work.

    Here are the Jars I need when running my java application:

    commons-logging.jar;
    log4j.jar;
    commons-httpclient-3.0.1.jar;
    xbean-2.2.0.jar;
    axis2-kernel-1.3.jar;
    connector2007ews.jar; // my own ews package
    annogen-0.1.0.jar;
    axiom-api-1.2.5.jar;
    axiom-impl-1.2.5.jar;
    backport-util-concurrent-2.2.jar;
    commons-codec-1.3.jar;
    httpcore-4.0-alpha5.jar;
    wsdl4j-1.6.2.jar;
    XmlSchema-1.3.2.jar;

    But If you talk about receiving the pushNotifications to a web server, here you could need tomcat but this is another subject.

    Did I understand what you meant ?

    Hervé
    Wednesday, March 19, 2008 9:35 AM
  • Hi Hervé

     

    Thanks for the reply.

     

    Yes you are right, i am asking about the pushNotification to a web server. I understand the concept what you are come to tell.

     

    I will try and let you know the status

     

    i have tried your sample and i got the error

     

    log4j:WARN No appenders could be found for logger (org.apache.axis2.description.AxisService).

    log4j:WARN Please initialize the log4j system properly.

    Exception in thread "main" java.lang.NullPointerException

    at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:720)

    at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1321)

    at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:386)

    at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:170)

    at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:396)

    at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:346)

    at org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:520)

    at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:191)

    at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:77)

    at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:327)

    at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:206)

    at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:396)

    at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:374)

    at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:211)

    at org.apache.axis2.client.OperationClient.execute(OperationClient.java:163)

    at com.microsoft.schemas.exchange.services._2006.messages.ExchangeWebServiceStub.GetFolder(ExchangeWebServiceStub.java:1317)

    at exchangeClient.impl.MsExchangeEmail.getInboxId(MsExchangeEmail.java:215)

    at exchangeClient.impl.MsExchangeEmail.main(MsExchangeEmail.java:172)

     

     

    do you have any idea about this ?

     

     

    Wednesday, March 19, 2008 11:37 AM
  •  

    Hi Hervé

     

    The above posted problem is due to the sslSocket and i have solved the problem. And finally i got one more error in auntheticate

     

    the error is

     

    org.apache.axis2.AxisFault: peer not authenticated

    at org.apache.axis2.AxisFault.makeFault(AxisFault.java:417)

    at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:195)

    at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:77)

    at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:327)

    at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:206)

    at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:396)

    at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:374)

    at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:211)

    at org.apache.axis2.client.OperationClient.execute(OperationClient.java:163)

    at com.microsoft.schemas.exchange.services._2006.messages.ExchangeWebServiceStub.GetFolder(ExchangeWebServiceStub.java:1317)

    at exchangeClient.impl.MsExchangeEmail.getInboxId(MsExchangeEmail.java:215)

    at exchangeClient.impl.MsExchangeEmail.main(MsExchangeEmail.java:172)

    Caused by: javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

    at com.sun.net.ssl.internal.ssl.SSLSessionImpl.getPeerCertificateChain(Unknown Source)

    at exchangeClient.impl.AlcSSLSocketFactory.verifyHostname(AlcSSLSocketFactory.java:173)

    at exchangeClient.impl.AlcSSLSocketFactory.createSocket(AlcSSLSocketFactory.java:248)

    at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:706)

    at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1321)

    at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:386)

    at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:170)

    at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:396)

    at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:346)

    at org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:520)

    at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:191)

    ... 10 more

     

    Please Check the error and let you know your view to correct the problem and i am trying here to solve the problem

     

     

    Sri

    Wednesday, March 19, 2008 12:05 PM
  • Sri,

    Could you start a new thread ?
    I guess that now, your ews package is generated and works. The curent thread is not anymore needed.

    Now we need to dig into the axis2 engine and the push notifications, right ?

    I remember that subscribing to push notifications was not too complicated,
    however receiving the notifications was another point (see http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=2175043&SiteID=17)

    Let me know and remind me exactly the steps already done.


    Hervé
    Wednesday, March 19, 2008 1:02 PM
  • OK I figured this out.  JAXWS does a GET when you instantiate the Service object.  Use java.net.Autnenticator to authenticate to Exchange Web Service at that point with an operating system proxy user if you have one or the current user--they become the proxy user at that point.

     

    when you access a EWS operation, such as GetItem, you reset the basic authentication credentials for that request via the BindingProvider methods.

    ((BindingProvider)proxy).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "userfoo");

    ((BindingProvider)proxy).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "passbar");

     

    Wednesday, March 19, 2008 3:34 PM
  •  

    Hi Hervé,

     

    Please check the new thread for my details

     

    https://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=3035502&SiteID=17&mode=1

     

    And let me know your comments

    Thursday, March 20, 2008 9:14 AM
  • Hello Lakshmi,

     

       It's really help us to know the services of the exchange web services. can you  send us simple java soap code for access the ews? We are struggling in this place long time.

     

    Thanks in advance,

     

    Bagy

     

    Wednesday, April 2, 2008 7:06 AM
  • Hello Heather,

     

          I'm very happy to heard the news from you. I'm also working in exchange server connection with java.

    There is no sample code in the forum. Can you please send any sample code without authentication problem?

    I'm waiting for your reply.

     

     

     

    by

    bagy

     

    Friday, April 4, 2008 11:48 AM

  • Dear Herve,

       Thanks for all your posts of communication between Java Interface with Exchange 2K7 Web services. Atpresent I'm working in Exchange server communication with java for retrieve the details of Exchange server attributes(i.e mail,task and calender).
    I have created java proxy classes using Axis2 1.3 without any compilation errrs. Then I have tried the sample code of getInbox folder item for particular id. While running the sample using Eclipse IDE I'm getting the following Unauthorized error,

    org.apache.axis2.AxisFault: Transport error: 401 Error: Unauthorized
        at org.apache.axis2.transport.http.HTTPSender.handleResponse(HTTPSender.java:298)
        at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:192)
        at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:77)
        at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:327)
        at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:206)
        at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:396)
        at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:374)

    Could please give some advice for the clarifications?

    1. Shall I have to set any authorization in IIS(Internet Information server)? Or
    2. Shall I have to set any authorization in Exchange server?
    3. Shall I have to create any credentials for my java test class(because one of the forum friend said have to set Network credentials like .Net) ?

    Regards,

    Bagyaraj.

    Monday, April 14, 2008 7:13 AM
  • Hi,

    You have to set some specific rights on the exchange server for the user you are using.

    for instance in the Exchange management shell:

    Add-MailboxPermission "mailbox1" -User mySuperUser -AccessRights FullAccess
    Add-MailboxPermission "mailbox1" -User mySuperUser -ExtendedRights "Send As"



    You don't seem  to have trouble with credentials, you get a 401 unaithorized which is the response of the Exchange server and not some intermediate SSL error.

    Hervé
    Monday, April 14, 2008 7:33 AM

  • Hello Herve,

       Thank you very much for the reply. I have set the rights to user in the exchange server. The same error will thrown,
    The following lines are my sample, Could you please check whether the code is correct??

    import java.rmi.RemoteException;
    import java.util.ArrayList;
    import java.util.List;
    import org.apache.axis2.client.Options;
    import org.apache.axis2.transport.http.HttpTransportProperties.Authenticator;
    import org.apache.commons.httpclient.protocol.Protocol;
    import com.microsoft.schemas.exchange.services._2006.messages.ExchangeWebServiceStub;
    import com.microsoft.schemas.exchange.services._2006.messages.FolderInfoResponseMessageType;
    import com.microsoft.schemas.exchange.services._2006.messages.GetFolderDocument;
    import com.microsoft.schemas.exchange.services._2006.messages.GetFolderResponseDocument;
    import com.microsoft.schemas.exchange.services._2006.messages.GetFolderType;
    import com.microsoft.schemas.exchange.services._2006.messages.ResponseCodeType;
    import com.microsoft.schemas.exchange.services._2006.types.DefaultShapeNamesType;
    import com.microsoft.schemas.exchange.services._2006.types.DistinguishedFolderIdNameType;
    import com.microsoft.schemas.exchange.services._2006.types.DistinguishedFolderIdType;
    import com.microsoft.schemas.exchange.services._2006.types.EmailAddressType;
    import com.microsoft.schemas.exchange.services._2006.types.FolderResponseShapeType;
    import com.microsoft.schemas.exchange.services._2006.types.NonEmptyArrayOfBaseFolderIdsType;

    public class testing
    {
        private static String getInboxId(ExchangeWebServiceStub m_EWSservice,
                String strAddress) throws RemoteException
        {
            GetFolderDocument request = com.microsoft.schemas.exchange.services._2006.messages.GetFolderDocument.Factory
                    .newInstance();
            GetFolderType getFolder = com.microsoft.schemas.exchange.services._2006.messages.GetFolderType.Factory
                    .newInstance();
            FolderResponseShapeType shape = com.microsoft.schemas.exchange.services._2006.types.FolderResponseShapeType.Factory
                    .newInstance();
            shape.setBaseShape(DefaultShapeNamesType.ID_ONLY);
            getFolder.setFolderShape(shape);
            DistinguishedFolderIdType distinguishedFolderId = com.microsoft.schemas.exchange.services._2006.types.DistinguishedFolderIdType.Factory
                    .newInstance();
            distinguishedFolderId.setId(DistinguishedFolderIdNameType.INBOX);
            EmailAddressType emailAddress = com.microsoft.schemas.exchange.services._2006.types.EmailAddressType.Factory
                    .newInstance();
            emailAddress.setEmailAddress(strAddress);
            distinguishedFolderId.setMailbox(emailAddress);
            NonEmptyArrayOfBaseFolderIdsType folderIds = com.microsoft.schemas.exchange.services._2006.types.NonEmptyArrayOfBaseFolderIdsType.Factory
                    .newInstance();
            folderIds
                    .setDistinguishedFolderIdArray(new DistinguishedFolderIdType[] { distinguishedFolderId });
            getFolder.setFolderIds(folderIds);
            request.setGetFolder(getFolder);

            GetFolderResponseDocument response = null;
            response = m_EWSservice.GetFolder(request, null, null, null, null);

            FolderInfoResponseMessageType folderInfo = response
                    .getGetFolderResponse().getResponseMessages()
                    .getGetFolderResponseMessageArray(0);

            if (folderInfo.getResponseCode().equals(ResponseCodeType.NO_ERROR))
                return folderInfo.getFolders().getFolderArray(0).getFolderId()
                        .getId();
            else
                return null;
        }

        public static void main(String args[])
        {
            String m_user = "administrator";
            String m_password = "super000";

            ExchangeWebServiceStub m_EWSservice = null;

            String ewsUrl = "https://manager/EWS/exchange.asmx";

            String host = "domain";

            String domain = "domain.local";

            Protocol AlcHttpsProtocol = new Protocol("https",
                    new MySSLSocketFactory(), 443);
            Protocol.registerProtocol("https", AlcHttpsProtocol);
            try
            {
                m_EWSservice = new ExchangeWebServiceStub(null, ewsUrl);
            }
            catch (RemoteException e)
            {
                e.printStackTrace();
            }
            Options options = m_EWSservice._getServiceClient().getOptions();

            Authenticator authenticator = new org.apache.axis2.transport.http.HttpTransportProperties.Authenticator();

            List authScheme = new ArrayList();
            authScheme.add("NTLM");

           
            authenticator.setAuthSchemes(authScheme);
            authenticator.setUsername(m_user);
            authenticator.setPassword(m_password);
            authenticator.setHost(host);

            if (domain != null)
                authenticator.setDomain(domain);

            authenticator.setPort(443);

            options .setProperty(org.apache.axis2.transport.http.HttpTransportProperties.Authenticator.NTLM,                            authenticator);

            m_EWSservice._getServiceClient().setOptions(options);

            try
            {
                String resultId = getInboxId(m_EWSservice, "administrator@domain.local");
                if( resultId == null)
                System.out.println((new StringBuilder("inbox folder id:")).append(resultId).toString());
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    Thanks in advance

    Regards,

    Bagyaraj.
    Monday, April 14, 2008 10:11 AM
  • Yes, code seems correct;
    however check your host and domain  variable (??)

    if you still get a 401 error , in my opinion, the problem really comes from rights.
    did you truy to acess a mailbox via OWA and the user and password you use here?

    uiWhile OWA does not work, you can't make you application  works either.
    (https://youeExchangeServer/owa )
    Monday, April 14, 2008 10:19 AM

  • Hello Herve,

         I have checked my host and domain, the sample contains correct names. And I'm unable to access Exchange service using OWA. ie https://manager/owa are working fine. But I don't know what's problem in the exchange server.


    Regards,

    Bagyaraj.
    Monday, April 14, 2008 12:28 PM
  • Hello Herve,

      sorry for the disturb, I have tried to set some access rights my user, but I'm not able to communicate with Exchange server.
    can you tell us shall we set any other rights for my user? or shall we use any third party code for communicate exchange server.

    Thanks in advance,

    Regards,

    Bagyaraj.



    Tuesday, April 15, 2008 10:45 AM
  • It seems that you are on the same blocking situation as Sridhaar (another poster)
     Unfortunately i'm afraid I shared with you two all my knowledge on the subject and the relevant code ...

    What more can i do ?

    Tuesday, April 15, 2008 11:35 AM

  • Helloo Herve,

        One small clarification from you, can I install Exchange server service pack1 for EWS communication?
    Because I'm using Exchange server without service pack.

    Thanks in advance

    Bagyaraj.
    Wednesday, April 16, 2008 3:46 PM
  •  

    sure,

    I use the Exchange SP1 since january,

    I had to re-generate the EWS JAVA proxy because WSDL has changed

    but it works nice.

     

     

    Wednesday, April 16, 2008 3:51 PM

  • Hello Herve,

       I have installed the Exchange server SP1 and removed the unwatted characters from messages.xsd and types.xsd. Then I have tried to create EWS folder using new wsdl, xsd files the following exception will thrown,

    Using AXIS2_HOME:   E:\EWSCreationAxis2-1.3\axis2-1.3
    Using JAVA_HOME:    C:\Program Files (x86)\Java\jdk1.5.0_05
    Retrieving schema at 'messages.xsd', relative to 'file:/E:/EWSCreationAxis2-1.3/axis2-1.3/bin/'.
    Retrieving schema at 'types.xsd', relative to 'file:/E:/EWSCreationAxis2-1.3/axis2-1.3/bin/messages.xsd'.
    Exception in thread "main" org.apache.axis2.wsdl.codegen.CodeGenerationException: Error parsing WSDL
            at org.apache.axis2.wsdl.codegen.CodeGenerationEngine.<init>(CodeGenerationEngine.java:147)
            at org.apache.axis2.wsdl.WSDL2Code.main(WSDL2Code.java:35)
            at org.apache.axis2.wsdl.WSDL2Java.main(WSDL2Java.java:24)
    Caused by: org.apache.axis2.AxisFault: No service was not found in the WSDL at file:/E:/EWSCreationAxis2-1.3/axis2-1.3/bin/ with targetnamespace http://schemas.
    microsoft.com/exchange/services/2006/messages      at org.apache.axis2.description.WSDL11ToAllAxisServicesBuilder.populateA
    llServices(WSDL11ToAllAxisServicesBuilder.java:117)       at org.apache.axis2.wsdl.codegen.CodeGenerationEngine.<init>(CodeGenerationEngine.java:141)
            ... 2 more

    could please help me how to avoid this exception?

    Thanks in advance

    Bagyaraj.
    Thursday, April 17, 2008 9:19 AM
  •  

    as explain before, Microsft omitted the service element in its WSDL file

     

        <wsdlTongue Tiedervice name="ExchangeWebService">
        <wsdlStick out tongueort name="ExchangeWebPort" binding="tns:ExchangeServiceBinding">
          <soap:address location="https://frbrj210.eccdevr5.atabrest.fr/EWS/exchange.asmx"/>
        </wsdlStick out tongueort>
      </wsdlTongue Tiedervice>

     

    see http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=2027791&SiteID=17

     

    Thursday, April 17, 2008 9:23 AM

  • hi Herve,would u mind sending me the java stub generated by Axis.I would appreciate if u will send the code samples.
    May u send through ntthang_338f@hotmail.com
    Thanks in advance.
    Thursday, April 17, 2008 10:06 AM

  • Hello Herve,

        I have created new EWS using Exchange server SP1 but still the same sad result. Could you tell me
    shall I have to give any authorization setting in Exchange server or IIS while install the softwares?
    Or shall I have to disable the any proxy settings in the machine?
    Could you please send your sample project communication of Exchange server SP1?
    This is my mail Id bagyafriends@gmail.com & palani.bagyaraj@gmail.com




    Thanks in advance

    Bagyaraj.
    Thursday, April 17, 2008 1:11 PM

  • Hello Herve,

       Sorry for the disturb you, I know you have helped me very lot. Here I don't thing problem in the authentication credentials.
    Because I'm able to view services.wsdl(https://bagyaraj/EWS/services.wsdl), messages.xsd(https://bagyaraj/EWS/messages.xsd) and types.xsd(https://bagyaraj/EWS/types.xsd) with out any problem using my mailbox user. Shall I have to provide any authentication my java class? Please advice me in this stage.

    The following are my Socket factory class please check my socket factory whether it is right

    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.InetSocketAddress;
    import java.net.Socket;
    import java.net.SocketAddress;
    import java.net.UnknownHostException;
    import javax.net.SocketFactory;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.SSLSocketFactory;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;
    import org.apache.commons.httpclient.ConnectTimeoutException;
    import org.apache.commons.httpclient.HttpClientError;
    import org.apache.commons.httpclient.params.HttpConnectionParams;
    import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
    import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;

    public class MySSLSocketFactory implements ProtocolSocketFactory
    {
        private SSLContext sslcontext = null;
        private SSLContext createEasySSLContext()
        {
            try
            {
                X509TrustManager trustMgr = new MyTrustManager();
                TrustManager trustMgrs[] = { trustMgr };

                SSLContext context = SSLContext.getInstance("SSL");
                context.init(null, trustMgrs, null);
                return context;
            }
            catch (Exception e)
            {
                e.printStackTrace();
                throw new HttpClientError(e.toString());
            }
        }

        /**
         * Retrieves SSL context.
         *
         * @return SSLContext.
         */
        private SSLContext getSSLContext()
        {
            if (this.sslcontext == null)
            {
                this.sslcontext = createEasySSLContext();
            }
            return this.sslcontext;
        }

        /**
         * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int)
         */
        public Socket createSocket(String host, int port, InetAddress clientHost,
                int clientPort) throws IOException, UnknownHostException
        {

            return getSSLContext().getSocketFactory().createSocket(host, port,
                    clientHost, clientPort);
        }

        public Socket createSocket(final String host, final int port,
                final InetAddress localAddress, final int localPort,
                final HttpConnectionParams params) throws IOException,
                UnknownHostException, ConnectTimeoutException
        {
            if (params == null)
            {
                throw new IllegalArgumentException("Parameters may not be null");
            }
            int timeout = params.getConnectionTimeout();
            SocketFactory socketfactory = getSSLContext().getSocketFactory();
            if (timeout == 0)
            {
                return socketfactory.createSocket(host, port, localAddress,
                        localPort);
            }
            else
            {
                Socket socket = socketfactory.createSocket();
                SocketAddress localaddr = new InetSocketAddress(localAddress,
                        localPort);
                SocketAddress remoteaddr = new InetSocketAddress(host, port);
                socket.bind(localaddr);
                socket.connect(remoteaddr, timeout);
                return socket;
            }
        }


        public Socket createSocket(String host, int port) throws IOException,
                UnknownHostException
        {
            return getSSLContext().getSocketFactory().createSocket(host, port);
        }

        public Socket createSocket(Socket socket, String host, int port,
                boolean autoClose) throws IOException, UnknownHostException
        {
            return getSSLContext().getSocketFactory().createSocket(socket, host,
                    port, autoClose);
        }

        public boolean equals(Object obj)
        {
            return ((obj != null) && obj.getClass().equals(SSLSocketFactory.class));
        }

        public int hashCode()
        {
            return MySSLSocketFactory.class.hashCode();
        }

    }



    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import javax.net.ssl.*;

    public class MyTrustManager implements X509TrustManager
    {
        public MyTrustManager()
        {
        }
        public void checkClientTrusted(X509Certificate ax509certificate[], String s)
                throws CertificateException
        {
        }

        public void checkServerTrusted(X509Certificate ax509certificate[], String s)
                throws CertificateException
        {
        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers()
        {
            return null;
        }

    }

    Thanks in advance

    Bagyaraj.
    Thursday, April 17, 2008 3:47 PM
  •  

    there is something strange ...

     

    i get :

    org.apache.axis2.AxisFault: Transport error: 401 Error: Unauthorized

    at org.apache.axis2.transport.http.HTTPSender.handleResponse(HTTPSender.java:298)

    at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:192)

    at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:77)

    at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:327)

    at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:206)

    at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:396)

    at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:374)

    at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:211)

    at org.apache.axis2.client.OperationClient.execute(OperationClient.java:163)

    at com.microsoft.schemas.exchange.services._2006.messages.ExchangeWebServiceStub.GetFolder(Unknown Source)

    at com.alcatel.connector.exchange.AlcExchangeClientAccessServer.getInboxId(AlcExchangeClientAccessServer.java:343)

    at com.alcatel.connector.exchange.AlcExchangeClientAccessServer.main(AlcExchangeClientAccessServer.java:308)

     

    when i I replace my class with yours....

    but they look identical !!!  

    Maybe If I find the solution i Could resolve your problem. (and Sri's ones too)

     

    I'll let you know

    Thursday, April 17, 2008 4:28 PM
  •  

    I found it !!!

     

    there is a mistake in

     

    Code Snippet
     public boolean equals(Object obj)
        {
            return ((obj != null) && obj.getClass().equals(SSLSocketFactory.class));
        }

     

     


    replace SSLSocketFactory by the  name of the class (e.g MySSLSocketFactory )

     

    I tried it and it works now.

     

    Thursday, April 17, 2008 4:35 PM

  • Thanks a lot Herve, I'm able retrieve particular user inbox id. I'll start my next step. Once again Thank you very much Herve.

    Bagyaraj.
    Friday, April 18, 2008 3:46 AM

  • I replace it but it generates the error:

    log4j:WARN No appenders could be found for logger (org.apache.axis2.description.AxisService).
    log4j:WARN Please initialize the log4j system properly.
    Exception in thread "main" java.lang.ExceptionInInitializerError
            at org.apache.axis2.util.XMLUtils.toOM(XMLUtils.java:564)
            at org.apache.axis2.deployment.DescriptionBuilder.buildOM(DescriptionBuilder.java:96)
            at org.apache.axis2.deployment.AxisConfigBuilder.populateConfig(AxisConfigBuilder.java:79)
            at org.apache.axis2.deployment.DeploymentEngine.populateAxisConfiguration(DeploymentEngine.java:615)
            at org.apache.axis2.deployment.FileSystemConfigurator.getAxisConfiguration(FileSystemConfigurator.java:115)
            at org.apache.axis2.context.ConfigurationContextFactory.createConfigurationContext(ConfigurationContextFactory.java:64)
            at org.apache.axis2.context.ConfigurationContextFactory.createConfigurationContextFromFileSystem(ConfigurationContextFactory.java:180)
            at org.apache.axis2.client.ServiceClient.configureServiceClient(ServiceClient.java:146)
            at org.apache.axis2.client.ServiceClient.<init>(ServiceClient.java:139)
            at com.microsoft.schemas.exchange.services._2006.messages.ExchangeWebServiceStub.<init>(Unknown Source)
            at com.microsoft.schemas.exchange.services._2006.messages.ExchangeWebServiceStub.<init>(Unknown Source)
            at MsExchangeEmail.main(MsExchangeEmail.java:31)
    Caused by: java.lang.IllegalStateException: No valid ObjectCreator found.
            at org.apache.axiom.om.util.StAXUtils$Pool.<init>(StAXUtils.java:64)
            at org.apache.axiom.om.util.StAXUtils.<clinit>(StAXUtils.java:88)
            ... 12 more
    Java Result: 1

    Friday, April 18, 2008 8:11 AM

  • Hi Herve, the code seems to have a lot of errors when I replace in my project.Last time,I received the stub from Sri which u sent to Sri.
    Here are some of the errors that I found in my project.

    1/GetFolderType getFolder = GetFolderType.Factory.newInstance();
    I have to replace wif
    GetFolderType getFolder = GetFolderType.class.newInstance();
    2/
    folderIds.setDistinguishedFolderIdArray(new DistinguishedFolderIdType [] {distinguishedFolderId} );
    there is no set method here.
    3/I dont know why it generates the error
    response.getGetFolderResponse().getResponseMessages().getGetFolderResponseMessageArray(0);
    Friday, April 18, 2008 10:09 AM

  • hi,I have this error when I try to run the code.

    log4j:WARN No appenders could be found for logger (org.apache.axis.i18n.ProjectResourceBundle).

    log4j:WARN Please initialize the log4j system properly.

    Friday, April 18, 2008 11:18 AM
  • Hi,

    you'd better generate your own package with AXIS2 1.3 and the -d xmlbeans options (for XMLbeans framework)

    then you need the MySSLSocketFactory and MyTrustManager to pass the authentication.

     

    I'm not sure but I thougt i've seen in one previous post that you use JAX-WS ?? it is 2 different APIs.

     

    concerning the log4j logs it is only warning and it is due to a bad log4j configuration.

     

    Friday, April 18, 2008 11:49 AM

  • the one that I generated can't be used. I follow all the steps that Sri told in his post.However,I have the java package wif more than 1000 warnings.Last time,he sent me his package then I tried to test the MySSLSocketFactory and MyTrustManager as well as the code for getInboxId, but it seems not work.

    Regarding JAXWS, I tried 2 approaches for this project. However, both 2 doesn't work.
    Sad The due-date for my project is coming in next week.
    I appreciate any help from u.

    Friday, April 18, 2008 11:55 AM

  • To summarize what I have done so far with Axis 2.1.3:
    at first I tried to generate the java stub,however, the java stub has more than 1000 warnings Sad . I wonder I did anything wrong,coz last time,Sri told that he could successfully generate the java stub with Axis 2.1.3
    Now,I have the java stub from Sri.
    I tried the MySSLSocketFactory and MyTrustManager,however, it has compiled error such as :

    1/GetFolderType.Factory.newInstance() , there is no method in the java package.Instead, I changed to GetFolderType.class.newInstance()

    2/folderIds.setDistinguishedFolderIdArray(......)
    it seems this method doesn't exist. I have to change the GET instead of SET.
    With the GET method , I can get the reference of the OBJECT and just change the content of this OBJECT.

    There are some addtional compiled errors.Would u mind show me how to connect to Exchange Server .

    Thanks very much.


    Friday, April 18, 2008 12:05 PM
  • 1000 warnings are not really a matter it is mainly because of JAVA6 and the generic type.

    you can use the package with JAVA 5 if you really want to avoid warnings.

    the most important is to not have error in the generated package !!

     

    Could you explain your errors,  I can't tell you that I will be able to help you, but Sri and Bagy are now as expert in JAVA EWS than I.

     

    The JAVA EWS package you received is the result of weeks of work... 

     

    Good luck Hervé.

    Friday, April 18, 2008 12:09 PM

  • thanks for your quick reply Big Smile

    however, when I tried to test the code. It has some syntax errors.I think that I used the java package that u sent us Stick out tongue but it still has those syntax errors.

    1/GetFolderType.Factory.newInstance() , there is no method in the java package.Instead, I changed to GetFolderType.class.newInstance()
    2/folderIds.setDistinguishedFolderIdArray(......)


    Would u mind send me the sample codes for connect to Exchange Server ? My mailbox id is ntthang_338f@hotmail.com

    thanks very much
    Friday, April 18, 2008 12:20 PM
  •  

    Generate your own package with wsdl2java and -d xmlbeans options, giving the Services.wsdl file and its associated xsd files.

    (it takes less than 2 minutes)

    wsdl2java -d xmlbeans -s -ss -g -o yourFolderPackage -uri Services.wsdl

     

    import the generated source and class in a java project.

    add all necessary jars to ytour project.

    there is no error after compilation, only warning.

     

     

     

     

     

    Friday, April 18, 2008 1:11 PM

  • hi Herve,
    just to confirm.
    With Axis 2.1.3 (Standard Binary Distribution) I only have to add the service element of Services.wsdl ?

    <wsdlTongue Tiedervice name="ExchangeServices">
         <wsdlStick out tongueort name="ExchangeServicePort" binding="tns:ExchangeServiceBinding">
           <soap:address location="http://152.96.11.51/EWS/Services.wsdl"/>
         </wsdlStick out tongueort>
       </wsdlTongue Tiedervice>

    In my situation, I put the Services.wsdl in the App Server (152.96.11.51) while Exchange Server resides on another machine (152.96.11.53).
    Do I have to change anything in types.xsd and messages.xsd

    thanks a lot
    Friday, April 18, 2008 1:20 PM
  •  

    actually  the location set in the wsdl is not important as long as you set the host and domain when creating you ExchangeWebServiceStub

     

    new ExchangeWebServiceStub(null, https://152.96.11.51/EWS/exchange.asmx);

     

     

    Friday, April 18, 2008 1:31 PM

  • May I confirm with you something ?
    I will use JDK 1.5 instead of JDK 1.6
    Axis 2.1.3 (Standard Binary Distribution)
    How about Ant(I also use Ant 1.7) and Tomcat ? I remeber in one post , u told me that there is no need for Tomcat .

    Anyway, my setup is like this.

    I changed the environment variables :

    AXIS_HOME : C:\axis2-1.3
    JAVA_HOME :  C:\Program Files\Java\jdk1.5.0_15
    TOMCAT_HOME : C:\Program Files\Apache Software Foundation\Apache Tomcat 6.0.14
    ANT_HOME : C:\Program Files\apache-ant-1.7.0
    PATH: %AXIS2_HOME%\bin;%AXIS_HOME%\webapp; %ANT_HOME%\bin;%TOMCAT_HOME%\common\lib;

    then
    wsdl2java -d xmlbeans -s -ss -g -o yourFolderPackage -uri Services.wsdl

    This is all the necessary jar files right ?

    common-logging-1.1.jar
    log4-1.2.14.jar
    commons-httpclient-3.0.1.jar;  
    xbean-2.2.0.jar;   
    axis2-kernel-1.3.jar;   
    annogen-0.1.0.jar;   
    axiom-api-1.2.5.jar; 

    axiom-impl-1.2.5.jar;

    backport-util-concurrent-2.2.jar;
    commons-codec-1.3.jar;
    httpcore-4.0-alpha5.jar;  

    wsdl4j-1.6.2.jar;
    XmlSchema-1.3.2.jar;



    Friday, April 18, 2008 2:00 PM

  • thanks a lot . I can generate the stubs already.
    May I ask the host and the domain .
    Is this the IP add of the Exchange Server or the App Server where I put the WSDL file in.
    I am quite wonder this.
    Friday, April 18, 2008 2:02 PM
  •  

    the host and domain are the one where the Exchange 2007 server is running.

     

    to answer your previous post,

    I don't use Tomcat, ( we are making a java application - client - to consume Exchange 2007 service)

     

     

     

    Friday, April 18, 2008 2:06 PM

  • after I generate the java stub.I have 2 folders resources and src and 1 file build.xml

    I used Eclipse to create new java project.Do I have copy and paste all the 2 folders and build.xml to the corresponding places in the new java project or I only have to put the src folder

    I have 2 errors (it is better than last time), This time I used JDK5 and I imported all the necessary jar files.
    the 2 errors are as follow :
    1/The project was not built since its build path is incomplete.Cannot find the class file for javax.xml.stream.XMLStreamReader.Fix the build path then building this project
    2/The type javax.xml.stream.XMLStreamReader cannot be resolved.It is indirectly referenced from required .class file

    Thanks for your kindly help.
    Friday, April 18, 2008 2:18 PM
  • hi Herve,
    may I ask which tool u used to generate the java package (Eclipse or Java)?
    Currently,when I checked again the generated java package :
    when I imported into Eclipse , I had 2 errors :
    1/The project was not built since its build path is incomplete.Cannot find the class file for javax.xml.stream.XMLStreamReader.Fix the build path then building this project
    2/The type javax.xml.stream.XMLStreamReader cannot be resolved.It is indirectly referenced from required .class file
    when I imported into Net Beans , I had a bunch of errors




    Monday, April 21, 2008 8:45 AM

  • hi Herve,
    I am very sorry for disturb u again.
    When I try to generate the stub by myself, I found that there are 2 jar files that I don't have.

    common-logging-1.1.jar
    log4-1.2.14.jar

    I managed to find the 2 substitutes i.e. the different version.
    May I ask where do u get the 2 jar files (wif correct versions) ?
    I am not sure if we use different version whether it will limit any functionality of the project.Coz the last time I generate the java stub (according to your suggestions), now it is really better than the previous one,however, there is still 2 errors and I am still can't use the stub file wif 2 errors.  Big Smile.

    Hope to hear from u soon.
    Monday, April 21, 2008 9:22 AM

  • hi Herve,
    when I tried to run this sample code.
    I had 2 problems :
    2 warnings wif initializing log4j, and 1 ClassNotFound error

     java.lang.ClassNotFoundException: schemaorg_apache_xmlbeans.system.s910A9A71E4C15BDE14230B4F92DDA8E5.TypeSystemHolder

    The following is the result of my Run command.

    log4j:WARN No appenders could be found for logger (org.apache.axis2.description.
    AxisService).
    log4j:WARN Please initialize the log4j system properly.
    Exception in thread "main" java.lang.ExceptionInInitializerError
            at com.microsoft.schemas.exchange.services._2006.messages.GetFolderDocum
    ent$Factory.newInstance(GetFolderDocument.java:48)
            at connection.getInboxId(connection.java:68)
            at connection.main(connection.java:58)
    Caused by: java.lang.RuntimeException: Cannot load SchemaTypeSystem. Unable to l
    oad class with name schemaorg_apache_xmlbeans.system.s910A9A71E4C15BDE14230B4F92
    DDA8E5.TypeSystemHolder. Make sure the generated binary files are on the classpa
    th.
            at org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(XmlBeans.java:7
    83)
            at com.microsoft.schemas.exchange.services._2006.messages.GetFolderDocum
    ent.<clinit>(GetFolderDocument.java:18)
            ... 3 more
    Caused by: java.lang.ClassNotFoundException: schemaorg_apache_xmlbeans.system.s9
    10A9A71E4C15BDE14230B4F92DDA8E5.TypeSystemHolder
            at java.net.URLClassLoader$1.run(Unknown Source)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.net.URLClassLoader.findClass(Unknown Source)
            at java.lang.ClassLoader.loadClass(Unknown Source)
            at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
            at java.lang.ClassLoader.loadClass(Unknown Source)
            at org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(XmlBeans.java:7
    69)
            ... 4 more

    Tuesday, April 22, 2008 9:06 AM
  • commons-logging-1.1.jar and log4-1.2.14.jar are provided with Axis 2 1.3 in the lib directory  (???)

     

    Wednesday, April 23, 2008 7:26 AM
  • Did you search on google for this ??

    http://ws.apache.org/axis2/tools/1_0/CodegenToolReference.html

     

     

     

    Wednesday, April 23, 2008 7:37 AM

  • thanks Herve,
    I finally can find the way already.
    Wednesday, April 23, 2008 11:13 AM
  • Hi hervé,

     

    Small clarifcation, below the code for set to address in new email. Please confirm me the code is right ?

    because the mail send successful but in the to address showing empty

     

     

    Code Snippet

    message.setToRecipients(ArrayOfRecipientsType.Factory.newInstance());

    EmailAddressType[] emailAddressType1 = new EmailAddressType[1];

    emailAddressType1[0] = EmailAddressType.Factory.newInstance();

    emailAddressType1[0].setEmailAddress(msExchangeEmailProperty.getTo()[0].toString());

    message.getToRecipients().setMailboxArray(emailAddressType1);

     

     

     

    Wednesday, April 23, 2008 11:14 AM
  • Hi,
    You can use EWSJ and do this with 4 lines of code:

    Code Snippet

    ExchangeConnectorFactory factory = new ExchangeConnectorFactory();
    EWSConnectorInterface connector = null;
    connector = factory.createEWSConnector(_exchangeHost,
                                                   _applicationUserAccountName,
                                                   _applicationUserPassword,
                                                   _prefix, _useSSL, _mailboxName);
           
    ArrayList contacts = connector.getPublicContacts();


    Download from:
    www.javaexchangeconnector.com

    Eli
    Tuesday, July 1, 2008 3:31 PM
  • I'm curious. With the WSDL I have I cannot generate stubs which contain a ExchangeServiceBindingStub. Can someone please email me their Services.wsdl which allows for this to be generated?

    Thanks in advance!
    Adam
    Monday, August 18, 2008 12:37 PM
  •  Dear All,

    Check the  following post link for the details of EWS with java communication

    1. Installation of Exchange server ans prerequest

    2. Creating EWS Stub package using AXIS

    3. Sending Simple mail

    4. Sending main with attachment

    http://kalaimaan.wordpress.com/2009/01/29/exchange-server-using-soap-service/
    http://kalaimaan.wordpress.com/2009/02/09/send-email-using-exchange-web-service/

    Have a great day :)


    sri
    • Edited by Sridhaar Tuesday, February 10, 2009 8:00 AM Added one line
    Tuesday, February 10, 2009 7:55 AM
  • Hey Herve,
    I also have generated my stub code using axis2 and xmlbeans.  I am new to Exchange and I am having trouble retrieving Calendar Events.  Unfortunately cannot find any good documentation of how to use the generated stub code within my client. 

    Your getInboxId() code worked briliantly and I was hoping you had some sample of how to perform calendar functions like get/add/remove/modify.

    Thanks in advance for your time.

     

    Thursday, February 19, 2009 4:16 PM
  • Is there any reason why we should not be using AXIS2 1.4?
    Thursday, March 12, 2009 2:35 AM
  • Hello all,

    This thread has proven to be extremely useful!  I have managed to generate the source code, the jar, the MySSL classes, but I am getting this error:

    org.apache.axis2.AxisFault: Transport error: 401 Error: Unauthorized

    at org.apache.axis2.transport.http.HTTPSender.handleResponse(HTTPSender.java:298)

    at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:192)

    at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:77)

    at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:327)

    at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:206)

    at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:396)[INFO] Unable to sendViaPost to url[https://company/EWS/exchange.asmx]

    org.apache.axis2.AxisFault: Transport error: 401 Error: Unauthorized

    at org.apache.axis2.transport.http.HTTPSender.handleResponse(HTTPSender.java:298)

    at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:192)

    at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:77)

    at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:327)

    at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:206)

    at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:396)

    at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:374)

    at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:211)

    at org.apache.axis2.client.OperationClient.execute(OperationClient.java:163)

    at com.microsoft.schemas.exchange.services._2006.messages.ExchangeServiceStub.GetFolder(ExchangeServiceStub.java:1107)

    at com.synetek.ews.test.GetInboxFodler.getInboxId(GetInboxFodler.java:50)

    at com.synetek.ews.test.GetInboxFodler.main(GetInboxFodler.java:110)

    at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:374)

    at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:211)

    at org.apache.axis2.client.OperationClient.execute(OperationClient.java:163)

    at com.microsoft.schemas.exchange.services._2006.messages.ExchangeServiceStub.GetFolder(ExchangeServiceStub.java:1107)

    at com.company.ews.test.GetInboxFodler.getInboxId(GetInboxFodler.java:50)

    at com.company.ews.test.GetInboxFodler.main(GetInboxFodler.java:110)

    Any ideas?


     

    Thursday, March 12, 2009 3:30 AM
  • Also, when I generated the code, instead of having

    com.microsoft.schemas.exchange.services._2006.messages.ExchangeWebServiceStub;

    I have

    com.microsoft.schemas.exchange.services._2006.messages.ExchangeServiceStub;

    I am on SBS2008 SP1.

    Anyone else experience this?

    Could it be my service addition in the WSDL?

      <wsdl:service name="ExchangeService">
      <wsdl:port name="ExchangeServicePort" binding="tns:ExchangeServiceBinding">
       <soap:address location="https://company/ews>
      </wsdl:port>
     </wsdl:service>

    Thursday, March 12, 2009 4:07 AM
  • Also, when I generated the code, instead of having
    com.microsoft.schemas.exchange.services._2006.messages.ExchangeWebServiceStub;

    I have

    com.microsoft.schemas.exchange.services._2006.messages.ExchangeServiceStub;

    I am on SBS2008 SP1.

    Anyone else experience this?

    Could it be my service addition in the WSDL?

      <wsdl:service name="ExchangeService">
      <wsdl:port name="ExchangeServicePort" binding="tns:ExchangeServiceBinding">
       <soap:address location="https://company/ews>
      </wsdl:port>
     </wsdl:service>

    Yes, you are right, this is not a problem.

    I have the same "org.apache.axis2.AxisFault: Transport error: 401 Error: Unauthorized" as u. I followed the steps above  generated java code and MySSLSocketFactory class, MyTrustManager class, testing calss, and sure:
    public boolean equals(Object obj) {
        return ((obj != null) && obj.getClass().equals(MySSLSocketFactory.class));
    }

    Wednesday, August 5, 2009 11:55 AM
  • Hi Andrew/ boxnoodle,

    Did you try with Basic authentication?

    -Vivek

    Thursday, October 15, 2009 1:27 PM
  • Hi Team,

              Intially posted the problem  in a wrong thread. I followed this thread and  did all the changes specified in that except removing

    ExchangeImpersonationType and SerializedSecurityContextType.

    when i try to access my Exchange Web Service , i get the following error. Any idea how to resolve this issue.

    I get the following error
    g4j:WARN Please initialize the log4j system properly.
    org.apache.axis2.AxisFault: First Element must contain the local name, Envelope , but found html
    at org.apache.axis2.AxisFault.makeFault(
    AxisFault.java:430)
    at org.apache.axis2.transport.TransportUtils.createSOAPMessage(
    TransportUtils.java:118)
    at org.apache.axis2.transport.TransportUtils.createSOAPMessage(
    TransportUtils.java:67)
    at org.apache.axis2.description.OutInAxisOperationClient.handleResponse(
    OutInAxisOperation.java:354)
    at org.apache.axis2.description.OutInAxisOperationClient.send(
    OutInAxisOperation.java:417)
    at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(
    OutInAxisOperation.java:229)
    at org.apache.axis2.client.OperationClient.execute(
    OperationClient.java:165)
    at com.microsoft.schemas.exchange.services._2006.messages.ExchangeServicesStub.getFolder(
    ExchangeServicesStub.java:3004)
    at com.test.ClientEWS.getInboxId(
    ClientEWS.java:131)
    at com.test.ClientEWS.main(
    ClientEWS.java:93)
    Caused by:
    org.apache.axiom.soap.SOAPProcessingException: First Element must contain the local name, Envelope , but found html
    at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.constructNode(
    StAXSOAPModelBuilder.java:267)
    at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.createOMElement(
    StAXSOAPModelBuilder.java:214)
    at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.createNextOMElement(
    StAXSOAPModelBuilder.java:196)
    at org.apache.axiom.om.impl.builder.StAXOMBuilder.next(
    StAXOMBuilder.java:207)
    at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.getSOAPEnvelope(
    StAXSOAPModelBuilder.java:161)
    at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.<init>(
    StAXSOAPModelBuilder.java:110)
    at org.apache.axis2.builder.BuilderUtil.getSOAPBuilder(
    BuilderUtil.java:682)
    at org.apache.axis2.transport.TransportUtils.createDocumentElement(
    TransportUtils.java:210)
    at org.apache.axis2.transport.TransportUtils.createSOAPMessage(
    TransportUtils.java:140)
    at org.apache.axis2.transport.TransportUtils.createSOAPMessage(
    TransportUtils.java:103)
    ... 8 mor
    Can any one guide as what should i do now ....


    Thanks
    Siva

     

     

    Wednesday, November 4, 2009 8:57 AM
  • I found in one Axis forum that the target URL may not be proper.I resolved to proper host. Now i get this error log4j:WARN No appenders could be found for logger (org.apache.axis2.description.AxisService). log4j:WARN Please initialize the log4j system properly. org.apache.axis2.AxisFault: Transport error: 401 Error: Unauthorized at org.apache.axis2.transport.http.HTTPSender.handleResponse(HTTPSender.java:295) at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:190) at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:75) at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:389) at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:222) at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:435) i understand from the forum that i should ask my admin to provide previlages Add-MailboxPermission "mailbox1" -User mySuperUser -AccessRights FullAccess Add-MailboxPermission "mailbox1" -User mySuperUser -ExtendedRights "Send As" I will get the rights and update this forum. mean while if you have any suggestion please do help me. One more thing i want is i am not able to see the request/respose data.Fiddler does not seem to capture when i am working with eclipse. thanks Siva
    Wednesday, November 4, 2009 9:49 AM
  • Hi,
    when i add 
     <wsdl:service name="ExchangeWebService">
        <wsdl:port name="ExchangeWebPort" binding="tns:ExchangeServiceBinding">
          <soap:address location="https://myserver/EWS/exchange.asmx" />
        </wsdl:port>
      </wsdl:service>
    to my services.wsdl on my hd, i get this error:

    Retrieving document at 'Services.wsdl'.
    Retrieving schema at 'messages.xsd', relative to 'file:/C:/Documents and Settings/*****/Desktop/*****/axis2-1.5.1/bin/Services.wsdl'.
    Retrieving schema at 'types.xsd', relative to 'file:/C:/Documents and Settings/setupuseracct/Desktop/Scambio/axis2-1.5.1/bin/messages.xsd'.
    [ERROR] java.net.URISyntaxException: Illegal character in path at index 18: file:/C:/Documents and Settings/*****/Desktop/****/axis2-1.5.1/bin/Services.wsdl
    java.lang.RuntimeException:
    java.net.URISyntaxException: Illegal character in path at index 18: file:/C:/Documents and Settings/****/Desktop/****/axis2-1.5.1/bin/Services.wsdl
    at org.apache.ws.commons.schema.resolver.DefaultURIResolver.resolveEntity(DefaultURIResolver.java:63)
    at org.apache.ws.commons.schema.SchemaBuilder.resolveXmlSchema(SchemaBuilder.java:1869)
    at org.apache.ws.commons.schema.SchemaBuilder.resolveXmlSchema(SchemaBuilder.java:1927)
    at org.apache.ws.commons.schema.SchemaBuilder.handleImport(SchemaBuilder.java:1616)
    at org.apache.ws.commons.schema.SchemaBuilder.handleXmlSchemaElement(SchemaBuilder.java:224)
    at org.apache.ws.commons.schema.XmlSchemaCollection.read(XmlSchemaCollection.java:433)
    at org.apache.axis2.description.WSDLToAxisServiceBuilder.getXMLSchema(WSDLToAxisServiceBuilder.java:144)
    at org.apache.axis2.description.WSDL11ToAxisServiceBuilder.copyExtensibleElements(WSDL11ToAxisServiceBuilder.java:2319)
    at org.apache.axis2.description.WSDL11ToAxisServiceBuilder.processTypes(WSDL11ToAxisServiceBuilder.java:413)
    at org.apache.axis2.description.WSDL11ToAxisServiceBuilder.processTypes(WSDL11ToAxisServiceBuilder.java:402)
    at org.apache.axis2.description.WSDL11ToAxisServiceBuilder.populateService(WSDL11ToAxisServiceBuilder.java:346)
    at org.apache.axis2.description.WSDL11ToAllAxisServicesBuilder.populateAllServices(WSDL11ToAllAxisServicesBuilder.java:107)
    at org.apache.axis2.wsdl.codegen.CodeGenerationEngine.<init>(CodeGenerationEngine.java:147)
    at org.apache.axis2.wsdl.WSDL2Code.main(WSDL2Code.java:35)
    at org.apache.axis2.wsdl.WSDL2Java.main(WSDL2Java.java:24)
    Caused by: java.net.URISyntaxException: Illegal character in path at index 18: file:/C:/Documents and Settings/*****/Desktop/****/axis2-1.5.1/bin/Services.wsdl
    at java.net.URI$Parser.fail(URI.java:2816)
    at java.net.URI$Parser.checkChars(URI.java:2989)
    at java.net.URI$Parser.parseHierarchical(URI.java:3073)
    at java.net.URI$Parser.parse(URI.java:3021)
    at java.net.URI.<init>(URI.java:578)
    at org.apache.ws.commons.schema.resolver.DefaultURIResolver.resolveEntity(DefaultURIResolver.java:57)
    ... 14 more

    How could i do?
    Thanks.
    Monday, December 21, 2009 4:56 PM
  • I notice there isn't any recent replies.  Is this still the best solution to create java code for a client to perform some Exchange operations?  I just need to get the calendar events for a given user. 

     

    thanks.

    Monday, April 19, 2010 3:24 PM
  • Dear Herve,

     

    I have read your topic and it was very usefull to me, as I lost hope to integrate with Exchange Server using Axis.

    but kindly I'm using Axis 1.4, and I can't authenticate with The Exchange Server as it uses secured protocols "HTTPS", can you help me please?

     

    Many Thanks,

    Ashraf

    Monday, April 26, 2010 10:18 AM
  • Hi Herve...why do you use jdk 1.5 and not jdk 1.4?
    Tuesday, November 2, 2010 11:57 AM