Saturday, August 2, 2014

Mostly asked HR interview questions with points

Here i have listed few key HR round interview questions with bullet point which are mostly asked. These questions are based on my personal experience. I think i should share this information with you and might be helpful to you when you are going to face HR round. Here i have listed only bullet points and not described in details.

Que 1: What is your strength?
Points to remember
Adaptability : Adjustable in any kind of environment situation to work
Hard Working : Very hard working towards work
Honest :
Flexibility : Can work any where and any place in any environment
Optimistic : Positive Attitude
Fast Decision Making : Fast decision making(Good decision) in any kind of situation and pressure
Persistence : Regular in work, work with dedication
Self Motivated : I am self motivated person

Example: I am honest, self motivated and hard working guy with positive attitude towards my carrer and life

Que 2: What is weakness?
Points to remember:
Straightforward : Strait forward attitude
Impatient : Impatient in work.
Sensitive
More Talkative
Trust people very quickly
I can't say no when someone ask for help
Take decisions very quickly
Get nervous when talk to stranger
To speak lie is difficult for me
I am bit lazy about which i am not interested

Example: I can't say no when someone ask for help and little bit lazy about which i am not interested
Note: Include only two-three points in weakness when facing real interview


Que 3: Why should i hire you?
Points to remember:
Share your knowledge
Work Experience
Skills Related to job
Career Goal

Example: With reference to my work experience, i satisfy all the requirement for this job. I am sincere with my work and would never let you down anyway. I promise you will never regret for the decision to appoint me in your organization.

Que 4: Tell me what you know about this company.
Points to remember:
Pre-study about the company in details
Do the background work about ongoing/upcoming projects
Know the names of owners and partners
Research about the current issues
Update your knowledge about their competitors

Example: It's one of the best growing company in India. The work environment of the company is very good. People feel proud to be part of the company as company provides full supports to their employees in professional front it has many branches across the world so i have good opportunity to show my talent.

Que 5: Why are looking for job change?
Points to remember
Thanks to previous organization
What you learn in your previous organization
Share your reason for job change
Relates to career goals

Example: I am thankful to my previous organization because i have learnt lot of things there. According to me changes are necessary for everyone to enhance skills, knowledge and for personal growth and financial growth. Your organization is the good platform where i can learn more.

Que 6: What are your salary requirements?
Points to remember
Should share their expected salary
Always say as per the company norms for the job

Example: I have 4 years of experience in IT. My current CTC is XXX Lac/yr salary has never been a big issue for me. Still i am expecting salary as company's norms as per my designation and my qualification and experience which can help me to maintain my standard of level of my personal and economical needs.

Que 7: What are your career goals?
Points to remember
Short term goal
Long term goal

Example: My short term goal is to get a job in reputed company where i can utilize my skills and improve my career path. My long term goal is to be in respectable position in that organization.


Que 8: Do you any questions to ask me?
Points to remember
Express thanks
Salary Structures
Job timings
Job Location
Overtime allowance
Training Period
Probation Period
Transport Facility

Example: Thank you for giving this opportunity. Sir I would like to know about the job timings and transport facility and what will be the job location and salary structure for this job?

Hope this will help you to crack HR round of interview. If you have any suggestion or feedback which help us than please share your opinion and feedback so i can add in the same.

Cheers,
Ashish Mishra

Wednesday, January 29, 2014

DOM4J: Remove duplicate xml elements from xml

Today i will explain about handling duplicate xml elements of xml.

I think you are little bit aware with DOM4J API from Apache Foundation.

DOM4J API basically is for playing with XML. Sometime your facing the issue that how to get distinct element list from the given xml. To achive this we iterate whole document and get required list. But same thing can be achive by given DOM4J API.

You need to have a latest copy of dom4j.jar. You can easily download it from Sourceforge

Here i will show you the practical example of the same.

