DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets

  • submit to reddit

Recent Snippets

                    import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.regex.Pattern;


public class RegexHashMap<V> implements Map<String, V>
{
	private class PatternMatcher
	{
		private final String regex;
		private final Pattern compiled;
		
		PatternMatcher(String name)
		{
			regex = name;
			compiled = Pattern.compile(regex);
			
		}
				
		boolean matched(String string)
		{
			if(compiled.matcher(string).matches())
			{
				ref.put(string, regex);
				return true;
			}
			return false;
		}
	}
	/**
	 * Map of input to pattern
	 */
	private final Map<String, String> ref;
	
	/**
	 * Map of pattern to value
	 */
	private final Map<String, V> map;
	
	/**
	 * Compiled patterns
	 */
	private final List<PatternMatcher> matchers;
	
	@Override
	public String toString()
	{
		return "RegexHashMap [ref=" + ref + ", map=" + map + "]";
	}

	/**
	 * 
	 */
	public RegexHashMap()
	{
		ref = new WeakHashMap<>();
		map = new HashMap<>();
		matchers = new ArrayList<>();
	}
			
	/**
	 * Returns the value to which the specified key pattern is mapped, or null if this map contains no mapping 
 		for the key pattern
	 */
	@Override
	public V get(Object weakKey)
	{
		if(!ref.containsKey(weakKey))
		{
			for(PatternMatcher matcher : matchers)
			{
				if(matcher.matched((String) weakKey))
				{
					break;
				}
			}
			
		}
		if(ref.containsKey(weakKey))
		{
			return map.get(ref.get(weakKey));
			
		}
		return null;
	}
	
	/**
	 * Associates a specified regular expression to a particular value
	 */
	@Override
	public V put(String key, V value)
	{
		V v = map.put(key, value);
		if (v == null)
		{
			matchers.add(new PatternMatcher(key));
		}
		return v;
		
	}

	/**
	 * Removes the regular expression key
	 */
	@Override
	public V remove(Object key) 
	{
		V v = map.remove(key);
		if(v != null)
		{
			for(Iterator<PatternMatcher> iter = matchers.iterator(); iter.hasNext();)
			{
				PatternMatcher matcher = iter.next();
				if(matcher.regex.equals(key))
				{
					iter.remove();
					break;
				}
			}
			
			for(Iterator<Entry<String, String>> iter = ref.entrySet().iterator(); iter.hasNext();)
			{
				Entry<String, String> entry = iter.next();
				if(entry.getValue().equals(key))
				{
					iter.remove();
				}
			}
		}
		return v;
        
    }
	/**
	 * Set of view on the regular expression keys
	 */
	@Override
	public Set<java.util.Map.Entry<String, V>> entrySet()
	{
		return map.entrySet();
	}

	@Override
	public void putAll(Map<? extends String, ? extends V> m) 
	{
		for(Entry<? extends String, ? extends V> entry : m.entrySet())
		{
			put(entry.getKey(), entry.getValue());
		}
    }

	@Override
	public int size()
	{
		return map.size();
	}

	@Override
	public boolean isEmpty()
	{
		return map.isEmpty();
	}

	/**
	 * Returns true if this map contains a mapping for the specified regular expression key.
	 */
	@Override
	public boolean containsKey(Object key)
	{
		return map.containsKey(key);
	}
	
	/**
	 * Returns true if this map contains a mapping for the specified regular expression matched pattern.
	 * @param key
	 * @return
	 */
	public boolean containsKeyPattern(Object key)
	{
		return ref.containsKey(key);
	}

	@Override
	public boolean containsValue(Object value)
	{
		return map.containsValue(value);
	}

	@Override
	public void clear()
	{
		map.clear();
		matchers.clear();
		ref.clear();
	}
	
	/**
	 * Returns a Set view of the regular expression keys contained in this map.
	 */
	@Override
	public Set<String> keySet()
	{
		return map.keySet();
	}
	
	/**
	 * Returns a Set view of the regex matched patterns contained in this map. The set is backed by the map, so changes to 
 		the map are reflected in the set, and vice-versa.
	 * @return
	 */
	public Set<String> keySetPattern()
	{
		return ref.keySet();
	}

	@Override
	public Collection<V> values()
	{
		return map.values();
	}
	
