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
  • submit to reddit
//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))

Abby Fichtner10/19/14
2176 views
3 replies

Fun Ways to Teach Kids to Code

Following up on my Why We Need to Teach Kid to Code, here are some fun ways to help them learn. So cool – wish some of these were around when I was an 8 year old learning to code on my Atari 800!

//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;
}
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
512m
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vm 
C:\java-home\jdk1.7.0_21\jre\bin\javaw.exe
-vmargs
-Dosgi.requiredJavaVersion=1.7
-Xms40m
-Xmx1024m
//Adding Attachments to a New Email Message

public static void main(String[] args)
{
    // Base folder for reading and writing files
    String strBaseFolder = "D:\\Data\\Aspose\\resources\\";

    //Initialize and Load an existing MSG file by specifying the MessageFormat
    MailMessage email = MailMessage.load(strBaseFolder + "anEmail.msg", MessageFormat.getMsg());

    //Initialize a String variable to get the Email Subject
    String subject = email.getSubject();
    //Append some more information to Subject
    subject = subject + " This text is added to the existing subject";
    //Set the Email Subject
    email.setSubject(subject);

    //Initialize a String variable to get the Email's HTML Body
    String body = email.getHtmlBody();
    //Apppend some more information to the Body variable
    body = body + "<br> This text is added to the existing body";
    //Set the Email Body
    email.setHtmlBody(body);

    //Initialize MailAddressCollection object
    MailAddressCollection contacts = new MailAddressCollection();

    //Retrieve Email's TO list
    contacts = email.getTo();
    //Check if TO list has some values
    if (contacts.size() > 0)
    {
        //Remove the first email address
        contacts.remove(0);
        //Add another email address to collection
        contacts.add("to1@domain.com");
    }
    //Set the collection as Email's TO list
    email.setTo(contacts);

    //Initialize MailAddressCollection
    contacts = new MailAddressCollection();

    //Retrieve Email's CC list
    contacts = email.getCC();
    //Add another email address to collection
    contacts.add("cc2@domain.com");
    //Set the collection as Email's CC list
    email.setCC(contacts);

    //Save the Email message to disk by specifying the MessageFormat
    email.save(strBaseFolder + "message.msg", MailMessageSaveType.getOutlookMessageFormat());
}

//Loading a Message with Load Options

//To load a message with specific load options, Aspose.Email provides the MessageLoadOptions class that can be used as follow:

MesageLoadOptions options = new MesageLoadOptions();
options.PrefferedTextEncoding = Encoding.getEncoding(1252);
options.setMessageFormat(MessageFormat.getMsg());
MailMessage eml = MailMessage.Load("EMAIL_497563\\test3.msg", options);

import java.io.IOException;
import java.util.Scanner;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class filter
 * @author prgrmmr.aben [at] gmail (dot) com
 * http://fivesnippets.blogspot.com/2014/08/servlet-filter-for-ddos-spam-etc.html
 * please give back a small donation if you find
 * this little educational snippet of code useful 
 */
@WebFilter("/filter")
public class filter implements Filter {

    /**
     * Default constructor. 
     */
    public filter() {
        // TODO Auto-generated constructor stub
    }

 /**
  * @see Filter#destroy()
  */
 public void destroy() {
  // TODO Auto-generated method stub
 }

 /**
  * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
  */
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  HttpSession session;
  System.out.println("being filtered"); //you can use logging instead
  HttpServletRequest req = (HttpServletRequest)request;
  HttpServletResponse res = (HttpServletResponse)response;
                res.addHeader("X-FRAME-OPTIONS", "DENY" ); 
  String requestedPath = req.getRequestURI().substring(req.getContextPath().length());
                // I was using the test bellow when developing the app
  /*Scanner verify = new Scanner(System.in);
  if(verify.nextInt()==0){
   req.getSession().invalidate();
  }*/
  session = req.getSession(false);
  if(req.getSession(false) == null){
   session = req.getSession(true);
   sessionInit(session);
   req.getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
  }else{
   long timeElapsed =  System.currentTimeMillis() - (long) session.getAttribute("lastTime"); 
   System.out.println(timeElapsed);
   System.out.println("seen");
   if(session.getAttribute("spam").equals(true))
    System.out.println("spams are not allowed"); //you can use logging instead
   else if (timeElapsed<2000) {
    session.setAttribute("spam", true);
    System.out.println("spam need to be blocked");
   }else if (session.getAttribute("logged").equals(false)) {
    session.setAttribute("lastTime", System.currentTimeMillis());
    req.getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
   System.out.println(2);
   }else{//if session.getAttribute("logged").equals(true) which should be set to true after user is logged
    System.out.println(requestedPath);
    session.setAttribute("lastTime", System.currentTimeMillis());
    if(requestedPath.equals("/login.jsp"))
     req.getServletContext().getRequestDispatcher("/main.jsp").forward(request, response);
    else
     req.getServletContext().getRequestDispatcher(requestedPath).forward(request, response);
   }
  }
  