//XML Document
<?xml version="1.0" encoding="UTF-8"?>
<document>
<element>
<id>1</id>
</element>
<element>
<id>1</id>
</element>
<element>
<id>2</id>
</element>
<element>
<id>3</id>
</element>
<element>
<id>2</id>
</element>
<element>
<id>6</id>
</element>
<element>
<id>5</id>
</element>
<element>
<id>3</id>
</element>
<element>
<id>4</id>
</element>
<element>
<id>4</id>
</element>
</document>

Now create one class file and add below code snippet in your class
String xmlDoc = ""; //Add code which reads the xml input file from your file location

//Creating org.dom4j.Document objet from xml content
Document document = DocumentHelper.parseText(xmlDoc);

//Now creating distinct list from the created xml ducument with below code snippet

List<Node> nodes = document.selectNodes("//document/element", "id", true);

/*
* XPath for distinct element : "//document/element"
* Element name on which nodes will be compare: "id"
* Boolean flag which indicates to remove duplicate nodes or not.
**/

Friday, March 22, 2013

XSLT Transformation: Full Swing Application


Hi to All,

I have lots of work with xslt and XML.
I frequently required xml transformation with xsl file. There haven't any xslt transformation tool with me as a open source.
So i came with basic xslt transformation application with java swing.

Through this application you can transform with the help of xslt.
You can also format your xml in well-formed xml with this application.

Create one class with the help of below sample code your transformer is ready to work. When you run this class then main screen is launched as i have attached screen shot.

You simple select your xslt file and xml file from appropriate button on the main screen. For transformation of xml file is performed by clicking on Transform button.

Once you click on Transform button, than resultant xml file will be printed on blank area of the screen. If any error occurred in transformation than error message will be printed in red color.

If you want to format you xml file, than simply copy your xml file content.
Once you done than clicked on the Format XML button than well-formed xml is being printed on text area.

Below is the full sample code.
-------------------
XSLTransformation.java
-------------------

package com.makhir.main;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.BevelBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.border.TitledBorder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.w3c.dom.Node;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.InputSource;

public class XSLTransformation implements ActionListener {
private static JFrame mainScreen;
private static JPanel mainPanel;
private static JLayeredPane insertLayPan, resultLayPan, operationLayPan;
private static JLabel xmlFileLabel, xslFileLabel;
private static JFileChooser fileChooser;
private static File xslFile, xmlFile;
private static JButton xmlFileSelector, xslFileSelector, transformButton, saveButton, clearButton, formatButton;
private static JTextArea textArea;
private static JScrollPane scrollPane;

static {
initComponents();
}

/**
* Inits the components.
*/
private static void initComponents() {
mainScreen = new JFrame("m@kh!r: XSLT Transformer");
mainPanel = new JPanel();
resultLayPan = new JLayeredPane();
insertLayPan = new JLayeredPane();
xmlFileLabel = new JLabel();
xslFileLabel = new JLabel();
operationLayPan = new JLayeredPane();
// Initializing the file chooser component 
fileChooser = new JFileChooser();
fileChooser.setMultiSelectionEnabled(true);
/* Setting Current Directory */
fileChooser.setCurrentDirectory(new File("."));
fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith(".xml") || f.getName().toLowerCase().endsWith(".xsl") || f.isDirectory();
}
@Override
public String getDescription() {
return "XML or XSL File";
}
});
xmlFileSelector = new JButton();
xslFileSelector = new JButton();
transformButton = new JButton();
saveButton = new JButton();
xmlFile = null;
xslFile = null;
textArea = new JTextArea();
scrollPane = new JScrollPane();
clearButton = new JButton();
formatButton = new JButton();
}