	/**
	 * Produces a map of patterns to values, based on the regex put in this map
	 * @param patterns
	 * @return
	 */
	public Map<String, V> transform(List<String> patterns)
	{
		for(String pattern : patterns)
		{
			get(pattern);
		}
		
		Map<String, V> transformed = new HashMap<>();
		for(Entry<String, String> entry : ref.entrySet())
		{
			transformed.put(entry.getKey(), map.get(entry.getValue()));
		}
		return transformed;
		
	}
	public static void main(String...strings)
	{
		RegexHashMap<String> rh = new RegexHashMap<>();
		rh.put("[o|O][s|S][e|E].?[1|2]", "This is a regex match");
		rh.put("account", "This is a direct match");
		System.out.println(rh);
		System.out.println("get:ose-1 -> "+rh.get("ose-1"));
		System.out.println("get:OSE2 -> "+rh.get("OSE2"));
		System.out.println("get:OSE112 -> "+rh.get("OSE112"));
		System.out.println("get:ose-2 -> "+rh.get("ose-2"));
		System.out.println("get:account -> "+rh.get("account"));
		System.out.println(rh);
	}

}                
                    import java.net.URI;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import microsoft.exchange.webservices.data.Appointment;
import microsoft.exchange.webservices.data.AppointmentSchema;
import microsoft.exchange.webservices.data.CalendarFolder;
import microsoft.exchange.webservices.data.CalendarView;
import microsoft.exchange.webservices.data.EmailMessage;
import microsoft.exchange.webservices.data.ExchangeCredentials;
import microsoft.exchange.webservices.data.ExchangeService;
import microsoft.exchange.webservices.data.ExchangeVersion;
import microsoft.exchange.webservices.data.FindItemsResults;
import microsoft.exchange.webservices.data.Folder;
import microsoft.exchange.webservices.data.Item;
import microsoft.exchange.webservices.data.ItemId;
import microsoft.exchange.webservices.data.ItemView;
import microsoft.exchange.webservices.data.PropertySet;
import microsoft.exchange.webservices.data.ServiceLocalException;
import microsoft.exchange.webservices.data.WebCredentials;
import microsoft.exchange.webservices.data.WellKnownFolderName;

/**
 * @author Shantanu Sikdar 
 *
 */

public class MSExchangeEmailService {
			
	private static ExchangeService service;
	private static Integer NUMBER_EMAILS_FETCH =5; // only latest 5 emails/appointments are fetched.
			