  //chain.doFilter(request, response);
 }

 private void sessionInit(HttpSession session) {
  // TODO Auto-generated method stub
  System.out.println("init");
  session.setAttribute("spam", false);
  session.setAttribute("logged", true);
  session.setAttribute("lastTime", System.currentTimeMillis());
  
 }

 /**
  * @see Filter#init(FilterConfig)
  */
 public void init(FilterConfig fConfig) throws ServletException {
  // TODO Auto-generated method stub

 }

}
CREATE TABLE IF NOT EXISTS `session` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  /*`refUser` int(11) DEFAULT NULL COMMENT 'references user number',*/
  `IP` int(39) DEFAULT NULL,
  `creation` datetime NOT NULL TIMESTAMP DEFAULT CURRENT_TIMESTAMP  COMMENT 'creation time',
  `expiry` datetime DEFAULT NULL  COMMENT 'expiry time',
  `secretToken` varchar(10) NOT NULL,
  `type` enum('guest','client') NOT NULL DEFAULT 'guest',
  PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='don''t need to be a real session in memory' AUTO_INCREMENT=1 ;
CREATE TABLE cachedSession ENGINE=MEMORY SELECT * FROM session;
CREATE DEFINER=`root`@`localhost` PROCEDURE `cacheSessions`()
    NO SQL
BEGIN
DELETE FROM cachedsession WHERE 1;
INSERT INTO cachedsession SELECT * FROM session WHERE `expiry`<NOW();
SELECT row_count();
end$$
 
CREATE DEFINER=`root`@`localhost` PROCEDURE `cleanSession`()
    NO SQL
    COMMENT 'clean sessions expired @hours ago'
BEGIN
DELETE FROM `session` WHERE  TIMESTAMPDIFF(MINUTE, expiry, NOW())>0;
SELECT row_count();
end$$
//Shows how to setup a connection to a database and execute commands.

//[C# Code Sample]

// Create a connection to the database.
mConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dbName);

// Open the database connection.
mConnection.Open();

//[VB Code Sample]

' Create a connection to the database.
mConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbName)

' Open the database connection.
mConnection.Open()

//Stores a document to the specified database

//[C# Code Sample]
 

public static void StoreToDatabase(Document doc)
{
    // Save the document to a MemoryStream object.
    MemoryStream stream = new MemoryStream();
    doc.Save(stream, SaveFormat.Doc);

    // Get the filename from the document.
    string fileName = Path.GetFileName(doc.OriginalFileName);

    // Create the SQL command.
    string commandString = "INSERT INTO Documents (FileName, FileContent) VALUES('" + fileName + "', @Doc)";
    OleDbCommand command = new OleDbCommand(commandString, mConnection);

    // Add the @Doc parameter.
    command.Parameters.AddWithValue("Doc", stream.ToArray());

    // Write the document to the database.
    command.ExecuteNonQuery();

}
 
//[VB.NET Code Sample]
 

Public Shared Sub StoreToDatabase(ByVal doc As Document)
    ' Save the document to a MemoryStream object.
    Dim stream As New MemoryStream()
    doc.Save(stream, SaveFormat.Doc)

    ' Get the filename from the document.
    Dim fileName As String = Path.GetFileName(doc.OriginalFileName)

    ' Create the SQL command.
    Dim commandString As String = "INSERT INTO Documents (FileName, FileContent) VALUES('" & fileName & "', @Doc)"
    Dim command As New OleDbCommand(commandString, mConnection)

    ' Add the @Doc parameter.
    command.Parameters.AddWithValue("Doc", stream.ToArray())

    ' Write the document to the database.
    command.ExecuteNonQuery()

End Sub

//Retrieves and returns the document from the specified database using the filename as a key to fetch the document.

//[C# Code Sample]
 

