Google

Mar 25, 2014

Top 10 Eclipse short-cut keys every Java developer using eclipse IDE must know -- part 2

Top 10 Eclipse short-cut keys every Java developer using eclipse IDE must know - part1 covered the frequently used CTRL+ key. This will cover CTRL+SHIFT+key. If you can remember only 1 short-cut key, this post will show you which one to remember.

8. CTRL+g and CTRL+SHIFT+g

Often you need to find where a particular type or method is referenced so that you can analyze the impact of changing the referenced class or method. You also often need to find where a particular type or method is declared. Impact analysis vital in enhancing existing code base.

CTRL+G is to find declarations in workspace



Ctrl+Shift+G is to find references in workspace



9. CTRL+SHIFT+t and CTRL+SHIFT+r

Often you need to search for Java types like classes and interfaces or Java resources like spring context XML file, properties files, sql files, data files, etc. CTRL+SHIFT+t and CTRL+SHIFT+r allow you to search for types and resources respectively with wild card character like * and ?. If you do CTRL+SHIFT+r it gives you options at the bottom as to which editor you want to use to open the selected resource. You can also use these two short cuts contextually by highlighting type (E.g. class name like EclipseShortCutKeys) and then pressing the shortcut keys.

CTRL+SHIFT+t



CTRL+SHIFT+r



10. ALT+SHIFT+R

Refactoring code is a key aspect of writing quality code. For example, you might name a variable "currentTimeMillis" and use it in a number of places. But, later on decide that a better variable name would be "startCurrentTimeMillis". If you change at one spot, you want it to be propagated to all occurences of "currentTimeMillis". This works for changing method and class names as well. If you change a name of a declared method, you want all the classes that refrencing this method to change its values in the method invocations. This is achived by highligting a class, method, or a variable, and then pressing CTRL+SHIFT+R, and then change the name at the highlighted spot, and it will propagated to other locations and resources where it is used.



Do I have to remember these 10 eclipse shortcut keys? 

With practice and experience, you will remember these frequently used shortcut keys. Until then, if you have to just remember 1 shortcut key, then it is CTRL+SHIFT+L, which lists all the short-cut keys in a popup.

If you press CTRL+SHIFT+L once



If you press CTRL+SHIFT+L twice



Labels: ,

Mar 12, 2014

Top 10 Eclipse short-cut keys every Java developer using eclipse IDE must know

1. CTRL+1

Probably the most useful one. It activates the quick fix and generates lots of code for you. This means less typing.

Generating local variables: For example, if you have written a method call and you highlight it and press Ctrl+1, Eclipse will give you options to extract to local variable, assign to new local variable or assign to new field.



If you've modified a method in a abstract superclass or interface and you highlight the subclass’ name and hit Ctrl+1, you’ll get options to add unimplemented methods or make the subclass abstract.



Suppose you’ve misspelled “currentTimeMillis”, you can highlight it, press Ctrl+1 and you’ll get an option to correct the spelling.



So, Ctrl+1 is a quick fix that does the thinking for you.

2. CTRL+space

This is a type assist tool. Handy for you to search for handy utility class like DateTimeUtils from the Joda library. There are myriad of libraries used in commercial Java projects, and very handy to pick a class.



Handy to pick your own classes as well if you don't remember the exact name for your model class, but knew that it starts with "Custom".


3. CTRL+o

You have an existing class with 15+ methods defined and want to get to a method quickly, then use CTRL+o.




4. CTRL+l

Say you get a stack trace in your eclipse console or in the log file as shown below, and you want to go directly to the line in your class that caused the exception, then use CTRL+l to go to the exact line number.


1394596218303
Exception in thread "main" java.lang.NumberFormatException: null
 at java.lang.Long.parseLong(Long.java:404)
 at java.lang.Long.(Long.java:702)
 at com.writtentest11.EclipseShortCutKeys.main(EclipseShortCutKeys.java:10)

In the above code, the class is "EclipseShortCutKeys" and line number is 10.


So, use CTRL+SHIFT+T to select the class EclipseShortCutKeys by typing the first few characters to filter, and then once this class is selected use CTRL+l and type 10 to go to the exact line.



5. CTRL+7 or CTRL+/

You may now want to comment out the line causing the java.lang.NumberFormatException. You comment and uncomment with the toggle control keys either CTRL+7 or CTRL+/. Highlight the number of lines you want to comment or uncomment, and then press CTRL+/.





6. CTRL+mouse click


The CTRL short-cuts will not be complete without the most powerful navigation CTRL + mouse click. This brings up the contextual menu to navigate to other classes or interface.  Press the CTRL key first, and then hover over the method -- for example currentTimeMillis( ) on the Joda library class DateTimeUtils, util you get a contextual menu that takes you over to the actual implementation or interface.