public void createGUI() {
// Main Screen height-width
mainScreen.setSize(845, 630);

// Main Panel height-width
mainPanel.setBorder(new BevelBorder(BevelBorder.RAISED, Color.gray, Color.pink, Color.white, Color.white));
mainPanel.setLayout(null);
mainPanel.setSize(mainScreen.getSize().width - ScreenSizeConstants.mainPanelWidthDiff, mainScreen.getSize().height - ScreenSizeConstants.mainPanelHeightDiff);

// ---- xmlFileLabel ----
xmlFileLabel.setText("XML File");
xmlFileLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
insertLayPan.add(xmlFileLabel, JLayeredPane.DEFAULT_LAYER);
xmlFileLabel.setBounds(15, 25, 125, xmlFileLabel.getPreferredSize().height);

// ---- xslFileLabel ----
xslFileLabel.setText("XSL File");
xslFileLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
insertLayPan.add(xslFileLabel, JLayeredPane.DEFAULT_LAYER);
xslFileLabel.setBounds(15, 78, 125, 14);

// ---- xmlFileSelector button ----
xmlFileSelector.setText("Select XML File");
xmlFileSelector.setFont(new Font("Tahoma", Font.BOLD, 12));
xmlFileSelector.setToolTipText("Click here to select the xml file from your directory");
insertLayPan.add(xmlFileSelector, JLayeredPane.DEFAULT_LAYER);
xmlFileSelector.setBounds(18, 48, 160, 25);
xmlFileSelector.addActionListener(this);

// ---- xslFileSelector button ----
xslFileSelector.setText("Select XSL File");
xslFileSelector.setFont(new Font("Tahoma", Font.BOLD, 12));
xslFileSelector.setToolTipText("Click here to select the xsl file from your directory");
insertLayPan.add(xslFileSelector, JLayeredPane.DEFAULT_LAYER);
xslFileSelector.setBounds(18, 100, 160, 26);
xslFileSelector.addActionListener(this);

// ---- File Selection layered panel
insertLayPan.setBorder(new TitledBorder(null, "File Selection",
TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION, new Font("Tahoma", Font.BOLD, 12), Color.blue));
insertLayPan.setBounds(10, 8, 200, 150);
mainPanel.add(insertLayPan);

// ---- Transformation button ----
transformButton.setText("Transform");
transformButton.setFont(new Font("Tahoma", Font.BOLD, 12));
transformButton.setToolTipText("Click here to transform the xml through xsl");
operationLayPan.add(transformButton, JLayeredPane.DEFAULT_LAYER);
transformButton.setBounds(18, 30, 160, 25);
transformButton.addActionListener(this);

// ---- Save button ----
saveButton.setText("Save");
saveButton.setFont(new Font("Tahoma", Font.BOLD, 12));
saveButton.setToolTipText("Click here to save the xml");
operationLayPan.add(saveButton, JLayeredPane.DEFAULT_LAYER);
saveButton.setBounds(18, 65, 160, 25);
saveButton.addActionListener(this);

// ---- Format button ----
formatButton.setText("Format XML");
formatButton.setFont(new Font("Tahoma", Font.BOLD, 12));
formatButton.setToolTipText("Click here to format xml");
operationLayPan.add(formatButton, JLayeredPane.DEFAULT_LAYER);
formatButton.setBounds(18, 100, 160, 25);
formatButton.addActionListener(this);
// ---- Clear button ----
clearButton.setText("Clear");
clearButton.setFont(new Font("Tahoma", Font.BOLD, 12));
clearButton.setToolTipText("Click here to clear result area");
operationLayPan.add(clearButton, JLayeredPane.DEFAULT_LAYER);
clearButton.setBounds(18, 138, 160, 25);
clearButton.addActionListener(this);

// ---- Operations layered panel
operationLayPan.setBorder(new TitledBorder(null, "Operation", TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION, new Font("Tahoma", Font.BOLD, 12), Color.blue));
operationLayPan.setBounds(10, 158, 200, 190);
mainPanel.add(operationLayPan);

// Setting height and width of component
resultLayPan.setBounds(220, 8, mainPanel.getSize().width - ScreenSizeConstants.resultLayPanWidthDiff, mainPanel.getSize().height - ScreenSizeConstants.resultLayPanHeightDiff);
scrollPane.setBounds(20, 25, resultLayPan.getSize().width - ScreenSizeConstants.scrollPaneWidthDiff, resultLayPan.getSize().height - ScreenSizeConstants.scrollPaneHeightDiff);
textArea.setBounds(5, 5, scrollPane.getSize().width - ScreenSizeConstants.textAreaWidthDiff, scrollPane.getSize().height - ScreenSizeConstants.textAreaHeightDiff);

// ----- textArea ------
textArea.setText("");
//textArea.setBounds(5, 5, 520, 520);
textArea.setFont(new Font("Tahoma", Font.PLAIN, 12));
textArea.setLineWrap(true);

scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.add(textArea);
//scrollPane.setBounds(20, 25, 560, 540);
scrollPane.setAutoscrolls(true);
scrollPane.setViewportView(textArea);
resultLayPan.add(scrollPane, JLayeredPane.DEFAULT_LAYER);

// Display result panel
resultLayPan.setBorder(new CompoundBorder(new TitledBorder(null, "Transformation Result", TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION, new Font("Tahoma", Font.BOLD, 12), Color.blue), null));
//resultLayPan.setBounds(220, 8, 600, 582);
mainPanel.add(resultLayPan);

Toolkit tk = Toolkit.getDefaultToolkit();
   Dimension screenSize = tk.getScreenSize();
   int screenHeight = screenSize.height;
   int screenWidth = screenSize.width;
   mainScreen.setLocation(screenWidth / 4, screenHeight / 4 - 200);
   mainScreen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainScreen.setVisible(true);
mainScreen.getContentPane().add(mainPanel);

final int initialWidth = mainScreen.getSize().width;
final int initialHeight = mainScreen.getSize().height;
mainScreen.addComponentListener(new ComponentAdapter() {
 public void componentResized(ComponentEvent event) {
 int width = Math.max(initialWidth, mainScreen.getWidth());
 int height = Math.max(initialHeight, mainScreen.getHeight());
 mainPanel.setSize(width - ScreenSizeConstants.mainPanelWidthDiff, height - ScreenSizeConstants.mainPanelHeightDiff);
 resultLayPan.setSize(mainPanel.getSize().width - ScreenSizeConstants.resultLayPanWidthDiff, mainPanel.getSize().height - ScreenSizeConstants.resultLayPanHeightDiff);
 scrollPane.setSize(resultLayPan.getSize().width - ScreenSizeConstants.scrollPaneWidthDiff, resultLayPan.getSize().height - ScreenSizeConstants.scrollPaneHeightDiff);
 textArea.setSize(scrollPane.getSize().width - ScreenSizeConstants.textAreaWidthDiff, scrollPane.getSize().height - ScreenSizeConstants.textAreaHeightDiff);
 }
});
}