public static Document ReadFromDatabase(string fileName, string path)
{
    // Create the SQL command.
    string commandString = "SELECT * FROM Documents WHERE FileName='" + fileName + "'";
    OleDbCommand command = new OleDbCommand(commandString, mConnection);

    // Create the data adapter.
    OleDbDataAdapter adapter = new OleDbDataAdapter(command);

    // Fill the results from the database into a DataTable.
    DataTable dataTable = new DataTable();
    adapter.Fill(dataTable);

    // Check there was a matching record found from the database and throw an exception if no record was found.
    if (dataTable.Rows.Count == 0)
        throw new ArgumentException(string.Format("Could not find any record matching the document \"{0}\" in the database.", fileName));

    // The document is stored in byte form in the FileContent column.
    // Retrieve these bytes of the first matching record to a new buffer.
    byte[] buffer = (byte[])dataTable.Rows[0]["FileContent"];

    // Wrap the bytes from the buffer into a new MemoryStream object.
    MemoryStream newStream = new MemoryStream(buffer);

    // Read the document from the stream.
    Document doc = new Document(newStream);

    // Return the retrieved document.
    return doc;

}
 
//[VB.NET Code Sample]
 

Public Shared Function ReadFromDatabase(ByVal fileName As String, ByVal path As String) As Document
    ' Create the SQL command.
    Dim commandString As String = "SELECT * FROM Documents WHERE FileName='" & fileName & "'"
    Dim command As New OleDbCommand(commandString, mConnection)

    ' Create the data adapter.
    Dim adapter As New OleDbDataAdapter(command)

    ' Fill the results from the database into a DataTable.
    Dim dataTable As New DataTable()
    adapter.Fill(dataTable)

    ' Check there was a matching record found from the database and throw an exception if no record was found.
    If dataTable.Rows.Count = 0 Then
        Throw New ArgumentException(String.Format("Could not find any record matching the document ""{0}"" in the database.", fileName))

    End If

    ' The document is stored in byte form in the FileContent column.
    ' Retrieve these bytes of the first matching record to a new buffer.
    Dim buffer() As Byte = CType(dataTable.Rows(0)("FileContent"), Byte())

    ' Wrap the bytes from the buffer into a new MemoryStream object.
    Dim newStream As New MemoryStream(buffer)

    ' Read the document from the stream.
    Dim doc As New Document(newStream)

    ' Return the retrieved document.
    Return doc

End Function

//Delete the document from the database, using filename to fetch the record.

//[C# Code Sample]
 

public static void DeleteFromDatabase(string fileName)
{
    // Create the SQL command.
    string commandString = "DELETE * FROM Documents WHERE FileName='" + fileName + "'";
    OleDbCommand command = new OleDbCommand(commandString, mConnection);

    // Delete the record.
    command.ExecuteNonQuery();

}
 
//[VB.NET Code Sample]
 

Public Shared Sub DeleteFromDatabase(ByVal fileName As String)
    ' Create the SQL command.
    Dim commandString As String = "DELETE * FROM Documents WHERE FileName='" & fileName & "'"
    Dim command As New OleDbCommand(commandString, mConnection)

    ' Delete the record.
    command.ExecuteNonQuery()
//Stores the document to a database, then reads the same document back again, and finally deletes the record containing the document from the database.

//[C# Code Sample]
 

// Store the document to the database.
StoreToDatabase(doc);
// Read the document from the database and store the file to disk.
Document dbDoc = ReadFromDatabase(fileName, dataDir);

// Save the retrieved document to disk.
string newFileName = Path.GetFileNameWithoutExtension(fileName) + " from DB" + Path.GetExtension(fileName);
dbDoc.Save(dataDir + newFileName);

// Delete the document from the database.
DeleteFromDatabase(fileName);

// Close the connection to the database.
mConnection.Close();
 
//[VB.NET Code Sample]
 
' Store the document to the database.
StoreToDatabase(doc)
' Read the document from the database and store the file to disk.
Dim dbDoc As Document = ReadFromDatabase(fileName, dataDir)

' Save the retrieved document to disk.
Dim newFileName As String = Path.GetFileNameWithoutExtension(fileName) & " from DB" & Path.GetExtension(fileName)
dbDoc.Save(dataDir & newFileName)

' Delete the document from the database.
DeleteFromDatabase(fileName)

' Close the connection to the database.
mConnection.Close()
//Load EML and Save to MSG and MHTML

