Sunday, March 30, 2014

Effective Java Debugging with Eclipse

http://eclipsesource.com/blogs/2013/01/08/effective-java-debugging-with-eclipse/

 

 

Learning to write code efficiently is only one step towards becoming a coding master. Another step is learning to debug. When it comes to legacy or 3rd party code you will need to debug in order to understand how the code behaves. In this post I will give you some basic tips on how to master your debugger and become more efficient.
This is a follow up to My Top 10 Tips on how to be more productive with the Eclipse IDE (which you should read before this one). I’ll assume you already know how to launch a Debug configuration for your project in your Workspace.
Note: Click on the images to reveal a larger screenshot.

1. Breakpoints

Basic Breakpoints
Breakpoint s Effective Java Debugging with Eclipse
This is essential and you probably already know how to use it – the Breakpoint.
In case you’re not familiar with them, you create a breakpoint by double-clicking on the left side of a line of code. The execution of your application will then halt at that point so you can analyze the state and hopefully find the cause of your misbehaving code.
Exception Breakpoints
ExceptionBreakpoint s Effective Java Debugging with Eclipse
Sometimes an exception occurs, but you are not sure where (e.g. no stack trace available) or the exception is not logged and not visible. This is the right time to create a global breakpoint that pulls the hand brake if a certain exception occurs.
You’ll find this in the Breakpoints view of the Debug perspective.
Conditional Breakpoints
ConditionalBreakpoint s Effective Java Debugging with Eclipse
To speed up debugging by not stopping at a breakpoint everytime, you can add a condition. The breakpoint will only stop your application if the condition is fulfilled – and will not unnecessarily disturb your hunt for the bug.
You can get there with a right-click on your break point > Breakpoint Properties...

2. Detail Formatter

DetailFormatter s Effective Java Debugging with Eclipse
While debugging and inspecting variables/objects in your debug perspective, you might encounter textual representations of objects that are not really meaningful. Usually the .toString() method on an object is used for the debug UI. It’s not the greatest idea to implement the .toString() method just for debugging purposes. Instead you can set up a detail formatter that takes care of the textual representation of your object.
You can get there by right-clicking on the variable in the Variables view, then selecting New Detail Formatter....

3. Logic Structure

LogicStructure s Effective Java Debugging with Eclipse
Here you can see what a difference a small click can make. Both Views show the same Map object. By activating Logic Structure in your Variables view, you get the “contents” and structure of objects presented as you would expect it for a human reader.

4. Drop To Frame

DropToFrame s Effective Java Debugging with Eclipse
In case your application stopped at your break point and the interesting things had already happened, you can “Drop To Frame”. This means you can jump back in your stack and then start debugging from there…

5. Inspect and Watch

Watch s Effective Java Debugging with Eclipse
Inspect provides you basically with the same functionality as the Variables View – you can unfold and inspect the various values of the object. Watch on the other hand enables you to observe a specific Object and see how it changes over time.

6. Change Variable Values

ChangeVariable s Effective Java Debugging with Eclipse
The Variables View can do more than just display values. You can also edit values. I don’t think there is much more to say about it icon wink Effective Java Debugging with Eclipse

7. Step Into, Over and Return – Shortcuts

Try to memorize the following function keys. They will greatly speed up your debugging by avoiding constantly having to use your mouse.
  • F5 – Step Into
  • F6 – Step Over
  • F7 – Step Return
  • F8 – Run until next breakpoint is reached

8. Step Filtering

stepfilters s Effective Java Debugging with Eclipse
With “Step Filters” you can filter out types that you do not wish to see or step through while debugging. This helps you to stay focused on the actual code and does not expose you to the inner workings where you might not even have the source. Have a look at Holger’s Effective Mockito post about Step Filtering in conjunction with Mockito.
You’ll find this in: Preferences > Java > Debug > Step Filtering

9. Remote Debugging

RemoteDebug s Effective Java Debugging with Eclipse
With Remote Debugging you can debug an application running on a different machine. The debugging itself is like any other app that you usually launch from within Eclipse. This is what you need to do:
  1. Make sure the source code on your machine and the application on the other machine are in sync.
  2. Start the application on the other machine with the following command line parameters:
    java -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005
    suspend=y/n declares whether the JVM of the application you want to debug will wait for Eclipse to connect or if it will start right away.
    address=5005 configures the TCP port to use for remote debugging.
  3. Create a Remote Java Application Debug Launch Configuration.
  4. Specify the Host and Port for your remote application.
  5. Add all the source projects of the application you want to debug to the Source tab.

