Kalaimaan

Doing simple things to make great life

Archive for the ‘Exchange Server’ Category

using soap service accessing Exchange server 2007

Calendar properties for Excange server (EWS) java

Posted by kalaimaan on February 11, 2009

The calendar have the follwoing properties to create the appointment (Type of Appointment)

1. Simple Appointment (Required fields)

  • Subject
  • Body of the text
  • Start Date
  • End Date
  • priority (Option)
  • set the Reminder
2. Appointment with Meeting  (Required fields)

  • Subject
  • Body of the text
  • Start Date
  • End Date
  • priority (Option)
  • Optional Attendee
  • Required Attendee
  • set the Reminder
Recurrency Appointment : Reflecting the appointment by the given condition in the format of( daily, monthly , Yearly, Weekly) and the required input fields are given below
3. Appointment with Recurrency (Daily).

  • Subject
  • Body of the text
  • Start Date
  • End Date
  • priority (Option)
  • Set Recurrence type (Daily)
  • Set Intervals ( it is make the interval for the each interval)
  • set Recurrency start date ( it the mention the date for the recurrency start)
  • Set the Number Of occurrence ( set the number of repetition of appointment in the consecutive intervals)
4. Appointment with Recurrency (Weekly).

  • Subject
  • Body of the text
  • Start Date
  • End Date
  • priority (Option)
  • Set the Recurrence type (Weekly)
  • Set the Intervals ( it is make the interval for the each interval)
  • set the day of week list (like monday, wednesday)
  • set the Recurrency start date ( it the mention the date for the recurrency start)
  • Set the Number of occurrence ( set the number of repetition of appointment in the consecutive intervals)
5. Appointment with Recurrency  (monthly).

  • Subject
  • Body of the text
  • Start Date
  • End Date
  • priority (Option)
  • Set the Recurrence type (monthly)
  • Set the Intervals ( it is make the interval for the each interval)
  • set the day of month
  • set the Recurrency start date ( it the mention the date for the recurrency start)
  • Set the Number of occurrence ( set the number of repetition of appointment in the consecutive intervals)
6. Appointment with Recurrency  (yearly).

  • Subject
  • Body of the text
  • Start Date
  • End Date
  • priority (Option)
  • Set the Recurrence type (monthly)
  • set month
  • set the day of month
  • set the Recurrency start date ( it the mention the date for the recurrency start)
  • Set the Number of occurrence ( set the number of repetition of appointment in the consecutive intervals)
Recurrency Appointment with meeting:

7. Appointment with Recurrency and meeting (Daily).

  • Subject
  • Body of the text
  • Start Date
  • End Date
  • priority (Option)
  • Optional Attendee
  • Required Attendee
  • Set Recurrence type (Daily)
  • Set Intervals ( it is make the interval for the each interval)
  • set Recurrency start date ( it the mention the date for the recurrency start)
  • Set the Number Of occurrence ( set the number of repetition of appointment in the consecutive intervals)
8. Appointment with Recurrency and meeting (Weekly).

  • Subject
  • Body of the text
  • Start Date
  • End Date
  • priority (Option)
  • Optional Attendee
  • Required Attendee
  • Set the Recurrence type (Weekly)
  • Set the Intervals ( it is make the interval for the each interval)
  • set the day of week list (like monday, wednesday)
  • set the Recurrency start date ( it the mention the date for the recurrency start)
  • Set the Number of occurrence ( set the number of repetition of appointment in the consecutive intervals)
9. Appointment with Recurrency and meeting  (monthly).

  • Subject
  • Body of the text
  • Start Date
  • End Date
  • priority (Option)
  • Optional Attendee
  • Required Attendee
  • Set the Recurrence type (monthly)
  • Set the Intervals ( it is make the interval for the each interval)
  • set the day of month
  • set the Recurrency start date ( it the mention the date for the recurrency start)
  • Set the Number of occurrence ( set the number of repetition of appointment in the consecutive intervals)
10. Appointment with Recurrency and meeting  (yearly).

  • Subject
  • Body of the text
  • Start Date
  • End Date
  • priority (Option)
  • Optional Attendee
  • Required Attendee
  • Set the Recurrence type (monthly)
  • set month
  • set the day of month
  • set the Recurrency start date ( it the mention the date for the recurrency start)
  • Set the Number of occurrence ( set the number of repetition of appointment in the consecutive intervals)

Posted in Exchange Server | Tagged: , , , , | Leave a Comment »

Create Calander Appointment, EWS, Exchanger server with java stub

Posted by kalaimaan on February 10, 2009

The below example is explain how to create Calander appointment in exchange server using Java stub


import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import net.adaptime.integration.EWSClient.Calendar.MsExchangeCalendarProperty;

import org.apache.axis2.AxisFault;
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.CreateItemDocument;
import com.microsoft.schemas.exchange.services._2006.messages.CreateItemResponseDocument;
import com.microsoft.schemas.exchange.services._2006.messages.CreateItemType;
import com.microsoft.schemas.exchange.services._2006.messages.ExchangeWebServiceStub;
import com.microsoft.schemas.exchange.services._2006.messages.ItemInfoResponseMessageType;
import com.microsoft.schemas.exchange.services._2006.types.BodyType;
import com.microsoft.schemas.exchange.services._2006.types.BodyTypeType;
import com.microsoft.schemas.exchange.services._2006.types.CalendarItemCreateOrDeleteOperationType;
import com.microsoft.schemas.exchange.services._2006.types.CalendarItemType;
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.ImportanceChoicesType;
import com.microsoft.schemas.exchange.services._2006.types.NonEmptyArrayOfAllItemsType;
import com.microsoft.schemas.exchange.services._2006.types.ResponseClassType;
import com.microsoft.schemas.exchange.services._2006.types.TargetFolderIdType;