public static void ConvertFromEML()
{
    // Base folder for reading and writing files
    String  strBaseFolder  = Environment.getExternalStorageDirectory().getPath();
    strBaseFolder = strBaseFolder + "/";

    //Initialize and Load an existing EML file by specifying the MessageFormat
    MailMessage msg = MailMessage.load(strBaseFolder + "AnEmail.eml", MessageFormat.getEml());

    //Save the Email message to disk by specifying the MSG and MHT MailMessageSaveType
    msg.save(strBaseFolder + "message.msg", MailMessageSaveType.getOutlookMessageFormat());
    msg.save(strBaseFolder + "message.mhtml", MailMessageSaveType.getMHtmlFormat());
}

//Load MSG and Save to EML and MHTML

public static void ConvertFromMSG()
{
    // Base folder for reading and writing files
    String  strBaseFolder  = Environment.getExternalStorageDirectory().getPath();
    strBaseFolder = strBaseFolder + "/";

    //Initialize and Load an existing MSG file by specifying the MessageFormat
    MailMessage msg = MailMessage.load(strBaseFolder + "AnEmail.msg", MessageFormat.getMsg());

    //Save the Email message to disk by specifying the EML and MHT MailMessageSaveType
    msg.save(strBaseFolder + "message.eml", MailMessageSaveType.getEmlFormat());
    msg.save(strBaseFolder + "message.mhtml", MailMessageSaveType.getMHtmlFormat());
}

//Load MHTML and Save as EML and MSG

public static void ConvertFromMHTML()
{
    // Base folder for reading and writing files
    String  strBaseFolder  = Environment.getExternalStorageDirectory().getPath();
    strBaseFolder = strBaseFolder + "/";

        //Initialize and Load an existing MHT file by specifying the MessageFormat
    MailMessage msg = MailMessage.load(strBaseFolder + "AnEmail.mhtml", MessageFormat.getMht());

    //Save the Email message to disk by specifying the EML and MSG MailMessageSaveType
    msg.save(strBaseFolder + "message.eml", MailMessageSaveType.getEmlFormat());
    msg.save(strBaseFolder + "message.msg", MailMessageSaveType.getOutlookMessageFormat());
}
Abby Fichtner08/22/14
7976 views
0 replies

Why We Need to Teach Kids to Code

Coding (computer programming) is the art of creating anything from computer games and iPhone apps to computational models that help us improve health care. As our kids grow up, this ability to code will become as fundamental as reading and writing to their success, regardless of what occupation they ultimately choose.

//Code sample shows how to create content control of type rich text box.

//[C# code sample]

Document doc = new Document();
StructuredDocumentTag sdtRichText = new StructuredDocumentTag(doc, SdtType.RichText, MarkupLevel.Block);

Paragraph para = new Paragraph(doc);
Run run = new Run(doc);
run.Text = "Hello World";
run.Font.Color = Color.Green;
para.Runs.Add(run);
sdtRichText.ChildNodes.Add(para);
doc.FirstSection.Body.AppendChild(sdtRichText);

doc.Save(MyDir + "Out.docx");

//[VB Code Sample]

Dim doc As New Document()
Dim sdtRichText As New StructuredDocumentTag(doc, SdtType.RichText, MarkupLevel.Block)

Dim para As New Paragraph(doc)
Dim run As New Run(doc)
run.Text = "Hello World"
run.Font.Color = Color.Green
para.Runs.Add(run)
sdtRichText.ChildNodes.Add(para)
doc.FirstSection.Body.AppendChild(sdtRichText)

doc.Save(MyDir & "Out.docx")
 
//Code samples for how to create content control of type combo box.

//[C# code sample]

Document doc = new Document();
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.ComboBox, MarkupLevel.Block);

sdt.ListItems.Add(new SdtListItem("Choose an item", "-1"));
sdt.ListItems.Add(new SdtListItem("Item 1", "1"));
sdt.ListItems.Add(new SdtListItem("Item 2", "2"));
doc.FirstSection.Body.AppendChild(sdt);

doc.Save(MyDir + "Out.docx");
 
//[VB Code Sample]

Dim doc As New Document()
Dim sdt As New StructuredDocumentTag(doc, SdtType.ComboBox, MarkupLevel.Block)