public void actionPerformed(ActionEvent event){
String command = event.getActionCommand();
String message = "";
int result = -1;
textArea.setForeground(Color.BLACK); // Setting default color
textArea.setFont(new Font("Tahoma", Font.PLAIN, 12)); // Setting default format
if(command.equalsIgnoreCase("Select XML File")){
result = fileChooser.showOpenDialog(new JFrame());
} else if(command.equalsIgnoreCase("Select XSL File")){
result = fileChooser.showOpenDialog(new JFrame());
} else if(command.equalsIgnoreCase("Transform")){
if(xmlFile != null && xslFile != null){
try {
//message = transform(xmlFile, xslFile);
transform(xmlFile, xslFile);
//textArea.setText(message);
} catch (Exception e) {
textArea.setFont(new Font("Tahoma", Font.BOLD, 12));
textArea.setForeground(Color.RED);
textArea.setText(e.getLocalizedMessage());
}
} else {
if(xmlFile == null)
JOptionPane.showMessageDialog(null, "Please, select xml file for transformation");
else if(xslFile == null)
JOptionPane.showMessageDialog(null, "Please, select xsl file for transformation");
else
JOptionPane.showMessageDialog(null, "Please, provide some valuable input");
}
} else if(command.equalsIgnoreCase("Save")){
JOptionPane.showMessageDialog(null, "Yet not implemented..!!");
} else if(command.equalsIgnoreCase("Clear")){
textArea.setText("");
} else if(command.equalsIgnoreCase("Format XML")){
try {
if(textArea.getText().length() > 0)
textArea.setText(formatXML(textArea.getText()));
} catch (Exception e) {
textArea.setFont(new Font("Tahoma", Font.BOLD, 12)); // "Tahoma", Font.BOLD, 12, Color.red
textArea.setForeground(Color.RED);
textArea.setText(e.getLocalizedMessage());
}
} else {
JOptionPane.showMessageDialog(null, "What is this?");
}

if(result == JFileChooser.APPROVE_OPTION){
File tempFile = fileChooser.getSelectedFile();
if(tempFile != null && tempFile.getName().toLowerCase().endsWith(".xml"))
xmlFile = tempFile;
else if(tempFile != null && tempFile.getName().toLowerCase().endsWith(".xsl"))
xslFile = tempFile;
else
JOptionPane.showMessageDialog(null, "Selected file " + fileChooser.getSelectedFile().getName() + " may not useful for xsl transformation.");
} else if(result == JFileChooser.CANCEL_OPTION){
JOptionPane.showMessageDialog(null, "You haven't select any file for transformation");
}
}
/**
* Transform the xml with use of xslt
* */
public void transform(File xmlFile, File xslFile){
try {
TransformerFactory factory = TransformerFactory.newInstance();
       Source xslt = new StreamSource(xslFile);
       Transformer transformer = factory.newTransformer(xslt);
       Source inputXML = new StreamSource(xmlFile);
       StringWriter writer = new StringWriter();
       Result result = new StreamResult(writer);
       if(xmlFile.exists() && xslFile.exists()){
        StreamResult output = new StreamResult(writer);
       transformer.transform(inputXML, output);
       textArea.setText(formatXML(writer.toString()));;
       } else 
        throw new Exception("XML or XSL File not found.");
       
} catch (TransformerException e) {
e.printStackTrace();
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
textArea.setFont(new Font("Tahoma", Font.PLAIN, 10));
textArea.setForeground(Color.RED);
textArea.setText(writer.toString());
//throw e;
}catch (Exception e) {
//e.printStackTrace();
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
textArea.setFont(new Font("Tahoma", Font.BOLD, 12));
textArea.setForeground(Color.BLACK);
textArea.setText(writer.toString());
}
}
/**
* This method format the xml with tagging and newline
* */
public String formatXML(String xml) throws Exception{
try {
        InputSource src = new InputSource(new StringReader(xml));
            Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
            boolean keepDeclaration = xml.startsWith("<?xml");
            DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
            DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
            LSSerializer writer = impl.createLSSerializer();
            writer.getDomConfig().setParameter("format-pretty-print", true); // Set this to true if the output needs to be beautified.
            writer.getDomConfig().setParameter("xml-declaration", keepDeclaration); // Set this to true if the declaration is needed to be outputted.
            LSOutput output = impl.createLSOutput();
            output.setEncoding("UTF-8");
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            output.setByteStream(stream);
            writer.write(document, output);
            return new String(stream.toByteArray(), "UTF-8");
        } catch (Exception e) {
            throw e;
        }
    }