10. Heap dump + Memory Analyzer

Sometimes you need a bigger picture of the inner workings of your application than you can get with line-by-line debugging – especially for finding memory leaks. In this case you are better off with the Eclipse Memory Analyzer (MAT). My colleague Ian wrote a blog post about how to create a heap dump and analyze it.
Update 21.01.2013: Ian just published an other more detailed article about the Eclipse Memory Analyzer: "10 Tips for using the Eclipse Memory Analyzer"

 

Friday, June 14, 2013

JDBC Realm and Form Based Authentication with GlassFish and Primefaces

Prepare the Database

Fire up NetBeans and switch to the Services tab. Right click the "Databases" node and select "Register MySQL Server". Fill in the details of your installation and click "ok". Right click the new MySQL node and select "connect". Now you see all the already available databases. Right click again and select "Create Database". Enter "jdbcrealm" as the new database name. Remark: We're not going to do all that with a separate database user. This is something that is highly recommended but I am using the root user in this examle. If you have a user you can also grant full access to it here. Click "ok". You get automatically connected to the newly created database. Expand the bold node and right click on "Tables". Select "Execute Command" or enter the table details via the wizard.

CREATE TABLE USERS (
  `USERID` VARCHAR(255) NOT NULL,
  `PASSWORD` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`USERID`)
);

CREATE TABLE USERS_GROUPS (
  `GROUPID` VARCHAR(20) NOT NULL,
  `USERID` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`GROUPID`)
);








Basic Project Setup
Start a new maven based web application project. Choose "New Project" > "Maven" > Web Application and hit next. Now enter a name (e.g. secureapp) and all the needed maven cordinates and hit next. Choose your configured GlassFish 3+ Server. Select Java EE 6 Web as your EE version and hit "Finish". Now we need to add some more configuration to our GlassFish domain.Right click on the newly created project and select "New > Other > GlassFish > JDBC Connection Pool". Enter a name for the new connection pool (e.g. SecurityConnectionPool) and underneath the checkbox "Extract from Existing Connection:" select your registered MySQL connection. Click next. review the connection pool properties and click finish. The newly created Server Resources folder now shows your sun-resources.xml file. Follow the steps and create a "New > Other > GlassFish > JDBC Resource" pointing the the created SecurityConnectionPool (e.g. jdbc/securityDatasource).You will find the configured things under "Other Sources / setup" in a file called glassfish-resources.xml. It gets deployed to your server together with your application. So you don't have to care about configuring everything with the GlassFish admin console.Additionally we still need Primefaces. Right click on your project, select "Properties" change to "Frameworks" category and add "JavaServer Faces". Switch to the Components tab and select "PrimeFaces". Finish by clicking "OK". You can validate if that worked by opening the pom.xml and checking for the Primefaces dependency. 3.4 should be there. Feel free to change the version to latest 3.4.2.

Final GlassFish Configuration
Now it is time to fire up GlassFish and do the realm configuration. In NetBeans switch to the "Services" tab again and right click on the "GlassFish 3+" node. Select "Start" and watch the Output window for a successful start. Right click again and select "View Domain Admin Console", which should open your default browser pointing you to http://localhost:4848/. Select "Configurations > server-config > Security > Realms" and click "New..." on top of the table. Enter a name (e.g. JDBCRealm) and select the com.sun.enterprise.security.auth.realm.jdbc.JDBCRealm from the drop down. Fill in the following values into the textfields:

JAASjdbcRealm
JNDIjdbc/securityDatasource
User Tableusers
User Name Columnusername
Password Columnpassword
Group Tablegroups
Group Name Columngroupname
Leave all the other defaults/blanks and select "OK" in the upper right corner. You are presented with a fancy JavaScript warning window which tells you to _not_ leave the Digest Algorithm Field empty. I field a bug about it. It defaults to SHA-256. Which is different to GlassFish versions prior to 3.1 which used MD5 here. The older version of this tutorial didn't use a digest algorithm at all ("none"). This was meant to make things easier but isn't considered good practice at all. So, let's stick to SHA-256 even for development, please.

Secure your application
Done with configuring your environment. Now we have to actually secure the application. First part is to think about the resources to protect. Jump to your Web Pages folder and create two more folders. One named "admin" and another called "users". The idea behind this is, to have two separate folders which could be accessed by users belonging to the appropriate groups. Now we have to create some pages. Open the Web Pages/index.xhtml and replace everything between the h:body tags with the following:



 <h:body>
        Select where you want to go:
         
 
        <h:link outcome="admin/index" value="To the admin section" />
 
        <h:link outcome="users/index" value="To the user section" />
    </h:body>
 
 
 
 