public class EWSCreateCalender
{
ExchangeWebServiceStub exService;

private static String NTLM_AUT = “_NTLM_DIGEST_BASIC_AUTHENTICATION_”;

private static String NTLM_PRO = “NTLM”;

private static String HTTPS = “https”;

String exchangeURL = null;

String bodyText;
String subject;
Calendar scal;
Calendar ecal;
String loc;
int minRBS;

private String itemId = null;
private String changeKey = null;


public EWSCreateCalender(String userName, String passWord)
{

String exchangeURL = “https://Manager/EWS/Exchange.asmx”;
try
{
exService = new ExchangeWebServiceStub(null, exchangeURL);
}
catch (AxisFault e)
{
e.printStackTrace();
}

checkAuthenticate(userName, passWord);
}


/**
*
*
*/
private void checkAuthenticate(String userName, String passWord)
{
Protocol AlcHttpsProtocol = new Protocol(HTTPS, new EWSSSLSocketFactory(), 443);
Protocol.registerProtocol(HTTPS, AlcHttpsProtocol);

Options options = exService._getServiceClient().getOptions();
Authenticator authenticator = new Authenticator();

List<String> authScheme = new ArrayList<String>();
authScheme.add(NTLM_PRO);

authenticator.setAuthSchemes(authScheme);
authenticator.setUsername(userName);
authenticator.setPassword(passWord);
authenticator.setHost(“Manager”);

authenticator.setDomain(exchangeURL);

authenticator.setPort(Integer.parseInt(“443”));

options.setProperty(NTLM_AUT, authenticator);

options.setUserName(userName);

exService._getServiceClient().setOptions(options);
}


/**
*
*/
public void createCalendarAppointment(String bodyText,String subject,Calendar scal,    Calendar ecal,String loc,int minRBS)
{
this.bodyText = bodyText;
this.subject = subject;
this.scal = scal;
this.ecal = ecal;
this.loc = loc;
this.minRBS = minRBS;

// Create the appointment.
CalendarItemType appointment = CalendarItemType.Factory.newInstance();

// Create the CreateItem request.
CreateItemType createItemRequest = CreateItemType.Factory.newInstance();

appointment = prepareAppointment(appointment);

appointment.setItemClass(“IPM.Appointment”);

createItemRequest.setSendMeetingInvitations(CalendarItemCreateOrDeleteOperationType.SEND_TO_ALL_AND_SAVE_COPY);

// Identify the destination folder that will contain the appointment.
DistinguishedFolderIdType folder = DistinguishedFolderIdType.Factory.newInstance();
folder.setId(DistinguishedFolderIdNameType.CALENDAR);

// Create the array of items that will contain the appointment.
NonEmptyArrayOfAllItemsType arrayOfItems = NonEmptyArrayOfAllItemsType.Factory.newInstance();
CalendarItemType[] calender = new CalendarItemType[1];
calender[0] = CalendarItemType.Factory.newInstance();
arrayOfItems.setCalendarItemArray(calender);
arrayOfItems.setCalendarItemArray(0, appointment);

createItemRequest.setSavedItemFolderId(TargetFolderIdType.Factory.newInstance());
createItemRequest.getSavedItemFolderId().setDistinguishedFolderId(folder);
createItemRequest.setItems(arrayOfItems);

CreateItemDocument createItemDocument = CreateItemDocument.Factory.newInstance();
createItemDocument.setCreateItem(createItemRequest);

CreateItemResponseDocument createItemResponseDocument = null;

try
{
createItemResponseDocument = exService.CreateItem(createItemDocument, null, null, null, null);
}
catch (RemoteException e)
{
return;
}

ItemInfoResponseMessageType[] infoResponseMessageType = createItemResponseDocument.getCreateItemResponse()
.getResponseMessages().getCreateItemResponseMessageArray();

for (int i = 0; i < infoResponseMessageType.length; i++)
{
if (infoResponseMessageType[i].getResponseClass() == ResponseClassType.SUCCESS)
{
System.out.println(“Success”);
itemId =  infoResponseMessageType[i].getItems().getCalendarItemArray()[0].getItemId().getId();
changeKey = infoResponseMessageType[i].getItems().getCalendarItemArray()[0].getItemId().getChangeKey();
System.out.println(“ItemId : ” + itemId);
System.out.println(“Change Id : ” + changeKey);
}
else if (infoResponseMessageType[i].getResponseClass() == ResponseClassType.ERROR)
System.out.println(“Error”);
}
}


/**
*
* @param appointment
* @param property
* @param type
* @return
*/
private CalendarItemType prepareAppointment(CalendarItemType appointment)
{
if (bodyText != null && bodyText.length() > 0)
{
appointment.setBody(BodyType.Factory.newInstance());
appointment.getBody().setBodyType(BodyTypeType.HTML);
appointment.getBody().setStringValue(bodyText);
}

appointment.setImportance(ImportanceChoicesType.NORMAL);

if (subject != null && subject.trim().length() > 0)
appointment.setSubject(subject);
else
return null;

if (scal != null)
appointment.setStart(scal);
else
return null;

if (ecal != null)
appointment.setEnd(ecal);
else
return null;

if (loc != null && loc.length() > 0)
appointment.setLocation(loc);

appointment.setReminderIsSet(true);

if (minRBS > MsExchangeCalendarProperty.remainder_Null)
{
appointment.setReminderIsSet(Boolean.TRUE);
appointment.setReminderMinutesBeforeStart(minRBS);
}

appointment.setImportance(ImportanceChoicesType.NORMAL);

return appointment;
}

public static void main(String[] args)
{
EWSCreateCalender calender = new EWSCreateCalender(“kalaimaan”, “test01.” );
Calendar cals = Calendar.getInstance();
Calendar cale = Calendar.getInstance();
cals.set(2009, 02, 11, 10,30);
cale.set(2009, 02, 11, 12,00);
calender.createCalendarAppointment(“sample boby test”, “Tomorrow morning we have scheduled for seminer, come without fail”, cals, cale, “Chennai”, 30);
}
}