/**
* @param args the arguments
*/
public static void main(String[] args) {
try {
new XSLTransformation().createGUI();
} catch (Exception e) {
e.printStackTrace();
}
}
}
-------------------------
Thats it.

Below is some screen snippet of this application.



Thursday, March 21, 2013

Android: Downloading a file from Server and save it into SD card with progress bar


Android: Downloading a file from Server and save it into SD card with progress bar


Hi to all,
Now i am  going to explain here about how to download file from remote server and save it in SD card.
For this tutorial i assumed that you might have good in Android application development with popular IDE Eclipse.
So lets start to see how this happen in Android.

First of all you need to create a demo application in eclipse.
For me i have created Android Demo.
Create an class which is you launching point of your application.

Here, i called it MainActivity.java which extends the Activity.
Now, before we go in detail we need to give some permission to our
application on mobile device operating system so it can utilize the mobile features.

For internet connectivity we need to add below entry in our AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

This permission is enough to access the internet by our application.

Now we need to give permission for reading and writing to our application.
These can be achieved by adding below permission in AndroidManifest.xml,

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS" />

Now our application has full rights to read/write and access to internet.

After this configuration we need to jump in our designing part.
Here, i have used only one button download. On clicking on the download button it
simply make a remote server request to download a file.

Below is my code snippet for the screen design xml,

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<Button
        android:id="@+id/buttonDownload"
        android:text="@string/buttonDonwload"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:title="@string/buttonDonwload"/>
