Stack trace is very useful while debugging or troubleshooting any issue in Java. Thankfully Java provides couple of ways to get current stack trace of a Thread in Java, which can be really handy in debugging. When I was new to Java programming, and didn’t know how to remote debug a Java application, I used to put debug code as patch release, which uses classpath to pick debug code for printing stack trace and shows how a particular method is get called and that some time provide vital clue on missing or incorrect argument. Now, When I have couple of Java debugging tips at my sleeve, I still think knowledge of how to get current stack trace in Java for any Thread, or simply print stack trace from any point in code worth knowing. For those who are not very familiar with stack trace and wondering what is stack trace in Java, here is quick revision. Thread executes code in Java, they call methods, and when they call, they keep them in there stack memory. You can print that stack trace to find out, from where a particular method is get called in execution flow. This is especially useful if you are using lot of open source libraries, and don’t have control on all the code. One of the most familiar face of stack trace in Java is printing stack trace using Exception.printStackTrace(), when an Exception or Error is thrown in Java. In this Java tutorial, we will look at couple of ways to print and get current stack trace of a Thread in Java.
Tampilkan postingan dengan label tutorial. Tampilkan semua postingan
Tampilkan postingan dengan label tutorial. Tampilkan semua postingan
Sabtu, 22 Februari 2014
How to get current stack trace in Java for a Thread Debugging Tutorial
Read more »
Diposting oleh
pebel
di
16.45
0
komentar
Kirimkan Ini lewat Email
BlogThis!
Bagikan ke X
Berbagi ke Facebook
Selasa, 18 Februari 2014
Difference between Primary key vs Foreign key in table – SQL database tutorial
Main difference between Primary key and Foreign key in a table is that, it’s the same column which behaves as primary key in parent table and as foreign key in child table. For example in Customer and Orderrelationship, customer_id is primary key in Customer table but foreign key in Order table. By the way what is foreign key in a table and difference between Primary and Foreign key are some of the popular SQL interview questions, much like truncate vs delete in SQL or difference between correlated and noncorrelated subquery. We have been learning key SQL concepts along with these frequently asked SQL questions and in this SQL tutorial we will discuss about what is foreign key in SQL and purpose of foreign key in any table. By the way this is the third article related to primary key in SQL, other being difference between primary and unique key and How to find second highest salary in SQL. If you are preparing for any technical job interview where you expect some SQL questions, check out these questions, they are worth preparing.
Diposting oleh
pebel
di
15.30
0
komentar
Kirimkan Ini lewat Email
BlogThis!
Bagikan ke X
Berbagi ke Facebook
Rabu, 12 Februari 2014
Java OpenCSV tutorial to work with CSV files
BeanIO is an open source Java framework for marshaling and marshaling Java beans from a flat file, stream, or simple String object. It is very powerful with support for XML, CSV, delimited and fixed length stream formats, Object binding, filed validation, integration with spring-batch, etc. But there are scenarios where you need to simply read or write CSV data, OpenCSV framework is quite useful. Here are simple step by step guide to convert Java objects to CSV data.
Step 1: Define in the maven pom.xml file to bring in the OpenCSV jar file.
<properties>
<opencsv.version>2.3</opencsv.version>
</properties>
<dependencies>
<!-- Open CSV -->
<dependency>
<groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>${opencsv.version}</version>
</dependency>
<dependencies>
Step 2: Write the Person model class.
package com.mycompany.app2;
public class Person
{
private String firstName;
private String surname;
private int age;
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getSurname()
{
return surname;
}
public void setSurname(String surname)
{
this.surname = surname;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
}
Step 3: Write the interface.
package com.mycompany.app2;
import java.util.List;
public interface SimpleWriter
{
abstract String writeCSV(Listpersons);
}
Step 4: Write the implementation using the above interface.
package com.mycompany.app2;
import au.com.bytecode.opencsv.CSVWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SimpleWriterImpl implements SimpleWriter
{
private static final char DELIMITER = ,;
public String writeCSV(List<Person> persons)
{
StringWriter writer = new StringWriter();
CSVWriter csvWriter = null;
try
{
csvWriter = new CSVWriter(writer, DELIMITER, CSVWriter.DEFAULT_QUOTE_CHARACTER,
CSVWriter.NO_ESCAPE_CHARACTER, "
");
List<String[]> records = new ArrayList<String[]>(10);
for (Person person : persons)
{
List<String> record = Arrays.asList(String.valueOf(person.getFirstName()),
String.valueOf(person.getSurname()),
String.valueOf(person.getAge()));
String[] recordArray = new String[record.size()];
record.toArray(recordArray);
records.add(recordArray);
}
csvWriter.writeAll(records);
}
catch (Exception e)
{
e.printStackTrace();
}
return writer.toString();
}
}
If you want to write to a file, you can use a FileWriter instead of the StringWriter.
Step 5: Write a test class to test it.In practice, a unit test class must be written.
package com.mycompany.app2;
import java.util.ArrayList;
import java.util.List;
public class SimpleWriterTest
{
public static void main(String[] args)
{
Person p1 = new Person();
p1.setFirstName("John");
p1.setSurname("Smith");
p1.setAge(12);
Listpersons = new ArrayList (5);
persons.add(p1);
SimpleWriter sw = new SimpleWriterImpl();
String csvOutPut = sw.writeCSV(persons);
System.out.println(csvOutPut);
}
}
Step 6: The output is
"John","Smith","12"
Diposting oleh
pebel
di
20.45
0
komentar
Kirimkan Ini lewat Email
BlogThis!
Bagikan ke X
Berbagi ke Facebook
Kamis, 06 Februari 2014
JUnit 4 Tutorial Test Exception thrown by Java Method with Example
One part of unit testing a Java method is checking exception thrown by that method. A Java unit test should verify correct exception thrown in exceptional case and no exception should be thrown in normal case. In JUnit 3.XX, there was no direct support to pass or fail a test based upon exception thrown by a Java method. JUnit4 address this issue and provides an easy, and readable way to test exception thrown by a Java method. There are many situations when you need to test exception thrown by any method in Java. Classical example of this is testing API methods which should throw IllegalArgumentException if arguments passed to method are not matching to pre-conditions. In order to test exception thrown by any method in JUnit 4 you need to use @Test(expected=IllegalArgumentException.class)annotation. You can replace IllegalArgumentException.class with any other exception e.g. NullPointerException.class or ArithmeticException.class etc. Bottom line is that JUnit 4 will execute that test and check if method actually throws expected exception or not. If method throws expected exception, specified as "expected", than JUnit 4 will pass that test, but if method throws any other exception, or doesn't throw any exception than JUnit4 will fail that particular test.
Diposting oleh
pebel
di
04.30
0
komentar
Kirimkan Ini lewat Email
BlogThis!
Bagikan ke X
Berbagi ke Facebook
Selasa, 04 Februari 2014
Java Tutorial Setting up Java Maven and eclipse
This is mainly for the beginners of Java to get familiarized with Java, Maven, and eclipse. This will also be handy for starting on your self-taught Java projects.
Install and configure Java
Step 1: Download and install Java 6 or later version if available by googling "Java downloads". Make sure that you download and install the right version for the operating system on which you will be running -- for example Windows (32 bit or 64 bit), Linux, Solaris, MAC, etc. You will need both the JDK and the JRE.
The javac is the compiler that converts a source file (e.g. HelloWorld.java) to a byte code file (e.g. HelloWorld.class). The java is the run-time command to execute a program (i.e. java HelloWorld). The src.zip is where all the library files are located and rt.jar is where the run-time class files are located.
Step 2: Set the environment variables. In a command prompt, if you type "set" (in WIN 32) and "env" (in Unix), it will show all the environment variables. You need to set the JAVA_HOME environment variable. In DOS it is %JAVA_HOME% and in a Unix system, it is $JAVA_HOME. You also need to add %JAVA_HOME%/bin to the "path" environment variable. you can verify if Java is set up correctly by typing the following command in a command prompt.
If the version is not displayed, then Java is not set up correctly.
Install and configure Maven
Maven is a build and deployment tool.
Step 1: Download and install Maven from http://maven.apache.org/download.html.
Step 2: Configure the environment variables "M2_HOME" and "path". Use M2_HOME instead of M3_HOME as eclipse might not work well with M3_HOME. For example
SET USERPROFILE=%TOOLS_HOME%homeOnce maven has been set up correctly, you should be able to verify it by
SET JAVA_HOME=%TOOLS_HOME%javajdk-1.6.0_25
SET M2_HOME=%TOOLS_HOME%mavenapache-maven-3.0.3
SET MAVEN_OPTS=-Xmx512m -XX:MaxPermSize=256m -Duser.home=%USERPROFILE%
You can set up the repository location by opening the settings.xml file under conf folder inside your maven installation directory. Repository is where the dependency Java libraries will be stored.
<localRepository>c: oolshome.m2 epository</localRepository>
If your internet access requires proxy settings, you need have that added to your settings.xml file.
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username>proxyuser</username>
<password>proxypass</password>
<host>webproxy</host>
<port>8080</port>
<nonProxyHosts>local.net,some.host.com</nonProxyHosts>
</proxy>
Install and configure eclipse.
Step 1: Download and install eclipse latest version from http://www.eclipse.org/downloads/. It is an IDE (i.e. Integrated Development Environment). Get the EE (Enterprise Edition).
Step 2: It is a good practice to keep your eclipse work space separate from where your tutorials or projects are stored. This will not tie up your projects or tutorials with an IDE. What if you want to use your projects or tutorials with NetBeans? For example
Here is a simple step by step guide in setting up Maven and eclipse
Step 1: The settings.xml file under %M2_HOME%/conf is where you can set up your local repository location, central repository server from where you can download the relevant artifacts, proxy server settings to access internet, etc as shown below.
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>c: empjava.m2 epository</localRepository>
<proxies>
<proxy>
<id>genproxy</id>
<active>true</active>
<protocol>http</protocol>
<username>username</username>
<password>passwd</password>
<host>proxy-server</host>
<port>8080</port>
<nonProxyHosts>localhost</nonProxyHosts>
</proxy>
</proxies>
</settings>
You can browse the repository by going to http://search.maven.org where you can search for artifacts and relevant version numbers. You can even manually download artifacts.
Need to add the following snippets to the root element of your settings.xml file to tell where to download the jar files from.
<profiles>
<profile>
<id>JDK</id>
<activation>
<property>
<name>JDK</name>
</property>
</activation>
<properties>
<JDK_1_5>c: oolsjavajdk-1.5.0_06</JDK_1_5>
<JDK_1_6>c: oolsjavajdk-1.6.0_11</JDK_1_6>
</properties>
</profile>
<profile>
<id>nexus</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<!--Enable snapshots for the built in central repo to direct -->
<!--all requests to nexus via the mirror -->
<repositories>
<repository>
<id>central</id>
<url>http://search.maven.org/</url>
<releases><enabled>true</enabled></releases>
<snapshots><enabled>true</enabled></snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>central</id>
<url>http://search.maven.org/</url>
<releases><enabled>true</enabled></releases>
<snapshots><enabled>false</enabled></snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
Note: Drill down by groupid that specify in your pom.xml file under dependencies.
Step 2: Generate the pom structure with the following maven command.
C:TempJavaprojects>mvn archetype:generate -DgroupId=com.mytutorial -DartifactId=simpleNote: Make sure that you already dont have a folder "simple" under projects. Accept the default settings when prompted by pressing enter. Now, if you inspect the file structure, it will look like.
Carefully, inspect the folders and files that maven has created. The local repository will also have a number of jar files for project dependencies like junit.jar and maven plugin jars.
This maven project can be imported into eclipse.
Step 3: create an eclipse short cut as shown below to open eclipse with your workspace "my-tutorials"
C:Toolseclipseeclipse-3.7-SR2-win32-x86_64eclipse.exe -data C:TempJavaworkspacemy-tutorials
Step 4: Close the welcome splash screen, and tell eclipse with the help of the m2e (i.e maven to eclipse) plugin where your maven settings.xml file is residing. This is done by selecting from the eclipse main menu Window --> Preferences --> Maven (note: you can also search at the top in the Preferences dialogue). As you can see below, it will also display your repository location as highlighted in blue.
Now, you can refresh your projects or select the project "simple" and then right-mouse-click to bring up the contextual menu, and then select "Maven --> Update Dependencies" to see the packages your project depends on. In this example, it is junit-xxx.jar.
You can also check you build path by right-mouse-clicking on the simple project and then selecting Build Path --> Configure Build Path
Step 5: Import the maven project you had just created. Select File --> Import and then
Click Next,
Step 6: Now, you can see the "App.java" Java source file as shown below. This was created by Maven.
Also inspect the pom.xml file which is used for packaging up your artifacts. The junit.jar is required for writing unit tests. You can also notice AppTest.java under src/test/java
Step 7: You can run the class by "right-clicking" on App.java to bring up the contextual menu and then selecting "Run As" and then "Java Application", which prints the output "Hello World" in the console tab window.
Step 8: You can now package it as a jar file by running the mvn command on a command prompt. The pom file says the packaging type is "jar". Currently the target folder is empty, and once you package it, it will have the packaged artifacts.
Firstly, locate the folder where the pom.xml file is and then execute the mvn command.
The command is "mvn clean package". if you refresh the "target" folder by selecting it and pressing F5 or by selecting it and then right-mouse-clicking and then selecting "Refresh" you will see the artifacts that are generated. If you dont want the junit tests to be run, you can add -Dmaven.test.skip to the above command.
If you want the package to be deployed to your maven repository which is located at "c: empjava.m2 epository" you should run the command "mvn clean install".
Step 9: Finally, you can run the jar file from a command prompt.The classpath tells where to find the App.class file.
java -classpath C:TempJava.m2 epositorycommytutorialsimple1.0-SNAPSHOTsimple-1.0-SNAPSHOT.jar com.mytutorial.App
Thats it. You now have Java, Maven (build tool), and eclipse (IDE) working with each other. If you liked this give me your feedback and stay tuned for more tutorials.
Note: If you want to generate the eclipse related artifacts outside eclipse from a command-line, you can issue the following command mvn eclipse:clean eclipse:eclipse. Similar commands are available for other IDEs as well.
You may also like
- Build tools (Maven and Ant) interview questions and answers
- Maven interview questions and answers - inheritance vs aggregation
- Java Tutorial: Setting up Java, Maven, and eclipse
Diposting oleh
pebel
di
22.00
0
komentar
Kirimkan Ini lewat Email
BlogThis!
Bagikan ke X
Berbagi ke Facebook
Senin, 03 Februari 2014
How to Create and Evaluate XPath Expression in Java Tutorial and Example
You can use XPathExpression from javax.xml.xpath package to create and execute XPATH expression in Java. Java API provides javax.xml.xpath package, which contains classes like Xpath, XpathFactory to work with XPATH and XML documents. By the way this is third article on Xpath, In last couple of tutorials e.g. XPATH examples to select values using attributes and my XPATH notes for Java programmer, we have seen basics of Xpath expression from XML and Java point of view. Anyone who has work with XML technologies in Java knows importance of XPATH, it is one the most useful technology to retrieve selected data from XML files. XPATH is like SQL which is used to retrieve data from relational database. Many back-office and middle-office Java application which transfers data in form of XML documents makes extensive use of XPATH expression to retrieve value for printing or for decision making. Though there are lot of open source XML libraries are available to assist with Java and XML development e.g. XML Beans. I personally prefer to use standard Java API if functionality is available there. In this Java tutorial we will learn how to create XPath expression in Java program and retrieving values from XPATH e.g. text, numbers and boolean values, which is critical for programming flow.
Diposting oleh
pebel
di
09.15
0
komentar
Kirimkan Ini lewat Email
BlogThis!
Bagikan ke X
Berbagi ke Facebook
Minggu, 02 Februari 2014
CSS Selectors Tutorial with FireBug
This tutorial extends the JavaScript tutorial with FireBug. The purpose of this tutorial is to debug CSS selectors in FireBug. CSS selectors are used in selecting your DOM element for debugging and for writing automated tests to verify the displayed DOM elements.
Step 1: Here is a basic HTML document (cssselectortest.html) to apply the CSS selectors.
Step 2: Open Firefox browser and type the URL to the above HTML (i.e. cssselectortest.html) file. Make sure that you have the FireBug add on installed. If not, download it and drag and drop on to the Firefox.
On the RHS bottom console, you have CSS selector as shown below.
The above CSS selector, selects the last h2 tag with class "myClass" under a DIV tag with id "myApp". You can experiment with other CSS selectors and see what is selected on LHS window, and once you highlight the selection on the bottom LHS window, you can see the HTML page highlighted as shown below.
You can try the following selectors to see what is highlighted.
For the following HTML
Try the following selectors
Read More..
Step 1: Here is a basic HTML document (cssselectortest.html) to apply the CSS selectors.
<html lang="en" >
<head>
<title>test app</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js?ver=1.9.1"></script>
</head>
<body>
<div id="myApp">
<h2 class="myClass">CSS selector test</h2>
<h2 class="myClass">CSS selector test2</h2>
<h2 class="myClass">CSS selector test3</h2>
</div>
</body>
Step 2: Open Firefox browser and type the URL to the above HTML (i.e. cssselectortest.html) file. Make sure that you have the FireBug add on installed. If not, download it and drag and drop on to the Firefox.
On the RHS bottom console, you have CSS selector as shown below.
console.clear();
console.log( jQuery(div#myApp h2.myClass:eq(-1)) );
The above CSS selector, selects the last h2 tag with class "myClass" under a DIV tag with id "myApp". You can experiment with other CSS selectors and see what is selected on LHS window, and once you highlight the selection on the bottom LHS window, you can see the HTML page highlighted as shown below.
You can try the following selectors to see what is highlighted.
console.log( jQuery(div#myApp h2.myClass:eq(0)) );//First h2
console.log( jQuery(div#myApp h2.myClass:eq(1)) );//2nd h2
console.log( jQuery(div#myApp h2.myClass:eq(2)) );//Third h2
For the following HTML
<html lang="en" >
<head>
<title>test app</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js?ver=1.9.1"></script>
</head>
<body>
<div id="myApp">
<h2 class="myClass">CSS selector test</h2>
<h2 class="myClass">CSS selector test2</h2>
<h2 class="myClass">CSS selector test3</h2>
</div>
<h2>Test +</h2>
</body>
Try the following selectors
console.clear();//clear the console
console.log( jQuery(div#myApp h2));//All h2 elements inside the div element with id "myApp"
console.log( jQuery(div#myApp>h2));//All h2 elements where the parent is a div with id "myApp"
console.log( jQuery(div#myApp, h2));//All div elements with id "myApp" and h2 elements
console.log( jQuery(div#myApp+h2));//All h2 elements that are immediately followed by div element with id "myApp"
Diposting oleh
pebel
di
05.30
0
komentar
Kirimkan Ini lewat Email
BlogThis!
Bagikan ke X
Berbagi ke Facebook
