Posted in Exchange Server | Tagged: , , , | 12 Comments »

Retrive Email item from the folder, Exchange server web service java

Posted by kalaimaan on February 10, 2009

The below method is use to retrive the email message from the specific folder (like inbox, sentitem, …)

Retrive Email item from Exchange server

/**
*
*/
public String retriveEmailItems(String folderType)
{
String status = “Error”;

// Form the FindItem request.
FindItemType findItemRequest = FindItemType.Factory.newInstance();

// Define which item properties are returned in the response.
ItemResponseShapeType itemProperties = ItemResponseShapeType.Factory.newInstance();
itemProperties.setBaseShape(DefaultShapeNamesType.ID_ONLY);

findItemRequest.setItemShape(itemProperties);

DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];
folderIDArray[0] = DistinguishedFolderIdType.Factory.newInstance();
DistinguishedFolderIdType folderIdType = com.microsoft.schemas.exchange.services._2006.types.DistinguishedFolderIdType.Factory
.newInstance();

if (folderType.equalsIgnoreCase(“Inbox”))
folderIdType.setId(DistinguishedFolderIdNameType.INBOX);
else if (folderType.equalsIgnoreCase(“SentItems”))
folderIdType.setId(DistinguishedFolderIdNameType.SENTITEMS);
else if (folderType.equalsIgnoreCase(“DeleteItems”))
folderIdType.setId(DistinguishedFolderIdNameType.DELETEDITEMS);
else if (folderType.equalsIgnoreCase(“Drafts”))
folderIdType.setId(DistinguishedFolderIdNameType.DRAFTS);

folderIDArray[0] = folderIdType;
folderIDArray[0].setMailbox(EmailAddressType.Factory.newInstance());

NonEmptyArrayOfBaseFolderIdsType arrayOfBaseFolderIdsType = NonEmptyArrayOfBaseFolderIdsType.Factory
.newInstance();
arrayOfBaseFolderIdsType.setDistinguishedFolderIdArray(folderIDArray);
findItemRequest.setParentFolderIds(arrayOfBaseFolderIdsType);

// Define the traversal type.
findItemRequest.setTraversal(ItemQueryTraversalType.SHALLOW);

FindItemDocument findItemDocument = FindItemDocument.Factory.newInstance();
findItemDocument.setFindItem(findItemRequest);

FindItemResponseDocument findItemResponseDocument = null;
try
{
findItemResponseDocument = exService.FindItem(findItemDocument, null, null, null, null);
}
catch (Exception e)
{
return status;
}

FindItemResponseType findItemResponse = findItemResponseDocument.getFindItemResponse();

// Access the response message.
ArrayOfResponseMessagesType responseMessages = findItemResponse.getResponseMessages();
ResponseMessageType[] rmta = responseMessages.getFindItemResponseMessageArray();

for (ResponseMessageType rmt : rmta)
{
// One FindItemResponseMessageType per folder searched.
FindItemResponseMessageType firmt = (FindItemResponseMessageType) rmt;

if (firmt.getResponseClass() == ResponseClassType.SUCCESS)
status = “Success”;
else if (firmt.getResponseClass() == ResponseClassType.ERROR)
status = “Error”;

if (firmt.getRootFolder() == null)
continue;

FindItemParentType fipt = firmt.getRootFolder();
Object obj = fipt.getItems();

// FindItem contains an array of items.
if (obj instanceof ArrayOfRealItemsType)
{
ArrayOfRealItemsType items = ((ArrayOfRealItemsType) obj);

if (items.getItemArray() != null)
{
for (MessageType it : items.getMessageArray())
{
MessageType messageType = (MessageType) it;

MsExchangeEmailResponse response = null;

MessageType mess = getEmailByItem(messageType.getItemId().getId(), messageType.getItemId()
.getChangeKey());
System.out.println(“Message :\n” + mess);
}
}
}
}

return status;
}