</menu>

After all these stuffes, now we need to code to make this apps running.
Below is the full code for which you are looking for.

---------------------------------
MainActivity.java
---------------------------------
package com.makhir.android.demo;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
private Button button;
ProgressDialog progDialog;
    int typeBar = 0;                 // Determines type progress bar: 0 = spinner, 1 = horizontal
    int delay = 40;                  // Milliseconds of delay in the update loop
    int maxBarValue = 200;           // Maximum value of horizontal progress bar
    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
   
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

button = (Button) findViewById(R.id.buttonDownload);

button.setOnClickListener(new View.OnClickListener() {
       @Override
            public void onClick(View v) {
                try {
                showDialog(typeBar);
String serverUrl = http://amishra.asite.asitehq.com:8080/exchange/doc.htm;
                new Downloader().getData(serverUrl);
                } catch (Exception e) {
e.printStackTrace();
}
            }
        });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

@Override
    protected Dialog onCreateDialog(int id) {
        switch(id) {
        case 0: // Spinner
            progDialog = new ProgressDialog(this);
            progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progDialog.setMessage("Downloading ...");
            progDialog.setCancelable(false);
            progDialog.show();
            return progDialog;
        case 1: // Horizontal
            progDialog = new ProgressDialog(this);
            progDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progDialog.setMax(maxBarValue);
            progDialog.setMessage("Dollars in checking account:");
            progDialog.setCancelable(false);
            progDialog.show();
            return progDialog;
        default:
            return null;
        }
    }

private class Downloader extends AsyncTask<String, String, String> {
private String reponseData = null;

@Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(typeBar);
        }

protected String doInBackground(String... args) {
int TIMEOUT_MILLISEC = 2000;
int count;
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);

// Instantiate an HttpClient
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(args[0]);

try {
Log.i(getClass().getSimpleName(), "send  task - start");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
reponseData = httpclient.execute(httppost, responseHandler);
Log.i(getClass().getSimpleName(), reponseData);
InputStream inputStream = new ByteArrayInputStream(reponseData.getBytes());

FileOutputStream output = new FileOutputStream(new File("/sdcard/sampleData.xml"));
byte data[] = new byte[1024];
                long total = 0;

                while ((count = inputStream.read(data)) != -1) {
                    total += count;
                    publishProgress("" + (int)(( total * 100) / reponseData.length()));
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                inputStream.close();
            } catch (Throwable t) {
t.printStackTrace();
Log.e("MainActivity", "" + t.getMessage());
}
return null;
}

protected void onProgressUpdate(String... progress) {
            Log.d("ANDRO_ASYNC",progress[0]);
            progDialog.setProgress(Integer.parseInt(progress[0]));
       }

       @Override
       protected void onPostExecute(String unused) {
           dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
  Toast.makeText(getApplicationContext(), "File downloaded successfully", Toast.LENGTH_LONG).show();
       }
 
  public String getData(String url) throws Exception{
try {
execute(url);
} catch (Exception e) {
throw e;
}
return reponseData;
}
}
}
-----

We have done all the required changes for application.
Below are the some screen snippets for application.


Sunday, March 17, 2013

Apche Solr in details with configuration

I were previously posted details of the Apche Solr and its configuration in J2EE.
Here is the web-link of my blog,

This might be useful to your business requirement.

Regards,
Ashish Mishra

Wednesday, February 27, 2013

DWR Integration Step By Step

Brief introduction of DWR
The DWR (Direct Web Remoting) project is an open source solution under the Apache license for the developer who wants to use AJAX and XMLHttpRequest in an easy way. It has a set of JavaScript functions that remove the complexity from calling methods in a Java object running on the application server from the HTML page. It handles parameters of different types and helps keep the HTML code readable.