sdt.ListItems.Add(New SdtListItem("Choose an item", "-1"))
sdt.ListItems.Add(New SdtListItem("Item 1", "1"))
sdt.ListItems.Add(New SdtListItem("Item 2", "2"))
doc.FirstSection.Body.AppendChild(sdt)

doc.Save(MyDir & "Out.docx")
 
//Code for how to modify content controls of type plain text box, drop down list and picture.

//[C# code sample]

Document doc = new Document(MyDir + "in.docx");

foreach (StructuredDocumentTag sdt in doc.GetChildNodes(NodeType.StructuredDocumentTag, true))
{
    if (sdt.SdtType == SdtType.PlainText)
    {
        sdt.RemoveAllChildren();
        Paragraph para = sdt.AppendChild(new Paragraph(doc)) as Paragraph;
        Run run = new Run(doc, "new text goes here");
        para.AppendChild(run);
    }
    else if (sdt.SdtType == SdtType.DropDownList)
    {
        SdtListItem secondItem = sdt.ListItems[2];
        sdt.ListItems.SelectedValue = secondItem;
    }
    else if (sdt.SdtType == SdtType.Picture)
    {
        DrawingML dml = (DrawingML)sdt.GetChild(NodeType.DrawingML, 0, true);
        if (dml.HasImage)
        {
            dml.ImageData.SetImage(MyDir + "image.png");
        }
    }
}

doc.Save(MyDir + "Out.docx");
 
//[VB Code Sample]

Dim doc As New Document(MyDir & "in.docx")

For Each sdt As StructuredDocumentTag In doc.GetChildNodes(NodeType.StructuredDocumentTag, True)
    If sdt.SdtType = SdtType.PlainText Then
        sdt.RemoveAllChildren()
        Dim para As Paragraph = TryCast(sdt.AppendChild(New Paragraph(doc)), Paragraph)
        Dim run As New Run(doc, "new text goes here")
        para.AppendChild(run)
    ElseIf sdt.SdtType = SdtType.DropDownList Then
        Dim secondItem As SdtListItem = sdt.ListItems(2)
        sdt.ListItems.SelectedValue = secondItem
    ElseIf sdt.SdtType = SdtType.Picture Then
        Dim dml As DrawingML = DirectCast(sdt.GetChild(NodeType.DrawingML, 0, True), DrawingML)
        If dml.HasImage Then
            dml.ImageData.SetImage(MyDir & "image.png")
        End If
    End If
Next

doc.Save(MyDir & "Out.docx")
JQuery::
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script>
		jQuery.fn.alternateColorCellBoard=function(p1,p2,parr,col1,col2,ht,wd){
			return this.append(
				    function(){
				        var content='<table border="1" id="acbGridTable">';
				        var idv=0;
				        var colr=0;
				        for (var i=0; i<p1; i++  ){			        	 
				        	content=content+'<tr id="acbRId_'+i+'">';
				        	for (var j=0; j<p2; j++  ){
				        		if(i%2<1){
				        			if(j%2<1)
				        				colr=col1;
				        			else 
				        				colr=col2;				        			
				        		}else{ 
				        			if(j%2<1)
				        				colr=col2;			        				
				        			else 
				        				colr=col1;				        			
				        		}
				        		content=content+'<td height="'+ht+'"px" width="'+wd+'"px" bgcolor="'+colr+'" class="acbCId_'+idv+'" id="acbCId_'+idv+'">'+parr[idv]+'</td>';
				            	idv++;
				        	}			        	
				        	content=content+'</tr>';
				        }
				        content= content+'</table>';
				        return content;
				    });
		}
</script>




The HTML ::

<body>
<div>
	<div id="chequeredBoard"></div>
</div>
</body>

<script>
var myArr = [];
for (var i=0; i<100; i++  ){
	myArr[i]=i+1;
}

$(document).ready(function() {	   
		$('#chequeredBoard').alternateColorCellBoard(10,10,myArr,"red","skyblue",50,50);			
	});
</script>
//Load a diagram
Diagram diagram = new Diagram("C:\\Drawing1.vdx");

//Get first page
if (diagram.getPages().getCount() == 0)
{
    JOptionPane.showConfirmDialog(null, "The diagram does not contain pages.");
    return;
}
Page page0 = diagram.getPages().getPage(0);
//Get the rectangle master
Master masterRectangle = null;
for (Master master : (Iterable<Master>) diagram.getMasters())
    if (master.getName() == "Rectangle")
    {
        masterRectangle = master;
        break;
    }