Now add a new index.xhtml to both users and admin folders. Make them do something like this:
 
<h:body>
        <h1>Hello Admin|User</h1>
         
 
        <h:link outcome="/index" value="Back to Homepage" />
    </h:body>
 
 
 
On to the login.xhtml. Create it with the following content in the root of your Web Pages folder.
 
 
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      xmlns:p="http://primefaces.org/ui"
      xmlns:h="http://java.sun.com/jsf/html">
    <h:head>
        <title>Login Form</title>
    </h:head>
    <h:body>
        <p:panel header="Login From">
            <form method="POST" action="j_security_check">
                Username: <input type="text" name="j_username" />
                Password: <input type="password" name="j_password" />
                 
 
                <input type="submit" value="Login" />
                <input type="reset" value="Reset" />
            </form>
        </p:panel>
    </h:body>
</html>
 
As you can see, whe have the basic Primefaces p:panel component which has a simple html form which
points to the predefined action j_security_check. This is, where all the magic is happening. You also have to include two input fields for username and password with the predefined names j_username and j_password. Now we are going to create the loginerror.xhtml which is displayed, if the user did not enter the right credentials. (use the same DOCTYPE and header as seen in the above example).
 
 
 
 
<h:body>
        <p:panel header="Login Error">
            Sorry, you made an Error. Please try again: <a href="#{facesContext.externalContext.requestContextPath}/" >Login</a>
        </p:panel>
    </h:body>
 
 
 
 
 
The only magic here is the href link of the Login anchor. We need to get the correct request context and this could be done by accessing the faces context. If a user without the appropriate rights tries to access a folder he is presented a 403 access denied error page. If you like to customize it, you need to add it and add the following lines to your web.xml:
 
 
<error-page>
<error-code>403</error-code>
<location>/faces/403.xhtml</location>
</error-page>
 
 
 