/**
*
* @param id
* @param changeKey
* @return
*/
private MessageType getEmailByItem(String id, String changeKey)
{
MessageType temp =  null;
// Form the GetItem request.
GetItemType getItemRequest = GetItemType.Factory.newInstance();

getItemRequest.setItemShape(ItemResponseShapeType.Factory.newInstance());

getItemRequest.getItemShape().setBaseShape(DefaultShapeNamesType.ALL_PROPERTIES);

ItemIdType[] itemIdType = new ItemIdType[1];
itemIdType[0] = ItemIdType.Factory.newInstance();
itemIdType[0].setId(id);
itemIdType[0].setChangeKey(changeKey);
NonEmptyArrayOfBaseItemIdsType[] arrayOfBaseItemIdsType = new NonEmptyArrayOfBaseItemIdsType[1];
arrayOfBaseItemIdsType[0] = NonEmptyArrayOfBaseItemIdsType.Factory.newInstance();

arrayOfBaseItemIdsType[0].setItemIdArray(itemIdType);

getItemRequest.setItemIds(arrayOfBaseItemIdsType[0]);

// Here is the call to exchange.
GetItemDocument getItemDocument = GetItemDocument.Factory.newInstance();
getItemDocument.setGetItem(getItemRequest);
GetItemResponseDocument getItemResponseDocument = null;

try
{
getItemResponseDocument = exService.GetItem(getItemDocument, null, null, null, null);
}
catch (RemoteException e)
{
return null;
}

GetItemResponseType getItemResponse = getItemResponseDocument.getGetItemResponse();

ItemInfoResponseMessageType getItemResponseMessage = (ItemInfoResponseMessageType) getItemResponse
.getResponseMessages().getGetItemResponseMessageArray(0);

if (getItemResponseMessage != null)
{
if (getItemResponseMessage.getResponseClass() == ResponseClassType.SUCCESS)
{
temp = (MessageType) getItemResponseMessage.getItems().getMessageArray(0);

}
}

return temp;
}

Posted in Exchange Server | Tagged: , , , , | Leave a Comment »

Delete Email item in Exchange Server EWS

Posted by kalaimaan on February 10, 2009

Delete Email Item In Exchange Server using Java Stub interface

The below code is use to delete the particular item of email

/**
*
* @param id
* @param key
* @return
*/
private String deleteMessageItem(String id, String key)
{
String status = “Error”;

DeleteItemType deleteItemType = DeleteItemType.Factory.newInstance();

NonEmptyArrayOfBaseItemIdsType arrayOfBaseItemIdsType = NonEmptyArrayOfBaseItemIdsType.Factory.newInstance();
ItemIdType[] itemIdType = new ItemIdType[1];
itemIdType[0] = ItemIdType.Factory.newInstance();
itemIdType[0].setId(id);
itemIdType[0].setChangeKey(key);
arrayOfBaseItemIdsType.setItemIdArray(itemIdType);
deleteItemType.setItemIds(arrayOfBaseItemIdsType);
deleteItemType.setDeleteType(DisposalType.HARD_DELETE);

DeleteItemDocument deleteItemDocument = DeleteItemDocument.Factory.newInstance();
deleteItemDocument.setDeleteItem(deleteItemType);

DeleteItemResponseDocument deleteItemResponseDocument = null;
try
{
deleteItemResponseDocument = exService.DeleteItem(deleteItemDocument, null, null, null, null);
}
catch (RemoteException e)
{
return status;
}

DeleteItemResponseType deleteItemResponseType = deleteItemResponseDocument.getDeleteItemResponse();

ResponseMessageType[] responseMessageType = deleteItemResponseType.getResponseMessages()
.getDeleteItemResponseMessageArray();

for (int i = 0; i < responseMessageType.length; i++)
{
if (responseMessageType[i].getResponseClass() == ResponseClassType.SUCCESS)
status= “Success”;
else if (responseMessageType[i].getResponseClass() == ResponseClassType.ERROR)
status= “Error”;
}

return status;
}

Posted in Exchange Server | Tagged: , , , , , | 1 Comment »

Send mail with Attachment using Exchange web service java

Posted by kalaimaan on February 9, 2009

Send mail with attachmen, here i am submiting the part of the code.  Collected the previous post and merge the attachment code given below

/**
*
* @return
*/
public void sendEmailItem(String[] to, String[] cc, String bcc[], String sub, String bodyText, List<String> attach)
{
String status = null;
this.to=  to;
this.cc = cc;
this.bcc = bcc;
this.sub = sub;
this.bodyText = bodyText;

MessageType message = getMessageType();

sendMessageToDraft(message);

List<String> ls = attach;
String list[] = null;
if (ls != null && ls.size() > 0)
list = attachFilesIntoDraftMessage(itemId, changeKey, ls);

itemId = list[0];
changeKey = list[1];
status = sendDraftMessage(itemId, changeKey);

System.out.println(“Status : ” + status);
}