	/**
	 * Firstly check, whether "https://webmail.xxxx.com/ews/Services.wsdl" and "https://webmail.xxxx.com/ews/Exchange.asmx"
	 * is accessible, if yes that means the Exchange Webservice is enabled on your MS Exchange.
	 */
	static{
		try{						
			service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
			//service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); //depending on the version of your Exchange. 
			service.setUrl(new URI("https://webmail.xxxx.com/ews/Exchange.asmx"));		
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Initialize the Exchange Credentials. 
	 * 	Don't forget to replace the "USRNAME","PWD","DOMAIN_NAME" variables. 
	 */
	public MSExchangeEmailService() {
		ExchangeCredentials credentials = new WebCredentials("USRNAME","PWD","DOMAIN_NAME");		
		service.setCredentials(credentials);
	}
	
	/**
	 * Reading one email at a time. Using Item ID of the email.
	 * Creating a message data map as a return value.   
	 */
	public Map<String, Object> readEmailItem(ItemId itemId){
		Map<String, Object> messageData = new HashMap<String, Object>();
		try{				
			Item itm = Item.bind(service, itemId, PropertySet.FirstClassProperties);
			EmailMessage emailMessage = EmailMessage.bind(service, itm.getId());			
			messageData.put("emailItemId", emailMessage.getId().toString());			
			messageData.put("subject", emailMessage.getSubject().toString());
			messageData.put("fromAddress",emailMessage.getFrom().getAddress().toString());
			messageData.put("senderName",emailMessage.getSender().getName().toString());
			Date dateTimeCreated = emailMessage.getDateTimeCreated();
			messageData.put("SendDate",dateTimeCreated.toString());			
			Date dateTimeRecieved = emailMessage.getDateTimeReceived();
			messageData.put("RecievedDate",dateTimeRecieved.toString());			
			messageData.put("Size",emailMessage.getSize()+"");						
			messageData.put("emailBody",emailMessage.getBody().toString());			
		}catch (Exception e) {
			e.printStackTrace();
		}
		return messageData;
	}
	
	/**
	 * Number of email we want to read is defined as NUMBER_EMAILS_FETCH, 
	 */
	public List<Map<String, Object>> readEmails(){
		List<Map<String, Object>> msgDataList = new ArrayList<Map<String, Object>>();
		try{
			Folder folder = Folder.bind( service, WellKnownFolderName.Inbox );
			FindItemsResults<Item> results = service.findItems(folder.getId(), new ItemView(NUMBER_EMAILS_FETCH));		
			int i =1;
			for (Item item : results){				
				Map<String, Object> messageData = new HashMap<String, Object>();
				messageData = readEmailItem(item.getId());
				System.out.println("\nEmails #" + (i++ ) + ":" );
				System.out.println("subject : " + messageData.get("subject").toString());
				System.out.println("Sender : " + messageData.get("senderName").toString());
				msgDataList.add(messageData);
			}			
		}catch (Exception e) { 	e.printStackTrace();		}
		return msgDataList;
	}

	/**
	 * Reading one appointment at a time. Using Appointment ID of the email.
	 * Creating a message data map as a return value.   
	 */
	public Map<String, Object> readAppointment(Appointment appointment){
		Map<String, Object> appointmentData = new HashMap<String, Object>();
		try {			
			appointmentData.put("appointmentItemId", appointment.getId().toString());
			appointmentData.put("appointmentSubject", appointment.getSubject());
			appointmentData.put("appointmentStartTime", appointment.getStart()+"");
			appointmentData.put("appointmentEndTime", appointment.getEnd()+"");
			//appointmentData.put("appointmentBody", appointment.getBody().toString());
		} catch (ServiceLocalException e) {
			e.printStackTrace();
		}		
		return appointmentData;
	}

	/**
 	 *	Number of Appointments we want to read is defined as NUMBER_EMAILS_FETCH,
 	 *  Here I also considered the start data and end date which is a 30 day span.
 	 *  We need to set the CalendarView property depending upon the need of ours.   
	 */
	public List<Map<String, Object>> readAppointments(){		
		List<Map<String, Object>> apntmtDataList = new ArrayList<Map<String, Object>>();		
		Calendar now = Calendar.getInstance();
		Date startDate = Calendar.getInstance().getTime();
		now.add(Calendar.DATE, 30);
        Date endDate = now.getTime();  
		try{
			CalendarFolder calendarFolder = CalendarFolder.bind(service, WellKnownFolderName.Calendar, new PropertySet());			
			CalendarView cView = new CalendarView(startDate, endDate, 5);			
			cView.setPropertySet(new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End));	// we can set other properties as well depending upon our need.		
			FindItemsResults<Appointment> appointments = calendarFolder.findAppointments(cView);			
			
			int i =1;
			List<Appointment> appList = appointments.getItems();			
			for (Appointment appointment : appList) {
				System.out.println("\nAPPOINTMENT #" + (i++ ) + ":" );
				Map<String, Object> appointmentData = new HashMap<String, Object>();
				appointmentData = readAppointment(appointment);
				System.out.println("subject : " + appointmentData.get("appointmentSubject").toString());
				System.out.println("On : " + appointmentData.get("appointmentStartTime").toString());
				apntmtDataList.add(appointmentData);
			}			
		}catch (Exception e) {
			e.printStackTrace();
		}
		return apntmtDataList;
	}	
	
	public static void main(String[] args) {		
		MSExchangeEmailService msees = new MSExchangeEmailService();
		msees.readEmails();
		msees.readAppointments();		
	}
}
                
                    public class ThreadProc implements Runnable {

	boolean isRunning = true;
	Workbook testWorkbook;
	Random r = new Random();

	public ThreadProc(Workbook workbook)
	{
		this.testWorkbook = workbook;
	}

	public int randomNext(int Low, int High)
	{
		int R = r.nextInt(High-Low) + Low;
		return R;
	}

	public void kill()
	{
		this.isRunning = false;
	}