In commercial projects, you need to navigate from service layer classes to DAO layer classes, helper classes, domain models, etc. Many different layers will collaborate with each other to implement the business use case. So, you need to rapidly move across different layer classes.


7. CTRL+h

This is a generic search pop up. You can do Java search, File search, etc. Either high-light the type, method, or variable  and then press CTRL+h or without highlighting to fill in the search criteria yourself. Very handy to search your selection, workspace, or working sets.





So far looked at very useful CTRL+. In the next post, will cover CTRL+SHIFT+. Top 10 Eclipse Short Cut Keys - Part 2. You will see in this Part 2, the only key that you must remember.

Labels: ,

Sep 25, 2012

Java tutorial: Create a simple Web app using JEE

Install Apache Tomcat application server

To run JEE based web apps, you need an  application server that contains a web container. There are a number of application servers like Apache Tomcat, JBoss, GlassFish, etc. This tutorial will use Apache Tomcat.

Step 1: Download and install Apache Tomcat from http://tomcat.apache.org/download-70.cgi. The installing is all about unzipping it to the right folder. If you are running on Windows 7, download the 64-bit windows zip.




Continue with creating a Web project.

Step 2: Generate a Web project structure using Maven as we did for simple Java project in the previous tutorial. Run the command under C:\Temp\Java\projects.

mvn archetype:generate -DgroupId=com.mytutorial -DartifactId=simpleWeb  -DarchetypeArtifactId=maven-archetype-webapp

This would have created  the simpleWeb and a number of other sub folders adhering to the maven convention.


As you can see, it had generated a webapp folder and the web.xml.

Step 3: Import this project into eclipse. This step is very similar to the simple Java tutorial.


Also, note that in the top right hand corner  the tab says that eclipse is in Java EE perspective.

Integrate Tomcat server into eclipse so that you can it within eclipse.

Step 4: From eclipse top menu select "Window --> Preferences"





Step 5: Select the path to previously installed Tomcat server.




Step 6: Add this new server to the panel marked "Server". This where the "Console" tab is also located. This will also allow you to deploy the "simpleWeb" project to the Tomcat  server.





Step 7: Deploy the simpleWeb project by selecting it from the left pane marked "Available" and adding to the right pane marked "Configured".



Step 8: Start the Tomcat server that was deployed with the simpleWeb within eclipse by right-mouse-clicking on the server and selecting "Start".




Step 9: The console tab will output the server logs.



Step 10: Once the server has started, you type the following URL in a browser of your choice. Now you have a very simple Web application running in Tomcat server.

http://localhost:8080/simpleWeb/index.jsp



Now, let's see how we can build the war  package and deploy it to Tomcat from outside eclipse.

Step 11: Firstly, use Maven to build the war package. These steps are very similar to simple Java tutorial, except for deploying the Web ARchive (i.e. the war file) to Tomcat, and starting Tomcat outside eclipse. If your Tomcat is already running within eclipse stop it by selecting the server and then right-mouse-clicking to bring up the context menu, and then selecting the "Stop" button. You can check the "console" tab to see if the server has stopped.


Step 12: Now, use the "mvn" command to build the war file after changing the directory to "simpleWeb"  in a command line.  You need to be in the "simpleWeb" folder because that is where the pom.xml file is.


c:\Temp\Java\projects\simpleWeb>mvn clean install

Step 13: You can see the generate war file deployed to your local maven repository.



Step 14: To deploy the simpleWeb-1.0-SNAPSHOT.war file to Tomcat, copy it to the Tomcat's "webapps" folder, and then you can start the server by double clicking on "startup.bat", which will deploy the application when the server starts up. It simply unzips the simpleWeb-1.0-SNAPSHOT.war file by creating a new folder "simpleWeb-1.0-SNAPSHOT", which will have all the required files.





Step 15: Once the server is started, you can access the application in browser of your choice with the following URL.

http://localhost:8080/simpleWeb-1.0-SNAPSHOT/index.jsp


As you can notice, "simpleWeb-1.0-SNAPSHOT" is the exploded folder under the "webapps" folder within Tomcat file structure.

You may also like

Labels: , ,

Sep 21, 2012

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%home
SET JAVA_HOME=%TOOLS_HOME%java\jdk-1.6.0_25

SET M2_HOME=%TOOLS_HOME%maven\apache-maven-3.0.3

SET MAVEN_OPTS=-Xmx512m -XX:MaxPermSize=256m -Duser.home=%USERPROFILE%