/**
*
* @param id
* @param key
* @return
*/
private String[] attachFilesIntoDraftMessage(String id, String key, List<String> attachToDraft)
{
String[] st = new String[2];

NonEmptyArrayOfAttachmentsType arrayOfAttachmentsType = null;
try
{
arrayOfAttachmentsType = getEmailAttachmentContent(attachToDraft);
}
catch (Exception e1)
{
st[0] = id;
st[1] = key;
return st;
}

// Create the CreateAttachment request.
CreateAttachmentType reqCreateAttach = CreateAttachmentType.Factory.newInstance();

// Identify the item that will have the attachments.
ItemIdType item = ItemIdType.Factory.newInstance();

item.setId(id);
item.setChangeKey(key);

// Add the parent item to the request.
reqCreateAttach.setParentItemId(item);
reqCreateAttach.setAttachments(arrayOfAttachmentsType);

CreateAttachmentDocument document = CreateAttachmentDocument.Factory.newInstance();
document.setCreateAttachment(reqCreateAttach);

CreateAttachmentResponseDocument responseDocument = null;
try
{
responseDocument = exService.CreateAttachment(document, null, null, null, null);
}
catch (Exception e)
{
return st;
}

ArrayOfResponseMessagesType arrayOfResponseMessagesType = responseDocument.getCreateAttachmentResponse()
.getResponseMessages();

AttachmentInfoResponseMessageType[] attachmentInfoResponseMessageTypes = arrayOfResponseMessagesType
.getCreateAttachmentResponseMessageArray();

for (AttachmentInfoResponseMessageType type : attachmentInfoResponseMessageTypes)
{
if (type.getResponseClass() == ResponseClassType.SUCCESS)
{
st[0] = type.getAttachments().getFileAttachmentArray()[0].getAttachmentId().getRootItemId();
st[1] = type.getAttachments().getFileAttachmentArray()[0].getAttachmentId().getRootItemChangeKey();
break;
}
else
{
st[0] = id;
st[1] = key;
}
}

return st;
}

/**
*
* @param ls
* @return
* @throws Exception
*/
private NonEmptyArrayOfAttachmentsType getEmailAttachmentContent(List<String> ls) throws Exception
{
// Add attachments to the request.
NonEmptyArrayOfAttachmentsType arrayOfAttachmentsType = NonEmptyArrayOfAttachmentsType.Factory.newInstance();

int total = 0;
FileAttachmentType[] attachmentTypes = new FileAttachmentType[ls.size()];
for (int count = 0; count < ls.size(); count++)
{
attachmentTypes[count] = FileAttachmentType.Factory.newInstance();
File f = new File(ls.get(count).toString());
attachmentTypes[count].setName(f.getName());

// Get the size of the file
attachmentTypes[count].setContent(getBytesFromFile(f));

total += f.length();
}
arrayOfAttachmentsType.setFileAttachmentArray(attachmentTypes);

return arrayOfAttachmentsType;
}

/**
* Returns the contents of the file in a byte array.
*
* @param file
* @return
* @throws IOException
*/
private byte[] getBytesFromFile(File file) throws IOException
{
InputStream is = new FileInputStream(file);

// Get the size of the file
long length = file.length();

// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.

if (length > Integer.MAX_VALUE)
{
// File is too large
}

// Create the byte array to hold the data
byte[] bytes = new byte[(int) length];

// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length – offset)) >= 0)
{
offset += numRead;
}

// Ensure all the bytes have been read in
if (offset < bytes.length)
{
throw new IOException(“Could not completely read file ” + file.getName());
}

// Close the input stream and return bytes
is.close();

return bytes;
}

Posted in Exchange Server | Tagged: , , , | Leave a Comment »

Send Email using Exchange web service

Posted by kalaimaan on February 9, 2009

Using exchange stub we can send mail to the selected user. In the previous post i have explained how to confiugre Ms Exchange server and creation of  SOAP stub for java.

Here is the sample to send mail to the use. The need two basic file for SSL

1. EWSSSLSocketFactory.java

2. EWSTrustManager.java

and the third one is the sample file for sending mail

3. EWSSendEmail.java

File : EWSSSLSocketFactory.java

/**
* @author Kalaimaan
*/

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.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 EWSSSLSocketFactory implements ProtocolSocketFactory
{

private SSLContext sslcontext = null;

private SSLContext createEasySSLContext()
{
try
{
X509TrustManager trustMgr = new EWSTrustManager();
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);
}

/**
* Attempts to get a new socket connection to the given host within the
* given time limit.
* <p>
* To circumvent the limitations of older JREs that do not support connect
* timeout a controller thread is executed. The controller thread attempts
* to create a new socket within the given limit of time. If socket
* constructor does not return until the timeout expires, the controller
* terminates and throws an {@link ConnectTimeoutException}
* </p>
*
* @param host
*            (String) The host name/IP.
* @param port
*            (int) The port number on the host.
* @param localAddress
*            (InetAddress) The local host name/IP to bind the socket to.
* @param localPort
*            (int) The port number on the local machine.
* @param params
*            (HttpConnectionParams) HTTP connection parameters.
*            <p>
* @throws IOException
*             if an I/O error occurs while creating the socket.
* @throws UnknownHostException
*             if the IP address of the host cannot be determined.
*             </p>
*             <p>
* @return Socket a new socket.
*         </p>
*/
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;
}
}

/**
* @see SecureProtocolSocketFactory#createSocket(java.lang.String,int)
*
*/
public Socket createSocket(String host, int port) throws IOException, UnknownHostException
{
return getSSLContext().getSocketFactory().createSocket(host, port);
}

/**
* @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)
*
*/
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(EWSSSLSocketFactory.class));
}

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

}