    public void run(){

    	while(this.isRunning)
    	{
            int row = randomNext(0, 100);
            int col = randomNext(0, 10);

            String s = testWorkbook.getWorksheets().get(0).getCells().get(row, col).getStringValue();

            if (s.equals("R" + row + "C" + col)!=true)
            {
                System.out.println("This message box will show up when cells read values are incorrect.");
            }
    	}
    }
  }


//........MainActivity.java........
//.................................
import java.io.File;
import java.util.Random;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;

import com.aspose.cells.CellsHelper;
import com.aspose.cells.IWarningCallback;
import com.aspose.cells.WarningInfo;
import com.aspose.cells.WarningType;
import com.aspose.cells.Workbook;

public class MainActivity extends Activity {

@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
try{
    Workbook testWorkbook = new Workbook();
    testWorkbook.getWorksheets().clear();
    testWorkbook.getWorksheets().add("Sheet1");

    for (int row = 0; row < 100; row++)
        for (int col = 0; col < 10; col++)
            testWorkbook.getWorksheets().get(0).getCells().get(row, col).setValue("R" + row + "C" + col);

    //Commenting this line will show a pop-up message
    testWorkbook.getWorksheets().get(0).getCells().setMultiThreadReading(true);

    ThreadProc tp = new ThreadProc(testWorkbook);

    Thread myThread1 = new Thread(tp);
    myThread1.start();

    Thread myThread2 = new Thread(tp);
    myThread2.start();

    Thread.currentThread().sleep(5*1000);
    tp.kill();
}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

.........

}

                
                    private List<Integer> getNeighbours(int num,int xsize,int ysize){
	List<Integer> neighbours = new ArrayList<Integer>();
	int max=xsize*ysize;
	int quo=num%xsize;
			
	int rowEnd = num+quo==num?num:(num+(xsize-quo));//works fine with most of the cases.		
	int rowBegin = rowEnd-xsize+1;
	int prevRowEnd = rowEnd-xsize<=0?rowEnd:rowEnd-xsize;
	int prevRowBegin = prevRowEnd-xsize+1;
	int nextRowEnd = rowEnd+xsize<=max?rowEnd+xsize:max;
	int nextRowBegin = nextRowEnd-xsize+1;		
			
	if(num-xsize-1>=prevRowBegin && num-xsize-1<prevRowEnd)    //North_West
		neighbours.add(num-xsize-1);
	if(num-xsize>0)             //North
		neighbours.add(num-xsize);			
	if(num-xsize+1>prevRowBegin && num-xsize+1<=prevRowEnd)             //North_East
		neighbours.add(num-xsize+1);
	if(num-1>=rowBegin)            //West
		neighbours.add(num-1);
	if(num+1<=rowEnd)               //East	
		neighbours.add(num+1);
	if(num+xsize-1>=nextRowBegin && num+xsize-1<nextRowEnd)        //South_West
		neighbours.add(num+xsize-1);
	if(num+xsize<=max)            //South
		neighbours.add(num+xsize);
	if(num+xsize+1>nextRowBegin && num+xsize+1<=nextRowEnd)     //South_East
		neighbours.add(num+xsize+1);
				
	return neighbours;
}
                