DWR is not intrusive to one's design, as it does not force any sort of inheritance architecture for objects to be exposed. It fits well in any application that runs in a servlet framework. For the less DHTML-experienced developers, DWR also provides a JavaScript library to help with frequently used DHTML tasks, like populating tables, filling select boxes with items, and changing the content of HTML elements such as and.

The DWR Website is comprehensive and has a fair amount of documentation, which has served as a foundation for this article. Some examples are provided to demonstrate how DWR can be used and what can be accomplished with the library.
Reference: Java World

I am going to show you about how to integrate DWR framework in your running J2EE application. Below are the steps to configure DWR framework.

Step 1: Download required files
For integrating DWR in your application, you need some supported files. You can easily find these files on official page of DWR.
http://directwebremoting.org/dwr/index.html

You need to download below files,
1) dwr.jar [http://directwebremoting.org/dwr/downloads/index.html] [deploy in your respective WEB-INF/lib dir]
2) commons-logging.jar [deploy in your respective WEB-INF/lib dir]
3) util.js [deploy in your respective folder where your jsp and js files resides]
4) engine.js [deploy in your respective folder where your jsp and js files resides]

Step 2: Configuration in your web application
We need to create dwr.xml file where your DWR related configuration and put this file in dir where your web.xml of your application reside.
I am showing the structure of the dwr.xml.
// DWR XML Content

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN" "http://getahead.org/dwr/dwr30.dtd">
<dwr>
<!-- init is only needed if you are extending DWR
<init>
<creator id="..." class="..." />
<converter id="..." class="..." />
</init> -->
<!-- without allow, DWR isn't allowed to do anything -->
<allow>
<filter class="com.makhir.filters.DWRFilter" /><!-- Your DWR filter here which manage the request/response to DWR servlet -->
<create creator="new" javascript="DWRInvoker"><!-- Your DWR Servlet class which handles the actual request and response -->
<param name="class" value="com.makhir.servlets.DWRInvoker"/>
</create>
<convert converter="bean" match="com.makhir.vo.UserRegisterVO" /> <!-- POJO entry for transferring along network if any-->
</allow>
<!-- you may need to tell DWR about method signatures
<signatures>
...
</signatures> -->

</dwr>

Now make an entry for dwr servlet in web.xml for URL mapping as below,
// web.xml entry
<servlet>
<servlet-name>dwr-starter</servlet-name>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<init-param>
    <param-name>debug</param-name>
    <param-value>true</param-value>
  </init-param>
</servlet>
<servlet-mapping>
<servlet-name>dwr-starter</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
Thats it as point of configuration.

Step 3: Code changes for Server side management
A) Create one filter with name DWRFilter whose entry is already available in dwr.xml with name DWRFilter
Note: We need not make this filter entry in our web.xml as we do traditionally
Below is the code snippet of for the filter,

//DWRFilter.java
import java.lang.reflect.Method;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.directwebremoting.AjaxFilter;
import org.directwebremoting.AjaxFilterChain;

public class DWRFilter implements AjaxFilter{
private static Log logger = LogFactory.getLog(DWRFilter.class);
@Override
public Object doFilter(Object object, Method method, Object[] params, AjaxFilterChain filterChain) throws Exception {
logger.debug("Enter : Entering into DWRFilter");
// TODO: Add code for some filteration on methods and params which are interchange between server and client
logger.debug("Exit : Entering into DWRFilter");
return filterChain.doFilter(object, method, params);
}
}

B) Create class for which is going to responsible for handling your reqeust of dwr call from the client
Here i made a class with name DWRInvoker.java as its entry already available in dwr.xml
Below is the code snippet of for the filter,

//DWRInvoker.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.makhir.vo.UserRegisterVO;