That snipped defines, that all requests that are not authorized should go to the 403 page. If you have the web.xml open already, let's start securing your application. We need to add a security constraint for any protected resource. Security Constraints are least understood by web developers, even though they are critical for the security of Java EE Web applications. Specifying a combination of URL patterns, HTTP methods, roles and transport constraints can be daunting to a programmer or administrator. It is important to realize that any combination that was intended to be secure but was not specified via security constraints, will mean that the web container will allow those requests. Security Constraints consist of Web Resource Collections (URL patterns, HTTP methods), Authorization Constraint (role names) and User Data Constraints (whether the web request needs to be received over a protected transport such as TLS).
 
 
<security-constraint>
        <display-name>Admin Pages</display-name>
        <web-resource-collection>
            <web-resource-name>Protected Admin Area</web-resource-name>
            <description></description>
            <url-pattern>/faces/admin/*</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
            <http-method>HEAD</http-method>
            <http-method>PUT</http-method>
            <http-method>OPTIONS</http-method>
            <http-method>TRACE</http-method>
            <http-method>DELETE</http-method>
        </web-resource-collection>
        <auth-constraint>
            <description/>
            <role-name>admin</role-name>
        </auth-constraint>
        <user-data-constraint>
            <transport-guarantee>NONE</transport-guarantee>
        </user-data-constraint>
    </security-constraint>
    <security-constraint>
        <display-name>All Access</display-name>
        <web-resource-collection>
            <web-resource-name>None Protected User Area</web-resource-name>
            <description/>
            <url-pattern>/faces/users/*</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
            <http-method>HEAD</http-method>
            <http-method>PUT</http-method>
            <http-method>OPTIONS</http-method>
            <http-method>TRACE</http-method>
            <http-method>DELETE</http-method>
        </web-resource-collection>
        <user-data-constraint>
            <transport-guarantee>NONE</transport-guarantee>
        </user-data-constraint>
    </security-constraint>
 
 
 
If the constraints are in place you have to define, how the container should challenge the user. A web container can authenticate a web client/user using either HTTP BASIC, HTTP DIGEST, HTTPS CLIENT or FORM based authentication schemes. In this case we are using FORM based authentication and define the JDBCRealm
 
 
<login-config>
        <auth-method>FORM</auth-method>
        <realm-name>JDBCRealm</realm-name>
        <form-login-config>
            <form-login-page>/faces/login.xhtml</form-login-page>
            <form-error-page>/faces/loginerror.xhtml</form-error-page>
        </form-login-config>
    </login-config>
 
 
 
The realm name has to be the name that you assigned the security realm before. Close the web.xml and open the sun-web.xml to do a mapping from the application role-names to the actual groups that are in the database. This abstraction feels weird, but it has some reasons. It was introduced to have the option of mapping application roles to different group names in enterprises. I have never seen this used extensively but the feature is there and you have to configure it. Other appservers do make the assumption that if no mapping is present, role names and group names do match. GlassFish doesn't think so. Therefore you have to put the following into the glassfish-web.xml. You can create it via a right click on your project's WEB-INF folder, selecting "New > Other > GlassFish > GlassFish Descriptor"
 
 
<security-role-mapping>
        <role-name>admin</role-name>
        <group-name>admin</group-name>
    </security-role-mapping>
 
 
 
 
 Adding a Test-User to the Database
And again we start by right clicking on the jdbcrealm database on the "Services" tab in NetBeans. Select "Execute Command" and insert the following:

INSERT INTO USERS VALUES ("admin", "8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918");
INSERT INTO USERS_GROUPS VALUES ("admin", "admin"); 
 
 
You can login with user: admin and password: admin and access the 
secured area. Sample code to generate the hash could look like this:
 
 
try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            String text = "admin";
            md.update(text.getBytes("UTF-8")); // Change this to "UTF-16" if needed
            byte[] digest = md.digest();
            BigInteger bigInt = new BigInteger(1, digest);
            String output = bigInt.toString(16);
 
            System.out.println(output);
 
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
            Logger.getLogger(PasswordTest.class.getName()).log(Level.SEVERE, null, ex);
 
        }
 
 
 
 
 Have fun securing your apps and keep the questions coming! In case you need it, the complete source code is on https://github.com/myfear/JDBCRealmExample
 
 
 
 
 
 
 










Thursday, June 6, 2013

Double Brace Initialization

http://www.c2.com/cgi/wiki?DoubleBraceInitialization



To pass a set to a method:
 Set<String> validCodes = new HashSet<String>();
 validCodes.add("XZ13s");
 validCodes.add("AB21/X");
 validCodes.add("YYLEX");
 validCodes.add("AR2D");
 removeProductsWithCodeIn(validCodes);
Or to initialize a set of constants:
 private static final Set<String> VALID_CODES = new HashSet<String>();
 static {
 validCodes.add("XZ13s");
 validCodes.add("AB21/X");
 validCodes.add("YYLEX");
 validCodes.add("AR2D");
 }
But... you can create and initialize a new collection as an expression by using the "double-brace" syntax: E.g.
 private static final Set<String> VALID_CODES = new HashSet<String>() {{
 add("XZ13s");
 add("AB21/X");
 add("YYLEX");
 add("AR2D");
 }};
Or:
 removeProductsWithCodeIn(new HashSet<String>() {{
 add("XZ13s");
 add("AB21/X");
 add("YYLEX");
 add("AR5E");
 }});

Thursday, January 10, 2013

UML Best Practice: 5 rules for better UML diagrams

Rule 1: Less is more

Large diagrams containing heaps of elements actually convey less information then small focussed diagrams.
When reading such a large diagram your audience will not know what to focus on, and since there’s too much on there to actually pay attention to all elements, they will quickly give up trying altogether.




 Show up with a diagram like this at your stakeholder, and you will have already lost his/her attention even before you start talking.



 The diagram above is a good indication of how much, or how little, you should put on a diagram. My rule of thumb is that you need to be able to print the diagram on a single A4 sheet while keeping things readable.


Rule 2: No Crossings

This is a fairly common and well known rule. Try to avoid any two lines in your diagram to cross each other.




Uncrossing lines in your diagram sure make it more readable and understandable, but there’s more to it then that.  If you are unable to uncross the lines on your diagram then that is a sign that
  • a) there’s too much on the diagram (see rule 1 Less is more)
    It might be that you are showing two different aspects of the model in one diagram. In that case it might be better to create two different diagrams, each focused on one aspect.
  • b) there is some kind of design flaw in your model
    For some reason well designed models don’t have the crossing lines problem. I have no idea why or what it is exactly, I just noticed that a lot of the times, when I’m unable to “uncross” all the lines in a diagram, I discover a design flaw that, when fixed results in a diagram without crossing lines.
The following diagram contains exactly the same information, but has just been ordered differently as to make sure there are no crossing lines.





Rule 3: Orthogonality

It seems like a small thing, but making the lines in a diagram go only horizontal or vertical, and having all only right angles makes a diagram look better instantly.
The diagram below is uses a direct style for its connectors. they all go directly from one element to the other with a straight line.






The mere fact that the lines have all kinds of angles makes the diagram look a lot messier, and less understandable.
Below here again the same diagram, but now with all connectors styles set to orthogonal.






Exceptions to this rule are (for me) note links and all relations with use cases. For some reason they look better with a direct style.

Rule 4: Parents Up

When drawing generalization or realization hierarchies on a diagram always make sure the parent elements are higher then the child elements so the arrows always point upwards.
This rule is pretty intuitive for most UML modelers. Only now and then I encounter diagrams that don’t follow this rule and have their hierarchies upside down.





Diagrams like this, where the generalization arrows point downwards are harder to read. For some reason it takes a greater mental effort to understand this then when the arrows all point upwards.
In case you have multiple elements all descending from the same parent, it is recommendable to show the hierarchy in a vertical tree style.





Rule 5: Tidy Up

I realize this sound like a nagging mom, but for crying out loud: Tidy Up!
If you want to convey the message that your analysis is a well thought trough construction that will solve your stakeholders problems then you better show up with a nice and clean diagram.





When tidying up think about
  • Aligning elements, either by one of their sides (e.g Top) or by their centers. The latter works best when aligning vertically
  • Make elements the same size where possible
After tidying up the diagram looks a loot better





 But it will allow you to make a better impression when trying explain the fruits of your hard labor to your stakeholders. You will need less time explaining diagrams, and you will be able to spend more time focusing on the actual content.
 

How-to Install Google AdMob 6.x into Android Apps

STEP 1: Register yourself as a user at http://admob.com . Login and create a site

admob in android app
  













admob in android app


setting site in admob


setting site in admob


setting site in admob


setting site in admob -publisher ID


STEP 2: Download the AdMob SDK currently SDK 6.1.0

make money from your android app


make money from your android app

STEP 3: Add an External JAR (library) in the project.

Copy GoogleAdMobAdsSdk-6.1.0.jar into libs

adding admob on android app


adding admob on android app

image



STEP 4: Additional details in the AndroidManifest.xml

Open your AndroidManifest.xml and add this lines to the <application> properties;

<activity android:name="com.google.ads.AdActivity"
   android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>

Next, add these  <uses-permission>

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

And the meta-data attributes;
<meta-data android:value="true" android:name="ADMOB_ALLOW_LOCATION_FOR_ADS" />

And the complete AndroidManifest.xml;
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.kerul.peribahasa"
    android:versionCode="7"
    android:versionName="1.07" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
        <activity
            android:name=".PeribahasaActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            
        </activity>
          <activity android:name="com.google.ads.AdActivity"
              android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
            
    </application>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <meta-data android:value="true" android:name="ADMOB_ALLOW_LOCATION_FOR_ADS" />
</manifest>




STEP 5: Adding the AdView widget in the screen

   1: <TableRow
   2:     android:id="@+id/tableRow2"
   3:     android:layout_width="match_parent"
   4:     android:layout_height="wrap_content" >
   5:     <com.google.ads.AdView
   6:         xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
   7:         android:id="@+id/ad"
   8:         android:layout_width="fill_parent"
   9:         android:layout_height="wrap_content"
  10:         ads:adSize="SMART_BANNER"
  11:         ads:adUnitId="738a44d913034b9f"
  12:         />    
  13: </TableRow>


STEP 6: Adding the adView in the source code.

   1: public class PeribahasaActivity extends Activity implements OnClickListener{
   2:     protected EditText txtsearch;
   3:     protected Button btnocr, btnkamus, btnsearch,btncadang;
   4:     //protected Button btnpaste,btntaipinput;
   5:     protected WebView webview1;
   6:     protected String serverurl;
   7:     protected AdView adView;
   8:     /** Called when the activity is first created. */
   9:     @Override
  10:     public void onCreate(Bundle savedInstanceState) {
  11:         super.onCreate(savedInstanceState);
  12:         setContentView(R.layout.main);
  13:         
  14:         //admob widget
  15:         adView = (AdView)findViewById(R.id.ad);
  16:         adView.loadAd(new AdRequest());
 



























































































































Saturday, November 3, 2012

nice looking calendar



 http://www.dansshorts.com/skins/dansshorts/assets/images/calendar.png



 <style>


</style>




<div class="post-date">