                    //Office Automation

//To use Office Automation objects for Microsoft Outlook, you need to add references to Microsoft Office and Microsoft Office Interop for Outlook libraries to your project.

[C#]

// Add the namespaces
using Microsoft.Office;
using Microsoft.Office.Interop.Outlook;

// Create a new Application Class
Application app = new Application();
// Create a MailItem object
MailItem item = (MailItem)outlook.CreateItemFromTemplate(@"d:\temp\test.msg", Type.Missing);
// Access different fields of the message
System.Console.WriteLine(string.Format("Subject:{0}", item.Subject));
System.Console.WriteLine(string.Format("Sender Email Address:{0}", item.SenderEmailAddress));
System.Console.WriteLine(string.Format("SenderName:{0}", item.SenderName));
System.Console.WriteLine(string.Format("TO:{0}", item.To));
System.Console.WriteLine(string.Format("CC:{0}", item.CC));
System.Console.WriteLine(string.Format("BCC:{0}", item.BCC));
System.Console.WriteLine(string.Format("Html Body:{0}", item.HTMLBody));
System.Console.WriteLine(string.Format("Text Body:{0}", item.Body));
 
[VB.NET]

' Add the namespaces
Imports Microsoft.Office
Imports Microsoft.Office.Interop.Outlook

' Create a new Application Class
Private outlook As Application = New Application()
' Create a MailItem object
Private item As MailItem = CType(outlook.CreateItemFromTemplate("d:\temp\test.msg", Type.Missing), MailItem)
' Access different fields of the message
System.Console.WriteLine(String.Format("Subject:{0}", item.Subject))
System.Console.WriteLine(String.Format("Sender Email Address:{0}", item.SenderEmailAddress))
System.Console.WriteLine(String.Format("SenderName:{0}", item.SenderName))
System.Console.WriteLine(String.Format("TO:{0}", item.To))
System.Console.WriteLine(String.Format("CC:{0}", item.CC))
System.Console.WriteLine(String.Format("BCC:{0}", item.BCC))
System.Console.WriteLine(String.Format("Html Body:{0}", item.HTMLBody))
System.Console.WriteLine(String.Format("Text Body:{0}", item.Body))
 
//Aspose.Email for .NET

//The following code snippet does the same thing as the code above using Aspose.Email for .NET. To access the Aspose.Email.Outlook objects, you need to add a reference to Aspose.Email to your project.

[C#]

// Add the namespace for Aspose.Email.Outlook
using Aspose.Email.Outlook;

// Create a new object of type MapiMessage
MapiMessage msg = MapiMessage.FromFile(@"d:\temp\test.msg");
// Access the fields of the message
System.Console.WriteLine(string.Format("Subject:{0}", msg.Subject));
System.Console.WriteLine(string.Format("Sender Email Address:{0}", msg.SenderEmailAddress));
System.Console.WriteLine(string.Format("SenderName:{0}", msg.SenderName));
System.Console.WriteLine(string.Format("TO:{0}", msg.DisplayTo));
System.Console.WriteLine(string.Format("CC:{0}", msg.DisplayCc));
System.Console.WriteLine(string.Format("BCC:{0}", msg.DisplayBcc));
System.Console.WriteLine(string.Format("Text Body:{0}", msg.Body));
System.Console.WriteLine(string.Format("Rtf Body:{0}", msg.BodyRtf));

[VB.NET]

' Add the namespace for Aspose.Email.Outlook
Imports Aspose.Email.Outlook

' Create a new object of type MapiMessage
Private msg As MapiMessage = MapiMessage.FromFile("d:\temp\test.msg")
' Access the fields of the message
System.Console.WriteLine(String.Format("Subject:{0}", msg.Subject))
System.Console.WriteLine(String.Format("Sender Email Address:{0}", msg.SenderEmailAddress))
System.Console.WriteLine(String.Format("SenderName:{0}", msg.SenderName))
System.Console.WriteLine(String.Format("TO:{0}", msg.DisplayTo))
System.Console.WriteLine(String.Format("CC:{0}", msg.DisplayCc))
System.Console.WriteLine(String.Format("BCC:{0}", msg.DisplayBcc))
System.Console.WriteLine(String.Format("Text Body:{0}", msg.Body))
System.Console.WriteLine(String.Format("Rtf Body:{0}", msg.BodyRtf))

                
                    //Insert a Document at Any Location
/**
 * Inserts content of the external document after the specified node.
 * Section breaks and section formatting of the inserted document are ignored.
 *
 * @param insertAfterNode Node in the destination document after which the content
 * should be inserted. This node should be a block level node (paragraph or table).
 * @param srcDoc The document to insert.
 */
public static void insertDocument(Node insertAfterNode, Document srcDoc) throws Exception
{
    // Make sure that the node is either a paragraph or table.
    if ((insertAfterNode.getNodeType() != NodeType.PARAGRAPH) &
      (insertAfterNode.getNodeType() != NodeType.TABLE))
        throw new IllegalArgumentException("The destination node should be either a paragraph or table.");

    // We will be inserting into the parent of the destination paragraph.
    CompositeNode dstStory = insertAfterNode.getParentNode();

    // This object will be translating styles and lists during the import.
    NodeImporter importer = new NodeImporter(srcDoc, insertAfterNode.getDocument(), ImportFormatMode.KEEP_SOURCE_FORMATTING);

    // Loop through all sections in the source document.
    for (Section srcSection : srcDoc.getSections())
    {
        // Loop through all block level nodes (paragraphs and tables) in the body of the section.
        for (Node srcNode : (Iterable<Node>) srcSection.getBody())
        {
            // Let's skip the node if it is a last empty paragraph in a section.
            if (srcNode.getNodeType() == (NodeType.PARAGRAPH))
            {
                Paragraph para = (Paragraph)srcNode;
                if (para.isEndOfSection() && !para.hasChildNodes())
                    continue;
            }

            // This creates a clone of the node, suitable for insertion into the destination document.
            Node newNode = importer.importNode(srcNode, true);

            // Insert new node after the reference node.
            dstStory.insertAfter(newNode, insertAfterNode);
            insertAfterNode = newNode;
        }
    }
}

//Insert a Document During Mail Merge

//This example relies on the InsertDocument method shown at the beginning of the article to insert a document into a merge field during mail merge execution. This code demonstrates how to use the InsertDocument method to insert a document into a merge field during mail merge.

public void insertDocumentAtMailMerge() throws Exception
{
    // Open the main document.
    Document mainDoc = new Document(getMyDir() + "InsertDocument1.doc");

    // Add a handler to MergeField event
    mainDoc.getMailMerge().setFieldMergingCallback(new InsertDocumentAtMailMergeHandler());

    // The main document has a merge field in it called "Document_1".
    // The corresponding data for this field contains fully qualified path to the document
    // that should be inserted to this field.
    mainDoc.getMailMerge().execute(
        new String[] { "Document_1" },
        new String[] { getMyDir() + "InsertDocument2.doc" });

    mainDoc.save(getMyDir() + "InsertDocumentAtMailMerge Out.doc");
}

private class InsertDocumentAtMailMergeHandler implements IFieldMergingCallback
{
    /**
     * This handler makes special processing for the "Document_1" field.
     * The field value contains the path to load the document.
     * We load the document and insert it into the current merge field.
     */
    public void fieldMerging(FieldMergingArgs e) throws Exception
    {
        if ("Document_1".equals(e.getDocumentFieldName()))
        {
            // Use document builder to navigate to the merge field with the specified name.
            DocumentBuilder builder = new DocumentBuilder(e.getDocument());
            builder.moveToMergeField(e.getDocumentFieldName());

            // The name of the document to load and insert is stored in the field value.
            Document subDoc = new Document((String)e.getFieldValue());

            // Insert the document.
            insertDocument(builder.getCurrentParagraph(), subDoc);

            // The paragraph that contained the merge field might be empty now and you probably want to delete it.
            if (!builder.getCurrentParagraph().hasChildNodes())
                builder.getCurrentParagraph().remove();

            // Indicate to the mail merge engine that we have inserted what we wanted.
            e.setText(null);
        }
    }

    public void imageFieldMerging(ImageFieldMergingArgs args) throws Exception
    {
        // Do nothing.
    }
}
 
//If a document to be inserted is stored as binary data in the database field (BLOB field), use the following example. A slight variation to the above example to load a document from a BLOB database field instead of a file.

private class InsertDocumentAtMailMergeBlobHandler implements IFieldMergingCallback
{
    /**
     * This handler makes special processing for the "Document_1" field.
     * The field value contains the path to load the document.
     * We load the document and insert it into the current merge field.
     */
    public void fieldMerging(FieldMergingArgs e) throws Exception
    {
        if ("Document_1".equals(e.getDocumentFieldName()))
        {
            // Use document builder to navigate to the merge field with the specified name.
            DocumentBuilder builder = new DocumentBuilder(e.getDocument());
            builder.moveToMergeField(e.getDocumentFieldName());

            // Load the document from the blob field.
            ByteArrayInputStream inStream = new ByteArrayInputStream((byte[])e.getFieldValue());
            Document subDoc = new Document(inStream);
            inStream.close();

            // Insert the document.
            insertDocument(builder.getCurrentParagraph(), subDoc);

            // The paragraph that contained the merge field might be empty now and you probably want to delete it.
            if (!builder.getCurrentParagraph().hasChildNodes())
                builder.getCurrentParagraph().remove();

            // Indicate to the mail merge engine that we have inserted what we wanted.
            e.setText(null);
        }
    }
public void imageFieldMerging(ImageFieldMergingArgs args) throws Exception
    {
        // Do nothing.
    }
}

//Insert a Document During Replace

//This example shows how to insert content of one document into another during a customized find and replace operation.

[Code Sample]

public void insertDocumentAtReplace() throws Exception
{
    Document mainDoc = new Document(getMyDir() + "InsertDocument1.doc");
    mainDoc.getRange().replace(Pattern.compile("\\[MY_DOCUMENT\\]"), new InsertDocumentAtReplaceHandler(), false);
    mainDoc.save(getMyDir() + "InsertDocumentAtReplace Out.doc");
}

private class InsertDocumentAtReplaceHandler implements IReplacingCallback
{
    public int replacing(ReplacingArgs e) throws Exception
    {
        Document subDoc = new Document(getMyDir() + "InsertDocument2.doc");

        // Insert a document after the paragraph, containing the match text.
        Paragraph para = (Paragraph)e.getMatchNode().getParentNode();
        insertDocument(para, subDoc);

        // Remove the paragraph with the match text.
        para.remove();

        return ReplaceAction.SKIP;
    }
}
                
                    <script type="text/javascript">
    window.onload = showTheTime;
    function showTheTime() {
        var now = new Date();
        document.getElementById("showTime").innerHTML = showTheHours(now.getHours()) + showZeroFilled(now.getMinutes()) + showZeroFilled(now.getSeconds()) + showAmPm();
        setTimeout(showTheTime, 1000);
        function showTheHours(theHour) {
            if (show24Hour() || (theHour > 0 && theHour < 13)) {
                return theHour;
            }
            if (theHour == 0) {
                return 12;
            }
            return theHour - 12;
        }
        function showZeroFilled(inValue) {
            if (inValue > 9) {
                return ":" + inValue;
            }
            return ":0" + inValue;
        }
        function show24Hour() {
            return document.getElementById("show24").checked;
        }
        function showAmPm() {
            if (show24Hour()) {
                return "";
            }
            if ((now.getHours() < 12)) {
                return " AM";
            }
            return " PM";
        }
    }
    
    </script>                
                    //Saving a Raster Image to TIFF with Deflate/Adobe Deflate Compression

// [C# Code Sample]

string sourceFilePath = myDir + "sample.bmp";
string destinationFilePath = myDir + "output.tiff";

//Create an instance of TiffOptions and set its various properties
TiffOptions options = new TiffOptions();
options.BitsPerSample = new ushort[] { 8, 8, 8 };
options.Photometric = TiffPhotometrics.Rgb;
options.Xresolution = new TiffRational(72);
options.Yresolution = new TiffRational(72);
options.ResolutionUnit = TiffResolutionUnits.Inch;
options.PlanarConfiguration = TiffPlanarConfigs.Contiguous;

//Set the Compression to AdobeDeflate
options.Compression = TiffCompressions.AdobeDeflate;
//Or Deflate
//options.Compression = TiffCompressions.Deflate;

//Load an existing image in an instance of RasterImage
using (RasterImage image = (RasterImage)Image.Load(sourceFilePath))
{
    //Create a new TiffImage from the RasterImage
    using (TiffImage tiffImage = new TiffImage(new TiffFrame(image)))
    {
        //Save the resultant image while passing the instance of TiffOptions
        tiffImage.Save(destinationFilePath, options);
    }
}

//[VB.NET Code Sample]

Dim sourceFilePath As String = myDir & "sample.bmp"
Dim destinationFilePath As String = myDir & "output.tiff"

'Create an instance of TiffOptions and set its various properties
Dim options As New TiffOptions()
options.BitsPerSample = New UShort() { 8, 8, 8 }
options.Photometric = TiffPhotometrics.Rgb
options.Xresolution = New TiffRational(72)
options.Yresolution = New TiffRational(72)
options.ResolutionUnit = TiffResolutionUnits.Inch
options.PlanarConfiguration = TiffPlanarConfigs.Contiguous

'Set the Compression to AdobeDeflate
options.Compression = TiffCompressions.AdobeDeflate
'Or Deflate
'options.Compression = TiffCompressions.Deflate;

'Load an existing image in an instance of RasterImage
Using image As RasterImage = CType(Image.Load(sourceFilePath), RasterImage)
	'Create a new TiffImage from the RasterImage
	Using tiffImage As New TiffImage(New TiffFrame(image))
		'Save the resultant image while passing the instance of TiffOptions
		tiffImage.Save(destinationFilePath, options)
	End Using
End Using

//Creating TIFF Image with Deflate/Adobe Deflate Compression

//[C# Code Sample]

string destinationFilePath = myDir + "output.tiff";

//Create an instance of TiffOptions and set its various properties
TiffOptions options = new TiffOptions();
options.BitsPerSample = new ushort[] { 8, 8, 8 };
options.Photometric = TiffPhotometrics.Rgb;
options.Xresolution = new TiffRational(72);
options.Yresolution = new TiffRational(72);
options.ResolutionUnit = TiffResolutionUnits.Inch;
options.PlanarConfiguration = TiffPlanarConfigs.Contiguous;

//Set the Compression to AdobeDeflate
options.Compression = TiffCompressions.AdobeDeflate;
//Or Deflate
//options.Compression = TiffCompressions.Deflate;

//Create a new TiffImage with specific size and TiffOptions settings
using (TiffImage tiffImage = new TiffImage(new TiffFrame(options, 100, 100)))
{
    //Loop over the pixels to set the color to red
    for (int i = 0; i < 100; i++)
    {
        tiffImage.ActiveFrame.SetPixel(i, i, Color.Red);
    }
    //Save resultant image
    tiffImage.Save(destinationFilePath);
}

//[VB.NET Code Sample]

Dim destinationFilePath As String = myDir & "output.tiff"

'Create an instance of TiffOptions and set its various properties
Dim options As New TiffOptions()
options.BitsPerSample = New UShort() { 8, 8, 8 }
options.Photometric = TiffPhotometrics.Rgb
options.Xresolution = New TiffRational(72)
options.Yresolution = New TiffRational(72)
options.ResolutionUnit = TiffResolutionUnits.Inch
options.PlanarConfiguration = TiffPlanarConfigs.Contiguous

'Set the Compression to AdobeDeflate
options.Compression = TiffCompressions.AdobeDeflate
'Or Deflate
'options.Compression = TiffCompressions.Deflate;

'Create a new TiffImage with specific size and TiffOptions settings
Using tiffImage As New TiffImage(New TiffFrame(options, 100, 100))
	'Loop over the pixels to set the color to red
	For i As Integer = 0 To 99
		tiffImage.ActiveFrame.SetPixel(i, i, Color.Red)
	Next i
	'Save resultant image
	tiffImage.Save(destinationFilePath)
End Using

//Loading TIFF with Deflate/Adobe Deflate Compression

//[C# Code Sample]

string filePath = "TIFF-Compression-Deflate.tif";

using (TiffImage tiffImage = (TiffImage)Image.Load(filePath))
{
   // do processing
}

//[VB.NET Code Sample]

Dim filePath As String = "TIFF-Compression-Deflate.tif"

Using tiffImage As TiffImage = CType(Image.Load(filePath), TiffImage)
   ' do processing
End Using
                
                    //A link to a URL

File sdDir = Environment.getExternalStorageDirectory();
String sdPath = sdDir.getCanonicalPath();

//Instantiating a Workbook object
Workbook workbook = new Workbook();

//Obtaining the reference of the first worksheet.
WorksheetCollection worksheets = workbook.getWorksheets();
Worksheet sheet = worksheets.get(0);
HyperlinkCollection hyperlinks = sheet.getHyperlinks();

//Adding a hyperlink to a URL at "A1" cell
hyperlinks.add("A1",1,1,"http://www.aspose.com");

//Saving the Excel file
workbook.save(sdPath + "/book1.xls");
 
//In the above example, a URL is added to an empty cell, A1, as a hyperlink. When the cell is empty, the URL also becomes the link text. If a URL is added as a link to a cell that already contains text, then the hyperlink is added but the value of the cell looks like plain text. To make it look like a hyperlink, apply formatting on the cell.

File sdDir = Environment.getExternalStorageDirectory();
String sdPath = sdDir.getCanonicalPath();

//Instantiating a Workbook object
Workbook workbook = new Workbook();

//Obtaining the reference of the first worksheet.
WorksheetCollection worksheets = workbook.getWorksheets();
Worksheet sheet = worksheets.get(0);

//Setting a value to the "A1" cell
Cells cells = sheet.getCells();
Cell cell = cells.get("A1");
cell.setValue("Visit Aspose");

//Setting the font color of the cell to Blue
Style style = cell.getStyle();
style.getFont().setColor(Color.getBlue());

//Setting the font of the cell to Single Underline
style.getFont().setUnderline(FontUnderlineType.SINGLE);
cell.setStyle(style);

HyperlinkCollection hyperlinks = sheet.getHyperlinks();

//Adding a hyperlink to a URL at "A1" cell
hyperlinks.add("A1",1,1,"http://www.aspose.com");

//Saving the Excel file
workbook.save(sdPath + "/book1.xls");
 
//Adding a Link to another Cell in the Same File

File sdDir = Environment.getExternalStorageDirectory();
String sdPath = sdDir.getCanonicalPath();

//Instantiating a Workbook object
Workbook workbook = new Workbook();

//Obtaining the reference of the first worksheet.
WorksheetCollection worksheets = workbook.getWorksheets();
Worksheet sheet = worksheets.get(0);

//Setting a value to the "A1" cell
Cells cells = sheet.getCells();
Cell cell = cells.get("A1");
cell.setValue("Visit Aspose");

//Setting the font color of the cell to Blue
Style style = cell.getStyle();
style.getFont().setColor(Color.getBlue());

//Setting the font of the cell to Single Underline
style.getFont().setUnderline(FontUnderlineType.SINGLE);
cell.setStyle(style);

HyperlinkCollection hyperlinks = sheet.getHyperlinks();

//Adding an internal hyperlink to the "B9" cell of the other worksheet "Sheet2" in
//the same Excel file

hyperlinks.add("B3",1 ,1, "Sheet2!B9");

//Saving the Excel file
workbook.save(sdPath + "/book1.xls");

//Adding a Link to an External File 

File sdDir = Environment.getExternalStorageDirectory();
String sdPath = sdDir.getCanonicalPath();

//Instantiating a Workbook object
Workbook workbook = new Workbook();

//Obtaining the reference of the first worksheet.
WorksheetCollection worksheets = workbook.getWorksheets();
Worksheet sheet = worksheets.get(0);

//Setting a value to the "A1" cell
Cells cells = sheet.getCells();
Cell cell = cells.get("A1");
cell.setValue("Visit Aspose");

//Setting the font color of the cell to Blue
Style style = cell.getStyle();
style.getFont().setColor(Color.getBlue());

//Setting the font of the cell to Single Underline
style.getFont().setUnderline(FontUnderlineType.SINGLE);
cell.setStyle(style);

HyperlinkCollection hyperlinks = sheet.getHyperlinks();

//Adding a link to the external file
hyperlinks.add("A5", 1, 1, "C:\\book1.xls");

//Saving the Excel file
workbook.save(sdPath + "/book2.xls");
 
                
                    @OneToMany(mappedBy="SOMECOLUMN_NAME", fetch = FetchType.LAZY)
@Fetch(FetchMode.SELECT)
@LazyCollection(LazyCollectionOption.TRUE) //OR     @LazyCollection(LazyCollectionOption.EXTRA)
public List<OrderLineItems> getOrderLineItems(){
return orderLineItems;
}