if (masterRectangle == null)
{
    JOptionPane.showConfirmDialog(null, "The diagram does not contain rectangle's master.");
    return;
}
//Get the next shape ID
long nextID;
for (Page page : (Iterable<Page>)diagram.getPages())
{
    for (Shape shape : (Iterable<Shape>) page.getShapes())
    {
        long temp = GetMaxShapeID(shape);
        if (temp > nextID)
            nextID = temp;
    }
    nextID++;
}
//Set shape properties and add it in the shapes' collection
Shape rectangle = new Shape();
rectangle.setMaster(masterRectangle);
rectangle.setMasterShape(masterRectangle.getShapes().getShape(0));
rectangle.setID(nextID);
rectangle.getXForm().getPinX().setValue(5);
rectangle.getXForm().getPinY().setValue(5);
rectangle.setType(TypeValue.SHAPE);
rectangle.getText().getValue().add(new Txt("Aspose Diagram"));
rectangle.setTextStyle(diagram.getStyleSheets().getStyleSheet(3));
rectangle.getLine().getLineColor().setValue(page0.getShapes().getShape(1).getFill().getFillForegnd().getValue());
rectangle.getLine().getLineWeight().setValue(0.03041666666666667);
rectangle.getLine().getRounding().setValue(0.1);
rectangle.getFill().getFillBkgnd().setValue(page0.getShapes().getShape(0).getFill().getFillBkgnd().getValue());
rectangle.getFill().getFillForegnd().setValue("#ebf8df");
page0.getShapes().add(rectangle);
diagram.save("C:\\output.vdx", SaveFileFormat.VDX);
JOptionPane.showConfirmDialog(null, "Shape has been added.");

private long GetMaxShapeID(Shape shape)
{
    long max = shape.getID();
    for (Shape child : (Iterable<Shape>)shape.getShapes())
    {
        long temp = GetMaxShapeID(child);
        if (temp > max)
            max = temp;
    }
    return max;
}

Context XML (userDAO-queries.xml) part :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans		 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
						http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
    
<util:map id="VALIDATE_USER_CREDENTIAL" key-type="java.lang.String" value-type="java.lang.String" >
    	<entry key="QUERY" >
    		 <value>SELECT	user_id,	 user_name,  user_password 
			FROM	ty_users 
			WHERE	user_name = ? AND user_password = ?
   		</value>
    	</entry> 
    </util:map>
</beans>




Java Code Part:

UserDAOImpl.java
public class UserDAOImpl implements UserDAO{
	
	private static final Logger logger = LoggerFactory.getLogger(UserDAOImpl.class);// logger
	
	DBQueries dbQuery = new DBQueriesImpl("userDAO-queries.xml");//
	DBConnection dbConn = ConnectionFactory.getInstance().getConnectionMySQL();
	
	@Override
	public List<User> authenitcUserDetails(String userName, String userPassword) {
		Map<String, String> queryMap = null;
		String query ;
		List<Map<String, Object>> mappedUserList = null;
		List<User> listUser = null;
		try{	
			listUser = new ArrayList<User>();
			queryMap = dbQuery.getQueryBeanFromFactory("VALIDATE_USER_CREDENTIAL"); //passing the query-name or Map Id.
			query =  dbQuery.getQuery(queryMap);//passing the query-map to get the query.

//rest of the code is common fetching code.						
			mappedUserList = dbConn.dbQueryRead(query, new Object[]{userName,userPassword});			
			if(mappedUserList.size()>0){
				listUser =  new QueryResultSetMapperImpl<User>().mapRersultSetToObject(mappedUserList, User.class);
			}
		}catch(Exception  ex){
			logger.error("fetchAllUser Error:: ", ex);
		}		
		return listUser;
	}
}








DBQueriesImpl.java
public class DBQueriesImpl implements DBQueries {
	
	private static final Logger logger = LoggerFactory.getLogger(DBQueriesImpl.class);
		
	private ApplicationContext queriesCtx ;
	
       /**
	 * @Desc: Loading the queryContext xml
	 * @param queryContext
	 */
	public DBQueriesImpl(String queryContext) {
		queriesCtx = new ClassPathXmlApplicationContext(queryContext);
	}
	