Once maven has been set up correctly, you should be able to verify it by


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:\tools\home\.m2\repository</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:\temp\java\.m2\repository</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:\tools\java\jdk-1.5.0_06</JDK_1_5>
        <JDK_1_6>c:\tools\java\jdk-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:\Temp\Java\projects>mvn archetype:generate -DgroupId=com.mytutorial -DartifactId=simple

Note: Make sure that you already don't 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:\Tools\eclipse\eclipse-3.7-SR2-win32-x86_64\eclipse.exe -data  C:\Temp\Java\workspace\my-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 don't 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:\temp\java\.m2\repository" 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:\Temp\Java\.m2\repository\com\mytutorial\simple\1.0-SNAPSHOT\simple-1.0-SNAPSHOT.jar com.mytutorial.App 


That's 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


Labels: , ,

May 31, 2012

Top 5 Eclipse debugging tips tutorial style

Good debugging skills can not only make you more productive, but also can be used in job interviews to determine your experience. The remote debugging was already discussed using eclipse, which is very handy if you have a scenario where you can't reproduce locally what your client is experiencing. In this case, you can set up the remote debugger using eclipse. In this blog I will go through some handy debugging options using eclipse IDE. Similar, options are available in other popular IDEs as well.


Q1. How will you go about getting the debugger to stop on NullPointerException, which is thrown on line E in the code  below?


import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MyClassWithACollection {
 
 //map instance variable
 private Map<integer, Country> fromMap = 
          new ConcurrentHashMap<integer, Country>(10);
 //class variable 
 private static Map<integer, Country> toMap = 
           new ConcurrentHashMap<integer, Country>(10);
 

 public static void main(String[] args) {
  MyClassWithACollection mcc = new MyClassWithACollection(); //Line X
  mcc.fromMap.put(1, new Country("India"));                  //Line Y 
  mcc.fromMap.put(2, new Country("UK"));
  mcc.fromMap.put(3, new Country("USA"));
  System.out.println(mcc.fromMap);          //Line A
  
  //copy from fromMap to toMap
  mcc.toMap.putAll(mcc.fromMap);            //Line B
  System.out.println(mcc.toMap);            //Line C
  
  mcc.fromMap = null;                       //Line D 
  //throws a null pointer exception
  System.out.println(mcc.fromMap.values()); //Line E
 
 }
 
 //inner class
 public static class Country {
  String name;
  
  public Country(String name){
     this.name = name;
  }
 }

}
 
A1. You can get the debugger to stop at a particular exception as ashown below.

1. go to the debug window
2. click on j! icon that brings up the modal panel to search and select the exception to set the break point on



3. Select the exception type.
4. Click okay.
5. Select the "MyClassWithACollection" file and right click to get the contextual menu and and then select Debug As --> Java Application as shown below, which will stop the debugger on Line E, where the NullPointerException will be thrown as mcc.fromMap was set to null on Line D.


 Note: For all the Q&A below, you need to use the above Debug As --> Java Application.

Q2. If you want to inspect the contents of "mcc.fromMap" on Line A, how will you go about accomplishing it?
A2. In eclipse you could follow the following steps

1. Set a break point on "Line A" by double clicking on the left hand side of the eclipse editor as shown below to set the break point.



2. When you run the program in debug mode as explained  earlier, the debugger will stop on the break point. 3. Go to the variables tab, and then make sure the "Logical Structure" icon shown in the diagram below is turned on by clicking it as shown below.



4. When the logical structure is turned on, you can easily drill into the "mcc.fromMap" as shown above to inspect the values. This approach can be used for all collection types.

Q3. How will you inspect the contents of the static variable "mcc" on Line X oand contents of the static variable "mcc.toMap" on Line C?
A3. To inspect a local variable "mcc" on Line X

1. Put the break point on Line Y.
2. When it stops on Line Y, highlight mcc on Line X, and then right click to get the contextual menu as shown below.



3. You could then select "Inspect" to get a pop up that inspects the variable as shown below.



4. Alternatively, you could select watch from the contextual menu which will display the local and static variables. You could even add expressions to stop when a variable has a particular value like null.



You can even edit the watch with expressions as shown below.




5. As you step through one line at a time, you can see the watch values changing.

Q4. Since Line B is a method from the Java API, how will you get eclipse to not step into the break point on Line B even if you press F5 (step into), and go to the next break point?

A4. You can achieve this via setting up the "Step Filters" in eclipse preferences.

1. Go to Window --> Preferences and you will get a modal popup window.
2. Follow the rest of the steps as shown below.



3. If you try debugging now, the debugger will stop at Line B, but if you press step into or F5, the code will not step into the putAll method, and step over to the next break point instead.

The best way to learn is by trying the above code.

Related posts: 

Labels: