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

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

                
                    MainActivity.java :

package www.andygeeks.blogspot.com;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import org.json.JSONArray;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    
boolean timeoutexcep=false,httpexcep=false,genexcep=false;
    
private static final String TAG_NAME = "J_Name";
private static final String TAG_ID = "J_Id";
private static final String TAG_PLACE = "J_Place";
private static final String TAG_MOBILE = "J_Phone";
    
public static String dist="Krishnagiri",type="P",no="50";
String Name,Id,Place,Phone;
    
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new pay().execute();
}

class pay extends AsyncTask<Void, Void, Void> {

private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);

@Override
protected void onPreExecute() {
this.dialog.setMessage("Loading data");
this.dialog.show();
}

@Override
protected Void doInBackground(Void... unused) {

final String NAMESPACE = "http://tempuri.org/";
final String URL = "http://www.xxxxxx.com/xxxx/xxx.asmx";
final String SOAP_ACTION = "http://tempuri.org/xxxxx";
final String METHOD_NAME = "xxxxx";

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

request.addProperty("sDistrict", dist);
request.addProperty("sTaxType", type);
request.addProperty("sTaxNo", no);

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;

envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;

try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

String responseJSON=response.toString();
JSONArray jarray =new JSONArray(responseJSON);

Name=jarray.getJSONObject(0).getString(TAG_NAME);
Id=jarray.getJSONObject(0).getString(TAG_ID);
Place=jarray.getJSONObject(0).getString(TAG_PLACE);
Phone=jarray.getJSONObject(0).getString(TAG_MOBILE);

System.out.println(request);
System.out.println(responseJSON);

}
catch(SocketTimeoutException e){
timeoutexcep=true;
e.printStackTrace();
}
catch(UnknownHostException e){
httpexcep=true;
e.printStackTrace();
}
catch (Exception e) {
genexcep=true;
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
if(timeoutexcep){
Toast.makeText(MainActivity.this, "Unable to connect to server, Please try again later",Toast.LENGTH_LONG).show();
}
else if(httpexcep){
Toast.makeText(MainActivity.this, "Please check your Internet connection",Toast.LENGTH_LONG).show();
}
else if(genexcep){
Toast.makeText(MainActivity.this, "Please try later",Toast.LENGTH_LONG).show();
}

else{
tableview();
}
timeoutexcep=false;httpexcep=false;genexcep=false;
}
}

public void tableview(){
try{
TextView name = (TextView)findViewById(R.id.textView5);
name.setText(Name);

TextView door = (TextView)findViewById(R.id.textView6);
door.setText(Id);

TextView ward = (TextView)findViewById(R.id.textView7);
ward.setText(Place);

TextView mobile = (TextView)findViewById(R.id.textView8);
mobile.setText(Phone);
}
catch(Exception e){
}
}
    
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}                
                    package com.bos.jmx;

public class Shutdown implements ShutdownMBean {
	private static volatile boolean flagRunOne = false;

	@Override
	public void shutdown() throws Exception {
		if (!flagRunOne) {
			System.out.println("Server shutting down...");
			//Sample shutdown code here
			Main.shutdown();
			System.out.println("Server shutdown.");
			flagRunOne = true;
		}
	}
}
                
                    <!DOCTYPE html>
<html ng-app="ngSpApp">
<head>
  <title>Single Page App Template</title>
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
		<table style="width:100%;margin:10px">
			<tr>
				<td style="width: 15%;vertical-align: top;">
					<div class="list-group" style="margin-top:20px" >
						<a href="#/" class="list-group-item active">Home</a> 
						<a href="#/link1" class="list-group-item">Link 1</a> 
					</div>
				</td>
				<td style="vertical-align: top;padding-left:10px;">
					<div ng-view></div>
				</td>
			</tr>
		</table>
	</div>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular-route.js"></script>
  <script>
    // 
    // Defining Module
    //
    var spApp = angular.module( "ngSpApp", ['ngRoute'] );
    //
    // Defining Routes
    //
    spApp.config(function($routeProvider) {
    	$routeProvider.when('/link1', {
    		controller : 'Link1Ctrl',
    		templateUrl : 'views/link1.html'
    	}).otherwise({
    		controller : 'HomeCtrl',
    		templateUrl: 'views/home.html'
        });
    });
    //
    // Controller for Home Page
    //
    spApp.controller( "HomeCtrl", [ '$scope', function($scope) {
      $scope.text = 'Hello, this is homepage';
    }]);
    //
    // Controller for Link1 Page
    //
    spApp.controller( "Link1Ctrl", [ '$scope', function($scope) {
      $scope.text = 'Hello, this is link1 page';
    }]);
  </script>
</body>
</html>