File : EWSTrustManager.java

/**
* @author kalaimaan
*/

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

public class EWSTrustManager implements X509TrustManager
{

public EWSTrustManager()
{
}

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

}

File : EWSSendEmail.java

import java.util.ArrayList;
import java.util.List;

import org.apache.axis2.AxisFault;
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.ArrayOfResponseMessagesType;
import com.microsoft.schemas.exchange.services._2006.messages.CreateItemDocument;
import com.microsoft.schemas.exchange.services._2006.messages.CreateItemResponseDocument;
import com.microsoft.schemas.exchange.services._2006.messages.CreateItemType;
import com.microsoft.schemas.exchange.services._2006.messages.ExchangeWebServiceStub;
import com.microsoft.schemas.exchange.services._2006.messages.ItemInfoResponseMessageType;
import com.microsoft.schemas.exchange.services._2006.messages.ResponseMessageType;
import com.microsoft.schemas.exchange.services._2006.messages.SendItemDocument;
import com.microsoft.schemas.exchange.services._2006.messages.SendItemResponseDocument;
import com.microsoft.schemas.exchange.services._2006.messages.SendItemType;
import com.microsoft.schemas.exchange.services._2006.types.ArrayOfRealItemsType;
import com.microsoft.schemas.exchange.services._2006.types.ArrayOfRecipientsType;
import com.microsoft.schemas.exchange.services._2006.types.BodyType;
import com.microsoft.schemas.exchange.services._2006.types.BodyTypeType;
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.ItemIdType;
import com.microsoft.schemas.exchange.services._2006.types.MessageDispositionType;
import com.microsoft.schemas.exchange.services._2006.types.MessageType;
import com.microsoft.schemas.exchange.services._2006.types.NonEmptyArrayOfAllItemsType;
import com.microsoft.schemas.exchange.services._2006.types.NonEmptyArrayOfBaseItemIdsType;
import com.microsoft.schemas.exchange.services._2006.types.ResponseClassType;
import com.microsoft.schemas.exchange.services._2006.types.TargetFolderIdType;