        /**
	 * @Desc: Reading from the loaded application context and getting the query-map, .  
	 */
	@Override
	public Map<String, String> getQueryBeanFromFactory(String beanId){
		Map<String, String> queryMap = null;
		if (queriesCtx != null && beanId != null) {
			queryMap = (Map<String, String>)queriesCtx.getBean(beanId);
		}
		return queryMap;
	}
	
       /**
	 * @Desc: Getting the exact query from the query-map, .  
	 */	
	@Override
	public String getQuery(Map<String, String> queryMap) {
		String query=null;
		try{
			if(queryMap.containsKey(QueryConstants.QUERY_NODE)){
				query = (String) queryMap.get(QueryConstants.QUERY_NODE);
				queryMap.remove(QueryConstants.QUERY_NODE);
			}else{
				throw new NoSuchFieldError();
			}
		}catch(Exception excp){
			excp.printStackTrace();
		}
		return query;
	}	
}
<html>
  <head>
    <title>Hello React</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <script src="http://fb.me/react-0.11.1.js"></script>
    <script src="http://fb.me/JSXTransformer-0.11.1.js"></script>
    <script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
  </head>
  <body>
    <div class="container">
      <div class="page-header">
        <h1>ReactJS Hello World - Code Example</h1>
      </div>
      <div id="sayhello"></div>  
    </div>
    <script type="text/jsx">
      /** @jsx React.DOM */
      //
      // This is the parent component comprising of two inner components
      // One of the component is UserName which is used to allow user to enter their name
      // Other component is HelloText which displays the text such as Hello, World
      //
      var SayHello = React.createClass({
        // This is used to set the state, "data" which is 
        // accessed later in HelloText component to display the updated state
        // 
        getInitialState: function() {
          return {data: 'World'}
        },
        // It is recommended to capture events happening with any children
        // at the parent level and set the new state that updates the children appropriately
        handleNameSubmit: function(name) {
          this.setState({data: name});
        },
        // Render method which is comprised of two components such as UserName and HelloText
        //
        render: function() {
         return(
           <div>
            <UserName onNameSubmit={this.handleNameSubmit}/>
            <HelloText data={this.state.data}/>
           </div>
           );
        }
      });
      // UserName component which has following two methods:
      // handleChange: Used to capture onChange event 
      // render: Code to render the component
      //
      var UserName = React.createClass({
        handleChange: function() {
          var username = this.refs.username.getDOMNode().value.trim();
          this.props.onNameSubmit({username: username });
          this.refs.username.getDOMNode().value = '';
          return false;
        },
        render: function() {
         return(
          <form role="form" onChange={this.handleChange}>
             <div className="input-group input-group-lg">
                <input type="text" className="form-control col-md-8"  placeholder="Type Your Name" ref="username"/>
             </div>
          </form>
          );
        }
      });
      // HelloText component to display Hello World or Hello Name text
      // render: Consists of code display the HelloText component
      //
      var HelloText = React.createClass({
          render: function() {
            return (
            <div>
              <h3>Hello, {this.props.data}</h3>
            </div>
            );
          }
      });
      
      React.renderComponent(
        <SayHello />,
        document.getElementById( "sayhello" )
        );
    </script>
  </body>
</html>
//open document
com.aspose.pdf.Document pdfDocument = new com.aspose.pdf.Document("/mnt/sdcard/input.pdf");
//create text stamp
com.aspose.pdf.TextStamp textStamp = new com.aspose.pdf.TextStamp("Sample Stamp");
//set properties of the stamp
textStamp.setTopMargin(10);
textStamp.setHorizontalAlignment(com.aspose.pdf.HorizontalAlignment.Center);
textStamp.setVerticalAlignment(com.aspose.pdf.VerticalAlignment.Top);

//set text properties
textStamp.getTextState().setFont(new com.aspose.pdf.FontRepository().findFont("Arial"));
textStamp.getTextState().setFontSize(14.0F);
textStamp.getTextState().setFontStyle(com.aspose.pdf.FontStyles.Bold);
textStamp.getTextState().setFontStyle(com.aspose.pdf.FontStyles.Italic);
textStamp.getTextState().setForegroundColor(java.awt.Color.GREEN);

// iterate through all pages of PDF file
for (int Page_counter =1; Page_counter<=pdfDocument.getPages().size();Page_counter++)
{
    //add stamp to all pages of PDF file
    pdfDocument.getPages().get_Item(Page_counter).addStamp(textStamp);
}
//save output document
pdfDocument.save("/mnt/sdcard/TextStamp_output.pdf");