public class DWRInvoker {
private static Log logger = LogFactory.getLog(DWRInvoker.class);
public DWRInvoker(){} // Default Constructor
public Object getUserInfo(String userId){
logger.debug("Enter : getUserInfo()");
UserRegisterVO registerVO = new UserRegisterVO(); //UserRegisterVO which is going to transfer on network.Its entry available in dwr.xml
registerVO.setUserName("Ashish Mishra");
registerVO.setUserId(userId);
registerVO.setDepartment("Development");
logger.debug("Exit : getUserInfo()");
return registerVO;
}
}

C) Create POJO class which is also your value object. Here i have created with name UserRegistrationVO.java.
Make an entry in dwr.xml in convert element.

Step 4: Code changes for client side management
Now its time make some changes on client side.
Here we need to create jsp files in which you want to manage your interaction with client and server with help of DWR call.
A) Download engine.js file from official DWR home page and depoly it in your dir where your jsp resides
B) Download util.js file from official DWR home page and depoly it in your dir where your jsp resides
C) Creating DWRInvoker.js in your application where your jsp and scripting files resides

Below is script snippet for your reference,
  //DWRInvoker.js

if (typeof dwr == 'undefined' || dwr.engine == undefined) throw new Error('You must include DWR engine before including this file');
(function() {
 if (dwr.engine._getObject("DWRInvoker") == undefined) {
var p;

p = {};
p._path = '/extreme/dwr';

/**
* @param {class java.awt.image.BufferedImage} p0 a param
* @param {class java.lang.String} p1 a param
* @param {class java.lang.String} p2 a param
* @param {function|Object} callback callback function or options object
*/
p.getUserInfo = function(p0, callback) {
 return dwr.engine._execute(p._path, 'DWRInvoker', 'getUserInfo', arguments);
};

dwr.engine._setObject("DWRInvoker", p);
 }
})();
/**
function DWRInvoker(){}
DWRInvoker.getUserInfo = function(p0,callback){
DWREngine._execute('/extreme/dwr','DWRInvoker','getUserInfo',p0,callback);
}
*/
D) Create your JSP page from where actual DWR calling will happen
  Here, i my case i have created the jsp file for your reference with name profilePage.jsp which load the profile details.
  DWR call will made by the client when profilePage.jsp is load and fetch specific user profile data from server and display it onto client
  browser without refreshing the page.
  You can make DWR call through any of events supported by the HTML component.
  Below is code snippet of the jsp file.
 
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Extreme Application</title>
<script type="text/javascript" src="engine.js"> </script> <%-- engine.js which should always be first  script file to be included [Mandatory] --%>
<script type="text/javascript" src="DWRInvoker.js"> </script> <%-- DWRInvoker.js needs to be included [Mandatory]--%>
<script type="text/javascript" src="util.js"> </script> <%-- util.js needs to be included for enhance the feature provided by DWR[Optional] --%>
<script type="text/javascript">
function loadProfile(){
dwr.util.useLoadingImage('images/ajax-loader.gif'); <%-- Progress image for showing the progress of dwr call on client side  --%>
DWRInvoker.getUserInfo(<%=userid%>, getinfo); <%-- Actual DWR call to get user's profile data from the server  --%>
}
function getinfo(data){ <%-- scripting method which handles the server response from DWR call--%>
document.getElementById("txtUserName").value = data.userName;
document.getElementById("txtDept").value = data.department;
document.getElementById("txtCity").value = data.city;
}
</script>
</head>
<body onload="loadProfile();">
<form action="#" method="post" name="updateFrom" id="updateFrom" enctype="multipart/form-data">
<table align="left" id="regisTable" style="border-color: gray;">
<tr>
<td class="td">Name</td>
<td class="td">:</td>
<td class="td"><input type="text" name="txtUserName" id="txtUserName" value="''"/></td>
</tr>
<tr>
<td class="td">Department</td>
<td class="td">:</td>
<td class="td"><input type="text" name="txtDept" id="txtDept" value="''"/></td>
</tr>
<tr>
<td class="td">City</td>
<td class="td">:</td>
<td class="td"><input type="text" name="txtCity" id="txtCity" value="''" /></td>
</tr>
</table>
</form>
</body>
</html>

I think i might have covered all those things which required to configure DWR in J2EE application.

Regards,
Ashish Mishra