/**
*
* @author Kalaimaan
*
*/
public class EWSSendEmail
{

ExchangeWebServiceStub exService;

private static String NTLM_AUT = “_NTLM_DIGEST_BASIC_AUTHENTICATION_”;

private static String NTLM_PRO = “NTLM”;

private static String HTTPS = “https”;

String exchangeURL = null;

private String[] to;
private String[] cc;
private String bcc[];
private String sub;
private String bodyText;

private String itemId = null;
private String changeKey = null;

public EWSSendEmail(String userName, String passWord)
{

String exchangeURL = “https://Manager/EWS/Exchange.asmx&#8221;;
try
{
exService = new ExchangeWebServiceStub(null, exchangeURL);
}
catch (AxisFault e)
{
e.printStackTrace();
}

checkAuthenticate(userName, passWord);
}

/**
*
*
*/
private void checkAuthenticate(String userName, String passWord)
{
Protocol AlcHttpsProtocol = new Protocol(HTTPS, new EWSSSLSocketFactory(), 443);
Protocol.registerProtocol(HTTPS, AlcHttpsProtocol);

Options options = exService._getServiceClient().getOptions();
Authenticator authenticator = new Authenticator();

List<String> authScheme = new ArrayList<String>();
authScheme.add(NTLM_PRO);

authenticator.setAuthSchemes(authScheme);
authenticator.setUsername(userName);
authenticator.setPassword(passWord);
authenticator.setHost(“Manager”);

authenticator.setDomain(exchangeURL);

authenticator.setPort(Integer.parseInt(“443”));

options.setProperty(NTLM_AUT, authenticator);

options.setUserName(userName);

exService._getServiceClient().setOptions(options);
}

/**
*
* @return
*/
public void sendEmailItem(String[] to, String[] cc, String bcc[], String sub, String bodyText)
{
String status = null;
this.to=  to;
this.cc = cc;
this.bcc = bcc;
this.sub = sub;
this.bodyText = bodyText;

MessageType message = getMessageType();

sendMessageToDraft(message);

status = sendDraftMessage(itemId, changeKey);

System.out.println(“Status : ” + status);
}

/**
*
* @return
*/
private MessageType getMessageType()
{
// Create a single e-mail message.
MessageType message = MessageType.Factory.newInstance();

EmailAddressType[] emailAddressType = null;
int index = to.length;
if (index > 0)
{
emailAddressType = new EmailAddressType[index];
message.setToRecipients(ArrayOfRecipientsType.Factory.newInstance());
for (int count = 0; count < index; count++)
{
String address = to[count];
if (address != null && address.trim().length() > 0)
{
emailAddressType[count] = EmailAddressType.Factory.newInstance();
emailAddressType[count].setEmailAddress(address);
}
}
message.getToRecipients().setMailboxArray(emailAddressType);
}

index = cc.length;
if (index > 0)
{
emailAddressType = new EmailAddressType[index];
message.setCcRecipients(ArrayOfRecipientsType.Factory.newInstance());
for (int count = 0; count < index; count++)
{
String address = cc[count];
if (address != null && address.trim().length() > 0)
{
emailAddressType[count] = EmailAddressType.Factory.newInstance();
emailAddressType[count].setEmailAddress(address);
}
}
message.getCcRecipients().setMailboxArray(emailAddressType);
}

index = bcc.length;
if (index > 0)
{
emailAddressType = new EmailAddressType[index];
message.setBccRecipients(ArrayOfRecipientsType.Factory.newInstance());
for (int count = 0; count < index; count++)
{
String address = bcc[count];
if (address != null && address.trim().length() > 0)
{
emailAddressType[count] = EmailAddressType.Factory.newInstance();
emailAddressType[count].setEmailAddress(address);
}
}
message.getBccRecipients().setMailboxArray(emailAddressType);
}

if (sub != null && sub.trim().length() > 0)
message.setSubject(sub);

String body = bodyText == null ? null : bodyText;
if (body != null && body.trim().length() > 0)
{
BodyType bodyType = BodyType.Factory.newInstance();
message.setBody(bodyType);
message.getBody().setBodyType(BodyTypeType.HTML);
message.getBody().setStringValue(bodyText);
}
message.setItemClass(“IPM.Note”);

return message;
}

/**
*
* @param message
* @return
*/
private void sendMessageToDraft(MessageType message)
{
DistinguishedFolderIdType sentitems = DistinguishedFolderIdType.Factory.newInstance();
sentitems.setId(DistinguishedFolderIdNameType.DRAFTS);

// Create the array of items that will contain the appointment.
NonEmptyArrayOfAllItemsType arrayOfItems = NonEmptyArrayOfAllItemsType.Factory.newInstance();
MessageType[] messageType = new MessageType[1];
messageType[0] = MessageType.Factory.newInstance();
arrayOfItems.setMessageArray(messageType);
arrayOfItems.setMessageArray(0, message);

CreateItemType createEmailRequest = CreateItemType.Factory.newInstance();

// Specifiy how the created items are handled
createEmailRequest.setMessageDisposition(MessageDispositionType.SAVE_ONLY);
createEmailRequest.setSavedItemFolderId(TargetFolderIdType.Factory.newInstance());
createEmailRequest.getSavedItemFolderId().setDistinguishedFolderId(sentitems);

createEmailRequest.setItems(arrayOfItems);

// Send a CreateItem request and get the CreateItem response.
CreateItemDocument createItemDocument = CreateItemDocument.Factory.newInstance();
createItemDocument.setCreateItem(createEmailRequest);

CreateItemResponseDocument createItemResponseDocument = null;
try
{
createItemResponseDocument = exService.CreateItem(createItemDocument, null, null, null, null);
}
catch (Exception e)
{
e.printStackTrace();
return;
}

ArrayOfResponseMessagesType arrayOfResponseMessagesType = createItemResponseDocument.getCreateItemResponse()
.getResponseMessages();

ItemInfoResponseMessageType[] infoResponseMessageType = arrayOfResponseMessagesType
.getCreateItemResponseMessageArray();

for (ItemInfoResponseMessageType type : infoResponseMessageType)
{
if (type.getResponseClass() == ResponseClassType.SUCCESS)
{
ArrayOfRealItemsType arrayOfRealItemsType = type.getItems();

if (arrayOfRealItemsType != null && arrayOfRealItemsType.getItemArray() != null)
{
for (MessageType itemType : arrayOfRealItemsType.getMessageArray())
{
itemId = itemType.getItemId().getId();
changeKey = itemType.getItemId().getChangeKey();
}
}
}
}
}

/**
*
* @param id
* @param key
* @return
*/
private String sendDraftMessage(String id, String key)
{
String status = “Error”;

SendItemType sendItemType = SendItemType.Factory.newInstance();

DistinguishedFolderIdType sentitems = DistinguishedFolderIdType.Factory.newInstance();
sentitems.setId(DistinguishedFolderIdNameType.SENTITEMS);

sendItemType.setSaveItemToFolder(true);
sendItemType.setSavedItemFolderId(TargetFolderIdType.Factory.newInstance());
sendItemType.getSavedItemFolderId().setDistinguishedFolderId(sentitems);

ItemIdType[] idType = new ItemIdType[1];
idType[0] = ItemIdType.Factory.newInstance();
idType[0].setId(id);
idType[0].setChangeKey(key);
NonEmptyArrayOfBaseItemIdsType baseItemIdsType = NonEmptyArrayOfBaseItemIdsType.Factory.newInstance();
baseItemIdsType.setItemIdArray(idType);

sendItemType.setItemIds(baseItemIdsType);

SendItemDocument sendItemDocument = SendItemDocument.Factory.newInstance();
sendItemDocument.setSendItem(sendItemType);

SendItemResponseDocument responseDocument = null;
try
{
responseDocument = exService.SendItem(sendItemDocument, null, null, null, null);
}
catch (Exception e)
{
e.printStackTrace();
return status;
}

ArrayOfResponseMessagesType arrayOfResponseMessagesType = responseDocument.getSendItemResponse()
.getResponseMessages();

ResponseMessageType[] sendItemResponseTypes = arrayOfResponseMessagesType.getSendItemResponseMessageArray();

for (ResponseMessageType type : sendItemResponseTypes)
{
if (type.getResponseClass() == ResponseClassType.SUCCESS)
{
System.out.println(“Id :  >>>> : ”  +id);
System.out.println(“key : >>>> : ” + key);
status = “Success”;
}
}

return status;
}
}

