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.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());
}
                
                    //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");