Output:

<!– @page { size: 8.5in 11in; margin: 0.79in } P { margin-bottom: 0.08in } –>

Id :  >>>> :  AAATAHRlc3QwMUBkb21haW4ubG9jYWwARgAAAAAAuIdR3qV3p0SYwe+85PKTjQcA1v6YTIQck0aSvXE4cDp+8wABPuROMgAA1v6YTIQck0aSvXE4cDp+8wChwpJ2OAAA

key : >>>> : CQAAABYAAADW/phMhByTRpK9cThwOn7zAKHCkotI

Status : Success


Posted in Exchange Server | Tagged: , , , , | 7 Comments »

Exchange Server 2007 Web service, SOAP

Posted by kalaimaan on January 29, 2009

Hi,

I like the share my Exchanges web service knowledge. Check the steps to generate the webservice package, installation of Exchanges server and prerequisite details

Prerequisite installation

Installation Steps for Exchange Server 2007:

Step1: Install windows 2003 x64 Standard Edition with service pack 2.

Step2: Install IIS service using windows component.

Step3: Install Active directory with DNS configuration.

Step4: Install .Net Frame work 2.0 x64 with latest service pack.

Step5: Install Power Management shell x64

Step6: Install MMC Controller x64

Step7: Installing required windows patch

Step8: Setting required properties for install MS Exchange server 2007

Step9: Install Ms Exchange server 2007 standard Edition.

To install Active directory with Domain control.

  1. Click Start, click Run, type dcpromo, and then click OK.
  2. On the first page of the Active Directory Installation Wizard, click Next.
  3. On the next page of the Active Directory Installation Wizard, click Next.
  4. On the Domain Controller Type page, click Domain Controller for a new domain, and then click Next.
  5. On the Create New Domain page, click Domain in a new forest, and then click Next.
  6. On the New Domain Name page, in the Full DNS name for new domain box, type NewDomain.local, and then click Next.
  7. On the Database and Log Folders page, accept the defaults in the Database folder box and the Log folder box, and then click Next.
  8. On the Shared System Volume page, accept the default in the Folder location box, and then click Next.
  9. On the DNS Registration Diagnostics page, click Install and configure the DNS server on this computer and set this computer to use this DNS server as its preferred DNS Server, and then click Next.
  10. On the Permissions page, click Permissions compatible only with Windows 2000 or Windows Server 2003 operating systems, and then click Next.
  11. On the Directory Services Restore Mode Administrator Password page, enter a password in the Restore Mode Password box, retype the password to confirm it in the Confirm password box, and then click Next.
  12. On the Summary page, confirm the information is correct, and then click Next.
  13. When prompted to restart the computer, click Restart now.
  14. After the computer restarts, log on to Administrator.

To install IIS on Windows Server 2003

  1. Click Start, point to Control Panel, and then click Add or Remove Programs.
  2. In Add or Remove Programs, click Add/Remove Windows Components.
  3. In the Windows Components Wizard, under Components, select Application Server.

    Note:

    Selecting Application Server performs a default installation of Internet Information Services (IIS) and includes components that are not necessary for Certificate Services. In most cases, this installation is acceptable for an isolated test environment. However, if you plan to connect your test environment to your production network, consult your organization’s security policy to determine which components to install.
  4. Click Next.
  5. After the wizard completes the installation, click Finish

To Install Exchange server 2007 in windows 2003

Reference : Exchange Server 2007 Guide.odt

How to create Exchange server stub to access.

Step 1:

Download Axis2 1.3 version from Apache axis tomcat

Step 2:

Place the folder axis2-1.3 in c drive

Step 3:

We have to set the following path in Enviorenment variable and the below is the sample

Please set the correct path for the corresponding “Variable Name”

1. AXIS_HOME – C:\axis2-1.3

2. JAVA_HOME – C:\Program Files\Java\jdk1.5.0_05

3. TOMCAT_HOME – C:\Program Files\Apache Software Foundation\Tomcat 5.0

4. JWSDP_SHARED – C:\Program Files\Apache Software Foundation\Tomcat 5.0\jwsdp-shared;

5. ANT_HOME – D:\MsExchangeServer-WorkFolder\Axis – Java\apache-ant-1.7.0-bin\apache-ant-1.7.0

6. PATH – %AXIS2_HOME%\bin;%AXIS_HOME%\webapp; %ANT_HOME%\bin;%TOMCAT_HOME%\common\lib; %JWSDP_SHARED%\bin;%JWSDP_SHARED%\lib; %JWSDP_SHARED%\webapps\jwsdp-callback\WEB-INF\classes

Step 4:

In the folder axis2-1.3 we have a bin folder. Open the cmd window and enter into

the path “C:\axis2-1.3\bin.”

<wsdl:service name=”ExchangeService”>

<wsdl:port name=”ExchangeServicePort” binding=”tns:ExchangeServiceBinding”>

<soap:address location=”<ExchangeServer>”/>

</wsdl:port>

</wsdl:service>

Place the Excahange server Wsdl and XSd file under bin folder and run the below command using “cmd prompt”

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

you can generate the set of java package for Exchange web service. Generate the Stub using the package

Have a Good Day 🙂


Posted in Exchange Server | Tagged: , , , | 6 Comments »