Quantcast
Channel: Geek On Java
Viewing all 322 articles
Browse latest View live

Struts2 AngularJS CRUD Example - Read Operation

$
0
0
Welcome Java geekers, hope you enjoy my previous article : Struts2 AngularJS CRUD Example - Insert Operation in which you learn how to insert data in database using Struts2 and AngularJS.
And in this article you'll learn how to fetch/read data from database using Struts2 and AngularJS.
For file structure you can see my previous article because here we'll go ahead with previous work.


2.1 create the database table

Run the subsequent SQL code on your PhpMyAdmin or any Database you want. this can be to create our database table. By the way, the database name we used in this tutorial was named “strutsangularcrud”.
--
-- Table structure for table `products`
--

CREATETABLE IF NOTEXISTS `products` (
`id` int(11) NOTNULL AUTO_INCREMENT,
`name` varchar(512) NOTNULL,
`description` textNOTNULL,
`price` int(11) NOTNULL,
PRIMARYKEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=64 ;

2.1.1 Dump sample data on the table

Run the following SQL code on your PhpMyAdmin again, this will pre-insert sample data or record on our “products” database table.
--
-- Dumping data for table `products`
--

INSERTINTO `products` (`id`, `name`, `description`, `price`) VALUES
(1, 'LG Optimus 4X HD P880 Black', 'Display - True HD-IPS LCD - 720 x 1280 pixels, 4.7 inches. Internal Memory - 16 GB storage (12 GB user available), 1 GB RAM. Camera - 8 MP, 3264x2448 pixels, autofocus, LED flash', 309),
(2, 'Motorola Google Nexus 6, Midnight Blue 32GB', 'The stunning 6 inch Quad HD display is great for movies, videos, gaming, e-books, and surfing the Web, and the Nexus 6 provides exceptional battery life.', 400),
(3, 'Samsung Galaxy S4 i9500 16GB', 'Make your life richer, simpler, and more fun. As a real life companion, the new Samsung GALAXY S4 helps bring us closer and captures those fun moments when we are together. Each feature was designed to simplify our daily lives. Furthermore, it cares enough to monitor our health and well being.', 600),
(6, 'Bench Men''s Bench Spokes Slim T-Shirt', 'Make their heads spin by rollin'' through with swag to spare. Cotton-poly heather blend provides for a soft, comfortable wear. Screen printed Bench graphics on front. Slim fitting for modern appeal. Contrast topstitching along shoulders. Ribbed crew neck. Short sleeves', 14),
(7, 'HP ZBook 17 Mobile Business Workstation', 'Feel the power! Take performance to a new level with the HP ZBook 17 with Intel''s quad core CPU and 4GB GDDR5 Nvidia Quadro graphics. Project a professional image at the office, client meetings, and on the road without sacrificing durability in a stylish chassis.', 5149),
(8, 'Samsung Galaxy Tab 4', 'Ideal for watching HD movies, playing games, browsing the web, or reading, the Samsung Galaxy Tab 4 features a 10.1-inch, 1280x800 resolution screen, so you experience rich graphics, bright colors, and crisp text.', 210),
(9, 'Spalding Men', 'Right from the beginning, it was all about being first, being the best…being what others could only dream of becoming. Founded by Boston Red Stockings pitcher A.G. Spalding in 1876, Spalding has become a leader of innovation and quality in the sporting goods industry.', 49),
(10, 'Sony Smart Watch 3', 'Contextually aware and smart, Android Wear gives you useful information at a glance and responds to your voice, feeding you relevant and specific information as you move.', 194),
(11, 'Huawei SnapTo', 'Support all GSM 4G LTE Networks ( T-Mobile, AT&T, Straight Talk, NET10, etc.). 75% screen-body ratio and a stylish, leather-texture finish battery cover with a slim design make the phone compac', 179),
(12, 'Abercrombie Men''s Lake Arnold Blazer', '100% Gabardine wool imported from Italy. Classic collegiate blazer with heritage A&F crest at left chest pocket. Front pockets with fold-over flaps.', 25);

2.2 Display list of data in table

We will put the following code under the “h4” tag of our index.jsp of previous article

<!-- used for searching the current list -->
<inputtype="text"ng-model="search"class="form-control"placeholder="Search product..."/>

<!-- table that shows product record list -->
<tableclass="hoverable bordered">

<thead>
<tr>
<thclass="text-align-center">ID</th>
<thclass="width-30-pct">Name</th>
<thclass="width-30-pct">Description</th>
<thclass="text-align-center">Price</th>
<thclass="text-align-center">Action</th>
</tr>
</thead>

<tbodyng-init="getAll()">
<trng-repeat="d in names | filter:search">
<tdclass="text-align-center">{{ d.id }}</td>
<td>{{ d.name }}</td>
<td>{{ d.description }}</td>
<tdclass="text-align-center">{{ d.price }}</td>
<td>
<ang-click="readOne(d.id)"class="waves-effect waves-light btn margin-bottom-1em"><iclass="material-icons left">edit</i>Edit</a>
<ang-click="deleteProduct(d.id)"class="waves-effect waves-light btn margin-bottom-1em"><iclass="material-icons left">delete</i>Delete</a>
</td>
</tr>
</tbody>
</table>

2.3 AngularJS code to read records

The following code will be inside the AngularJS app.controller curly braces.
// read products
$scope.getAll =
function(){
$http.get(
"readproducts").success(function(response){
$scope.names = response.records;
});
}

ProductDB.java

It will retrieve records from the database. The code will look like the following.
publicstatic List<Product> selectAll() {
List<Product> persons = new ArrayList<Product>();
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;

try {
connection = ConnectionConfiguration.getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT * FROM products");

while (resultSet.next()) {
Product person = new Product();
person.setId(resultSet.getInt("id"));
person.setName(resultSet.getString("name"));
person.setPrice(resultSet.getInt("price"));
person.setDescription(resultSet.getString("description"));

persons.add(person);
}

} catch (Exception e) {
e.printStackTrace();
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

return persons;
}

ProductJSONAction.java

In this file it return JSON data to AngularJS which deal to show data in table
package com.blogspot.geekonjava.json;

importjava.io.IOException;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;

importjavax.servlet.http.HttpServletRequest;

importorg.apache.commons.io.IOUtils;
importorg.apache.struts2.ServletActionContext;

importcom.blogspot.geekonjava.db.ProductDB;
importcom.blogspot.geekonjava.gs.Product;
importcom.opensymphony.xwork2.Action;

publicclassProductJSONAction{
static HttpServletRequest request ;

private Map<String,String> map = new HashMap<String,String>();

private Product pd = new Product();

private List<Product> records = new ArrayList<Product>();

publicProductJSONAction()
{
List<Product> ps = ProductDB.selectAll();

for(Product p : ps)
{

pd.setName(p.getName());
pd.setId(p.getId());
pd.setDescription(p.getDescription());
pd.setPrice(p.getPrice());

records.add(p);
}
}


public List<Product> getRecords() {
return records;
}

publicvoidsetRecords(List<Product> records) {
this.records = records;
}


public String execute() {
return Action.SUCCESS;
}

}

Output should look like this

Now we can view the product list and try the search feature.

This section is for fetching or reading module of Struts2 with AngularJS and hope you enjoy this tutorial. And if you want source code of this section. Please send me your request then i'll send that on your email id and contact us.
Please feel free to suggest and comment.

Struts2 AngularJS CRUD Example - Update Operation

$
0
0
In my previous article on Struts2 and AngularJS CRUD example I covered CR(Create/Insert and Read/Fetch) part and in this article we're covering update operation in this integration.
For better understanding of this section please check previous article carefully because we'll go ahead with previous references.



Hope you'll be familiar with file structure now we'll dive in update operation. Here all works performed on Read section 2 where data shown in table with Edit button like given below:


Now  our first work is that when we click on edit button a modal will be open with their correspondence data relate to their id.

3.1 AngularJS code to read details of record to be edited

The following code will help put the details of record to be edited to our HTML form.
// retrieve record to fill out the form
$scope.readOne = function(id){

// change modal title
$('#modal-product-title').text("Edit Product");

// show udpate product button
$('#btn-update-product').show();

// show create product button
$('#btn-create-product').hide();

// post id of product to be edited
$http.post("readoneproducts", {
'id' : id
})
.success(function(data, status, headers, config){

// put the values in form

$scope.id = data['personData']["id"];
$scope.name = data['personData']["name"];
$scope.description = data['personData']["description"];
$scope.price = data['personData']["price"];

// show modal
$('#modal-product-form').openModal();
})
.error(function(data, status, headers, config){
Materialize.toast('Unable to retrieve record.', 4000);
});
}
Now configure readoneproducts action in struts.xml

3.2 Struts.xml

<actionname="readoneproducts"class="com.blogspot.geekonjava.json.ProductSingleFetch">
<resulttype="json"/>

</action>
Now write our logic code in ProductSingleFetch

3.3 ProductSingleFetch.java

package com.blogspot.geekonjava.json;

importjava.io.IOException;

importjavax.servlet.http.HttpServletRequest;

importorg.apache.commons.io.IOUtils;
importorg.apache.struts2.ServletActionContext;

importcom.blogspot.geekonjava.db.ProductDB;
importcom.blogspot.geekonjava.gs.Product;
importcom.opensymphony.xwork2.Action;

publicclassProductSingleFetchimplements Action {
static HttpServletRequest request ;

private Product personData = new Product();

public String execute() throws IOException {

request = ServletActionContext.getRequest();
String filename = IOUtils.toString(request.getInputStream());
Product p = ProductDB.fileToString(filename);
personData.setId(p.getId());
personData.setName(p.getName());
personData.setDescription(p.getDescription());
personData.setPrice(p.getPrice());
return SUCCESS;
}


public String updateProductData() throws IOException
{
request = ServletActionContext.getRequest();
String filename = IOUtils.toString(request.getInputStream());
System.out.println("fileee1 "+filename);
Product p = ProductDB.jsonDataForUpdate(filename);

return"success";
}


public Product getPersonData() {
return personData;
}

publicvoidsetPersonData(Product personData) {
this.personData = personData;
}

}

3.4 AngularJS code to update a record

The following code will be triggered when the “Save Changes” button in the modal was clicked. Put it inside the app.controller curly braces.
// update product record / save changes
$scope.updateProduct = function(){
$http.post('updateproducts', {
'id' : $scope.id,
'name' : $scope.name,
'description' : $scope.description,
'price' : $scope.price
})
.success(function (data, status, headers, config){
// tell the user product record was updated
Materialize.toast(data, 4000);

// close modal
$('#modal-product-form').closeModal();

// clear modal content
$scope.clearForm();

// refresh the product list
$scope.getAll();
});
}
Now configure updateproducts action in struts.xml after section 3.2
<actionname="updateproducts"class="com.blogspot.geekonjava.json.ProductSingleFetch"method="updateProductData">
<resulttype="json"/>

</action>

3.5 Now add two function in ProductDB.java

jsonDataForUpdate

publicstatic Product jsonDataForUpdate(String filename)
{
System.out.println("inside filetostring "+filename);
Product p = new Product();
JSONParser parser = new JSONParser();
try {

Object obj = parser.parse(filename);
System.out.println("object "+obj);
JSONObject json = (JSONObject) obj;

int id = Integer.parseInt(String.valueOf(json.get("id")));
String name= (String)json.get("name");
String description = (String)json.get("description");
int price = Integer.parseInt(String.valueOf(json.get("price")));
p.setId(id);
p.setName(name);
p.setDescription(description);
p.setPrice(price);
update(p, id);
System.out.println("id "+id);


}
catch (Exception ex) { }
return p;

}

update

publicstaticvoidupdate(Product person, int id) {
Connection connection = null;
PreparedStatement preparedStatement = null;

try {
connection = ConnectionConfiguration.getConnection();
preparedStatement = connection.prepareStatement("UPDATE products SET " +
"name = ?, description = ?, price = ? WHERE id = ?");

preparedStatement.setString(1, person.getName());
preparedStatement.setString(2, person.getDescription());
preparedStatement.setInt(3, person.getPrice());
preparedStatement.setInt(4, id);
preparedStatement.executeUpdate();

System.out.println("UPDATE person SET " +
"first_name = ?, last_name = ? WHERE id = ?");

} catch (Exception e) {
e.printStackTrace();
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

Output should look like this

When you clicked an “Edit” button in the product list, you should see the modal with form data of record to be edited.

This section is for editing or updating module of Struts2 with AngularJS and hope you enjoy this tutorial. And if you want source code of this section. Please send me your request then i'll send that on your email id and contact us.
Please feel free to suggest and comment.

Struts2 AngularJS CRUD Example - Delete Operation

$
0
0
This is last section of Struts2 and AngularJS CRUD integration section and in my previous article I covered CRU(Create/Insert , Read/Fetch and Update/Edit) part. Please check all previous part because we worked next with previous references.



In this article we'll cover deletion part of CRUD section.
We already cover fetching data from database and show on table with two button Edit and Delete.

4.1 AngularJS code to delete a record

Put the following code inside the app.controller part of our AngularJS code.
// delete product
$scope.deleteProduct = function(id){

// ask the user if he is sure to delete the record
if(confirm("Are you sure?")){
// post the id of product to be deleted
$http.post("deleteproduct", {
'id' : id
}).success(function (data, status, headers, config){

// tell the user product was deleted
Materialize.toast(data, 4000);

// refresh the list
$scope.getAll();
});
}
}
Configure deleteproduct action in struts.xml

4.2 Struts.xml

<actionname="deleteproduct"class="com.blogspot.geekonjava.json.ProductDelete">
<resulttype="json"/>

</action>

Now we define our ProductDelete class where action controller exist

4.3 ProductDelete.java

package com.blogspot.geekonjava.json;

importjava.io.IOException;

importjavax.servlet.http.HttpServletRequest;

importorg.apache.commons.io.IOUtils;
importorg.apache.struts2.ServletActionContext;

importcom.blogspot.geekonjava.db.ProductDB;
importcom.blogspot.geekonjava.gs.Product;
importcom.opensymphony.xwork2.Action;

publicclassProductDeleteimplements Action{
static HttpServletRequest request ;
private Product personData = new Product();

public String execute() throws IOException {

request = ServletActionContext.getRequest();
String filename = IOUtils.toString(request.getInputStream());
System.out.println("fileee1 "+filename);
Product p = ProductDB.jsonDataForDelete(filename);


return SUCCESS;
}





public Product getPersonData() {
return personData;
}

publicvoidsetPersonData(Product personData) {
this.personData = personData;
}


}

4.4 Now we add two function in ProductDB class

jsonDataForDelete

In this function we get id from json object
publicstatic Product jsonDataForDelete(String filename)
{
System.out.println("inside filetostring "+filename);
Product p = new Product();
JSONParser parser = new JSONParser();
try {

Object obj = parser.parse(filename);
System.out.println("object "+obj);
JSONObject json = (JSONObject) obj;

int id = Integer.parseInt(String.valueOf(json.get("id")));
delete(id);


}
catch (Exception ex) { }
return p;

}

delete

In this function we look for delete query hit on database
publicstaticvoiddelete(int id) {
Connection connection = null;
PreparedStatement preparedStatement = null;

try {
connection = ConnectionConfiguration.getConnection();
preparedStatement = connection.prepareStatement("DELETE FROM products WHERE id = ?");
preparedStatement.setInt(1, id);
preparedStatement.executeUpdate();

System.out.println("DELETE FROM person WHERE id = ?");

} catch (Exception e) {
e.printStackTrace();
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

Output should look like this

When a delete button was clicked, it will show a confirmation pop up. When the user clicked “Ok”, a toast message will appear confirming the deletion of a record.


This section is for deleting or removing module of Struts2 with AngularJS and hope you enjoy this tutorial. And if you want source code of this section. Please send me your request then i'll send that on your email id and contact us.
Please feel free to suggest and comment.

Best 16 Features of Android 7 Nougat You Should Know

$
0
0
Google has published the official name as the “Nougat” for the latest release of Android. Nougats are a series confections made using sugar, honey, roasted nuts and chopped candied fruits. There were many predictions regarding the name of new android firmware version. Millions of people thought that it will be “Android Nutella”. But the Google has confirmed the official name as “Android Nougat”.



You should see : Naming Android: What Comes After Marshmallow

1. View Apps Side-by-Side

Possibly the biggest new feature in Android Nougat is a multi-window mode. While you're using an app, just long-press the recent apps button, then you'll be prompted to select another app. Once you do that, both apps will be visible side by side, with a black bar in the middle that you can drag to resize the windows. It makes for a great experience when browsing the web while watching videos, and it turns Android into a true multitasking platform.


2. Drag & Drop

To make the multi-window experience even better, Google has included support for dragging and dropping files or text in Android Nougat. Developers will have to update their apps to offer support for this new feature, but some, like Gmail, have already added it.


3. Switch Apps Faster

Nougat has several multitasking improvements, but this one might be the most practical of them all. When you want to switch back to the last app you were using, just double-tap your recent apps button. It works a lot like the Alt-Tab feature in Windows (or Command-Tab on a Mac), so you can keep double-tapping to flip back and forth between your two most recently-used apps.

4. Clear All Recent Apps

With all of the attention given to the recent apps button, you might think the menu itself was overlooked. But in addition to an updated interface with bigger preview cards, Google added a "Clear All" button to the top of this list. You have to scroll all the way up to the top of your recent apps list to see it, but this should help a lot if you like to keep things tidy.

5. Deal with Notifications in Groups or Individually

A new feature called "Bundled Notifications" should make it a lot easier to deal with multiple emails or text messages in Nougat. Like previous versions, notifications from the same app will be grouped together in your notification tray, where you can dismiss them all as one. But if you only want to dismiss one email, for example, you can now swipe down on the grouped notification to expand them, where you can then dismiss them one by one.



6. Respond from Notifications

Nougat's new "Direct Reply" feature should save you lots of time when messaging or responding to emails. As soon as a new message arrives, you'll see a "Reply" button directly on the notification—just tap this, then start typing to respond. Some apps have had this capability in the past, but biggest difference here is that Nougat provides a unified interface that all apps can use.


7. Set Notification Importance

Marshmallow implemented granular controls for notification importance, but Nougat is taking this concept to the next level. Notifications can now be set to different importance levels, meaning you can set one app to never cause your phone to beep, while setting the next app to have full "heads up"-style notifications. You have to enable the System UI Tuner, then turn on "Power notification controls" to get these newer options, but it offers a lot more control. To access this new menu, simply long-press any notification.


8. Access Quick Settings Faster

Samsung's TouchWiz and other manufacturer-skinned versions of Android will show you a small collection of toggles when you swipe down to view your notifications, but stock Android has always required that you swipe down twice to access these "Quick Settings." That's changing with Nougat, and now, the top 5 toggles will be visible directly from your notification tray. You can still swipe down a second time to see the full suite of toggles (and even edit or rearrange the tiles), but having quicker access to common functions makes this menu a lot more useful.

9. Add Your Own Quick Settings Tiles

Android Marshmallow introduced a feature that allowed you to create your own Quick Settings tiles and toggles, but it was buried pretty deep in Settings, and the setup process was fairly complicated. With Nougat, this feature has been vastly improved, and now it's ready for prime time. You simply install any compatible app to add the tiles, then tap the "Edit" button at the bottom of the Quick Settings menu, which lets you move your custom tiles to the top of the list.

10. Set a Separate Wallpaper for Your Lock Screen

Another Nougat feature that previously existed in manufacturer-skinned versions of Android is the ability to set one wallpaper for your home screen, then have a separate wallpaper just for your lock screen. There's no Settings menu for this, but you'll be prompted to choose when applying a new photo as your home screen wallpaper.

11. Send Better Emoji

Android has typically lagged behind iOS when it comes to staying up-to-date on the latest emoji, but that's changing with Nougat. The month-long window between Nougat's release and the debut of iOS 10 will mark the first time that Android devices have newer emoji than their iPhone counterparts, as Android 7.0 is using the latest Unicode 9.0 standard.


12. Save More Data

Android has had a "Data saver" mode for a few versions now, but Nougat makes this feature far more intelligent. When the feature is enabled in Settings, your phone will detect the type of cellular plan being used, and whether or not you're roaming. If you're on a plan with limited data, it will automatically restrict the amount of data that apps can use in the background, which should hopefully save a few megabytes each month.

13. Cancel Downloads Easily

It's the little finishing touches that make Android Nougat one of Google's best releases yet. For instance, you'll no longer have to open the Downloads app to cancel an ongoing download—instead, there are now "Pause" and "Cancel" buttons directly on the download notification.


14. Install Apps Faster

Android 7.0 will be using a new "Just in Time" compiler to prepare apps and their files upon installation. Dry, technical stuff to the side, this ultimately means that bigger apps like Facebook and graphics-intensive games will now install up to three times faster. Less time waiting on apps to install, and more time actually enjoying them—what's not to love about that?

15. Change Your DPI to Shrink or Enlarge Content

Android screens keep getting bigger every year, and it seems as though all of the icons and fonts are doing the same. If you felt that on-screen elements were too big in the past, you would previously have to root your device and install a DPI-changing app to shrink things down. But with Nougat, you can now just head to the Display menu in Settings, then select the "Display size" option to scale everything up or down by a few notches.


16. Block Phone Numbers Across All Apps

The Google Phone app introduced a call-blocking feature last year, and now Android Nougat is taking this functionality to the next level. Instead of just blocking calls, you can block a number from communicating with you altogether—even through third-party SMS apps. When you enable call blocking in your default dialer, you'll be prompted to turn on the new feature. Third-party developers will have to update their apps for compatibility, but a system-wide phone number blocker is a welcome addition.

What your thought of that cool features about Android Nought if you want to say something then comment below. Thanks

Java Optimization Rules Every Java Developer need to know

$
0
0

Java Optimization Rules 

Total 135 rules to optimize your Java program and Every Java developer know about this.


Picture source: blog.takipi.com



Rules available in this category:
  1. Use_String_length_to_compare_empty_string_variables
  2. Avoid_using_Math_class_methods_on_constants
  3. Avoid_consecutively_invoking_StringBuffer_append_with_string_literals
  4. Avoid_creating_thread_without_run_method
  5. Always_reuse_immutable_constant_objects_for_better_memory_utilization
  6. Avoid_constant_expressions_in_loops
  7. Avoid_invoking_time_consuming_methods_in_loop
  8. Avoid_duplication_of_code
  9. Use_entrySet_instead_of_keySet
  10. Ensure_efficient_removal_of_elements_in_a_collection
  11. Ensure_efficient_removal_of_map_entries
  12. Ensure_efficient_iteration_over_map_entries
  13. Avoid_using_java_lang_Class_forName
  14. Do_not_declare_members_accessed_by_inner_class_private
  15. Avoid_synchronized_modifier_in_method
  16. Avoid_empty_if
  17. Avoid_empty_static_initializer
  18. Avoid_unnecessary_if
  19. Avoid_unnecessary_parentheses
  20. Avoid_unnecessary_implementing_Clonable_interface
  21. Avoid_using_MessageFormat
  22. Avoid_writeByte_method_in_loop
  23. Avoid_repeated_casting
  24. Use_ternary_operator
  25. Remove_unnecessary_if_then_else_statement
  26. Always_dispose_SWT_Control
  27. Always_declare_constant_field_static
  28. Use_buffered_IO
  29. Avoid_unnecessary_casting
  30. Avoid_instantiation_of_class_with_only_static_members
  31. Close_jdbc_connections
  32. Close_jdbc_connections_Only_In_finally_Block
  33. Avoid_synchronized_readObject_method
  34. Avoid_boolean_array
  35. Avoid_string_concatenation_in_loop
  36. Avoid_method_calls_in_loop
  37. Avoid_new_with_string
  38. Loop_invariant_code_motion
  39. Use_short_circuit_boolean_operators
  40. Avoid_using_StringTokenizer
  41. Use_instanceof_only_on_interfaces
  42. Avoid_null_check_before_instanceof
  43. Stream_not_closed
  44. Close_streams_only_in_finally
  45. Avoid_instantiation_for_getClass
  46. Use_System_arrayCopy
  47. Use_String_length_to_compare_empty_string
  48. Use_String_equalsIgnoreCase
  49. Place_try_catch_out_of_loop
  50. Declare_inner_class_static
  51. Declare_inner_class_using_outer_class_only_in_constructor_static
  52. Avoid_nested_Synchronized_blocks
  53. Avoid_empty_try_blocks
  54. Declare_accessor_methods_final
  55. Use_batch_update_for_sql_queries
  56. Declare_private_constant_fields_final
  57. Always_declare_constant_local_variables_final
  58. Reduce_number_of_exception_creations
  59. Reduce_switch_density
  60. Avoid_empty_loops
  61. Avoid_new_Integer_toString
  62. Avoid_passing_primitive_int_to_Integer_constructor
  63. Avoid_passing_primitive_long_to_Long_constructor
  64. Avoid_passing_primitive_double_to_Double_constructor
  65. Avoid_passing_primitive_short_to_Short_constructor
  66. Avoid_passing_primitive_byte_to_Byte_constructor
  67. Avoid_passing_primitive_char_to_Character_constructor
  68. Avoid_using_String_toString
  69. Avoid_unnecessary_substring
  70. Use_toArray_with_array_as_parameter
  71. Do_lazy_initialization
  72. Avoid_using_Thread_yield
  73. Avoid_unread_fields
  74. Avoid_equality_with_boolean
  75. Avoid_startsWith
  76. Avoid_readByte_method_in_loop
  77. Avoid_instantiation_of_boolean
  78. Avoid_Synchronized_blocks
  79. Declare_package_private_method_final
  80. Declare_public_or_protected_method_final
  81. Declare_public_or_protected_class_final
  82. Use_array_of_primitive_type_insteadof_collection
  83. Avoid_using_Double_toString
  84. Avoid_debugging_code
  85. Avoid_using_Thread_dumpStack
  86. Avoid_using_java_lang_Runtime_freeMemory
  87. Avoid_using_java_lang_Runtime_totalMemory
  88. Avoid_using_java_lang_Runtime_traceInstructions
  89. Avoid_using_java_lang_Runtime_traceMethodCalls
  90. Avoid_using_java_lang_Class_getMethod
  91. Avoid_using_java_lang_Class_getField
  92. Avoid_using_java_lang_Class_getDeclaredMethod
  93. Avoid_using_java_lang_Class_getDeclaredField
  94. Always_Access_Fields_In_Same_Class_Directly
  95. Use_arrayList_inplace_of_vector
  96. Avoid_unnecessary_exception_throwing
  97. Avoid_LinkedLists
  98. Use_single_quotes_when_concatenating_character_to_String
  99. Use_PreparedStatement_instead_of_Statement
  100. Avoid_multi_dimensional_arrays
  101. Avoid_empty_synchronized_block
  102. Use_DataSource_instead_of_DriverManager
  103. Avoid_call_to_Thread.sleep()
  104. Use_String_instead_StringBuffer_for_constant_strings
  105. Avoid_using_String_charAt
  106. Avoid_Extending_java_lang_Object
  107. Use_compound_operators
  108. Avoid_concatenating_Strings_in_StringBuffer
  109. Declare_package_private_class_final
  110. Use_hashMap_inplace_of_hashTable
  111. Avoid_creating_double_from_string
  112. Always_use_right_shift_operator_for_division_by_powers_of_two
  113. Use_shift_operators
  114. Avoid_java_lang_reflect_package
  115. Use_NIO_in_server
  116. Avoid_object_instantiation_in_loops
  117. Avoid_unnecessary_instanceof
  118. Define_initial_capacities
  119. Avoid_empty_catch_blocks
  120. Avoid_synchronized_methods_in_loop
  121. Avoid_synchronized_blocks_in_loop
  122. Close_jdbc_resources
  123. Close_jdbc_resources_only_in_finally_block
  124. Specify_StringBuffer_capacity
  125. Avoid_using_exponentiation
  126. Use_transient_keyword
  127. Avoid_new_inside_getTableCellRendererComponent
  128. Avoid_Integer_valueOf_intValue
  129. Use_ternary_operator_for_assignment
  130. Avoid_Serialized_class_with_no_instance_variables
  131. Avoid_Vector_elementAt_inside_loop
  132. Declare_variable_final
  133. Declare_method_arguments_final
  134. Avoid_polling_loops
  135. Avoid_Serialized_class_with_only_transient_fields

Rule 1: Use_String_length_to_compare_empty_string_variables

Severity:  High
Rule:  The String.equals() method is overkill to test for an empty string. It is quicker to test if the length of the string is 0.
Reason:  The String.equals() method is overkill to test for an empty string. It is quicker to test if the length of the string is 0.
Usage Example: 
package com.rule;
class Use_String_length_to_compare_empty_string_violation
{
public boolean isEmpty(String str)
{
return str.equals(""); // VIOLATION
}
}
Should be written as:
package com.rule;
class Use_String_length_to_compare_empty_string_correction
{
public boolean isEmpty(String str)
{
return str.length()==0; // CORRECTION
}
}

Rule 2: Avoid_using_Math_class_methods_on_constants

Severity:  Medium
Rule:  It is quicker to determine the value statically.
Reason:  It is quicker to determine the value statically.
Usage Example: 
public class Test
{
public void fubar() 
{
double a;
a = Math.abs(1.5); // VIOLATION
}
}
Should be written as:
public class Test
{
public void fubar() 
{
double a;
a =1.5; // FIXED
}
}
Reference:  Not Available. 

Rule 3: Avoid_consecutively_invoking_StringBuffer_append_with_string_literals

Severity:  Medium
Rule:  Doing so reduces the classfile size  by 17 bytes and eliminates a few instructions.
Reason:  Doing so reduces the classfile size  by 17 bytes and eliminates a few instructions.
Usage Example: 
public class Test 
{
private void fubar() 
{
StringBuffer buf = new StringBuffer();
buf.append("Hello").append(" ").append("World");  // VIOLATION
 }
}
Should be written as:
public class Test 
{
private void fubar() 
{
StringBuffer buf = new StringBuffer();
buf.append("Hello World");// FIXED
}
}
Reference:  Not Available. 

Rule 4: Avoid_creating_thread_without_run_method

Severity:  High
Rule:  A Thread which is created without specifying a run method does nothing other than a delay in performance.
Reason:  A Thread which is created without specifying a run method does nothing other than a delay in performance.
Usage Example: 
public class Test
{
 public void method() throws Exception
 {
  new Thread().start();  //VIOLATION
 }
}
Should be written as:
public class Test
{
 public void method(Runnable r) throws Exception
 {
  new Thread(r).start();  //FIXED
 }
}
Reference:  Not Available. 

Rule 5: Always_reuse_immutable_constant_objects_for_better_memory_utilization

Severity:  Medium
Rule:  Creation of constant immutable objects that are not assigned to static final variables lead to unnecessary memory consumption.
Reason:  Creation of constant immutable objects that are not assigned to static final variables lead to unnecessary memory consumption.
Usage Example: 
public class Test
{
  protected Object[] getObjects() 
 {
  return new Object[0];  // VIOLATION
  }
 
 publicstatic Integer convertToInt(String s) 
 {
  if (s == null || s.length() == 0)
  {
return new Integer(-1);  // VIOLATION
}
  else
  {
return new Integer(s);
}
 }
}
Should be written as:
public class Test 
{
 public static final Object[] NO_OBJECTS = new Object[0];
 
 protected Object[] getObjects() 
{
  return NO_OBJECTS;  // FIXED
 }
 
 private static final Integer INT_N1 = new Integer(-1);
 
 public static Integer convertToIn(String s) {
  if (s == null || s.length() == 0)
  {
return INT_N1;  // FIXED
}
  else
  {
return new Integer(s);
}
 }
}
Reference:  Not available. 

Rule 6: Avoid_constant_expressions_in_loops

Severity:  Medium
Rule:  It is more efficient to either simplify these expressions or move them outside the body of the loop.
Reason:  It is more efficient to either simplify these expressions or move them outside the body of the loop.
Usage Example: 
public class Test
{
 public static final boolean TRUE= true;
 public static final boolean FALSE= false;
 public static final int FOO= 7;
 
 public void myMethod()
 {
  int[] x= new int[10];
  int j= 0;
  
  for(int i=0; i<10; i++)
 {
x[0]= 7+(FOO+9);// VIOLATION

for(j=0; TRUE||FALSE;)// VIOLATION
  {
}
  }
 }
}
Should be written as:
public class Test
{
 public void myMethod()
 {
  int[] x= new int[10];
  int j= 0;
  
  x[0]= 7+(FOO+9);//FIXED
  for(int i=0; i<10; i++)
 {
for(j=0; TRUE;)//FIXED
  {
}
  }
 }
}
Reference:  Not Available. 

Rule 7: Avoid_invoking_time_consuming_methods_in_loop

Severity:  Medium
Rule:  Moving method calls which may take a long time outside of loops can improve performance.
Reason:  Moving method calls which may take a long time outside of loops can improve performance.
Usage Example: 
import java.util.Arrays;


public class Test
{
 public int[] sortArray(int[] a)
{
  for(int i=0; i<100; i++)
  {
Arrays.sort(a);  // VIOLATION
//Some other code
  }
  return a;
 }
}
Should be written as:
public class Test
{
 public int[] sortArray(int[] a)
{
  Arrays.sort(a);  // FIXED
  for(int i=0; i<100; i++)
 {
//Some other code
  }
  return a;
 }
}
Reference:  Not Available. 

Rule 8: Avoid_duplication_of_code

Severity:  High
Rule:  Avoid duplication of code.
Reason:  Avoid duplication of code.
Usage Example: 
package com.rule;

public class Avoid_duplication_of_code_violation
{
public void method()
{
int x = getValue();

if(x > 10)
{ // Violation.
int j = i + 10;
int k = j * 2;
System.out.println(k);
}
else if( x < 20 )
{ // Violation.
int j = i + 10;
int k = j * 2;
System.out.println(k);
}
}

}
Should be written as:
Reference:  Reference not available. 

Rule 9: Use_entrySet_instead_of_keySet

Severity:  Medium
Rule:  Use entrySet() instead of keySet().
Reason:  Use entrySet() instead of keySet().
Usage Example: 
package com.rule;

import java.util.Map;
import java.util.Set;
import java.util.HashMap;
import java.util.Iterator;

public class Use_entrySet_instead_of_keySet_violation
{
public void method()
{
Map m = new HashMap();
Iterator it = m.keySet().iterator();
Object key = it.next();
Object v = m.get(key); // Violation

}

}
Should be written as:
package com.rule;

public class Use_entrySet_instead_of_keySet_correction
{
public void method()
{
Map m = new HashMap();
Set set = m.entrySet(); //Correction.
Object keyValuePair = it.next();
}

}
Reference:  Reference not available. 

Rule 10: Ensure_efficient_removal_of_elements_in_a_collection

Severity:  Medium
Rule:  Searching a collection to fetch the element to remove is inefficient.
Reason:  Searching a collection to fetch the element to remove is inefficient.
Usage Example: 
public class Test 
{
public void someMethod(Collection collection)
{
Iterator iter = collection.iterator();
while (iter.hasNext()) 
{
Object element = iter.next();
collection.remove(element); // VIOLATION
}
}
}
Should be written as:
public class Test 
{
public void someMethod(Collection collection)
{
Iterator iter = collection.iterator();
while (iter.hasNext()) 
{
iter.remove(); // FIXED
}
}
}
Reference:  Not available. 

Rule 11: Ensure_efficient_removal_of_map_entries

Severity:  Medium
Rule:  Searching a keyset/entryset to fetch the key to remove the element is inefficient.
Reason:  Searching a keyset/entryset to fetch the key to remove the element is inefficient.
Usage Example: 
import java.util.*;

public class Test 
{
 public void someMethod(HashMap collection)
 {
  Set keySet = collection.keySet();
  Iterator keyIter = keySet.iterator();
  while (keyIter.hasNext()) 
  {
Object key = keyIter.next();
collection.remove(key); // VIOLATION
  }
 }
}
or another case when we iterate on entry set:


public class Test 
{
 public void someMethod(HashMap collection)
 {
  Set entrySet = collection.entrySet();
  Iterator entriesIter = entrySet.iterator();
  while (entriesIter.hasNext()) 
  {
(Map.Entry) entry = (Map.Entry)entriesIter.next();
Object key = entry.getKey();
collection.remove(key); // VIOLATION
  }
 }
}
Should be written as:
public class Test 
{
 public void someMethod(HashMap collection)
 {
  Set keySet = collection.keySet();
  Iterator keyIter = keySet.iterator();
  while (keyIter.hasNext()) 
  {
keyIter.remove(); // FIXED
  }
 }
}
Reference:  Not available. 

Rule 12: Ensure_efficient_iteration_over_map_entries

Severity:  Medium
Rule:  Using a keyset to iterate over a map, and then requesting values for each key is inefficient.
Reason:  Using a keyset to iterate over a map, and then requesting values for each key is inefficient.
Usage Example: 
import java.util.Iterator;
import java.util.Map;

public class Test
{
 public void inefficientIteration(Map map)
 {
  Iterator iter = map.keySet().iterator();
  while (iter.hasNext()) {
Object key = iter.next();
Object value = map.get(key); // VIOLATION
  }
 }
}
Should be written as:
import java.util.Iterator;
import java.util.Map;

public class Test
{
 public void efficientIteration(Map map)
 {
  Iterator iter = map.entrySet().iterator();
  while (iter.hasNext()) {
Map.Entry entry = (Map.Entry)iter.next();
Object key = entry.getKey();
Object value = entry.getValue(); // FIXED
  }
 }
}
Reference:  Not available. 

Rule 13: Avoid_using_java_lang_Class_forName

Severity:  Medium
Rule:  Decreases performance and could cause possible bugs.
Reason:  Decreases performance and could cause possible bugs.
Usage Example: 
public class Test 
{
private void foo()
{
try
{
System.out.println(Class.forName("java.lang.Integer")
.getName()); // VIOLATION
}
catch ( ClassNotFoundException e )
{
e.printStackTrace();
}
}

}
Should be written as:
public class Test 
{
private void foo()
{
System.out.println(java.lang.Integer.class.getName()); // CORRECTION
}

}
Reference:  No references available. 

Rule 14: Do_not_declare_members_accessed_by_inner_class_private

Severity:  High
Rule:  Do not declare members accessed by inner class private.
Reason:  Do not declare members accessed by inner class private.
Usage Example: 
package com.rule;
public class Do_not_declare_members_accessed_by_inner_class_private_violation 
{
private int iVar = 0; // Violation
class inner
{
int var2;
public void foo()
{
var2 = iVar;
// ...
}
}
}
Should be written as:
package com.rule;
public class Do_not_declare_members_accessed_by_inner_class_private_correction 
{
int iVar = 0; // Correction
class inner
{
int var2;
public void foo()
{
var2 = iVar;
// ...
}
}
}

Rule 15: Avoid_synchronized_modifier_in_method

Severity:  High
Rule:  Avoid synchronized modifier in method for performace reasons
Reason:  Avoid synchronized modifier in method for performace reasons
Usage Example: 
package com.rule;
import java.io.ObjectOutputStream;
import java.io.IOException;

class Avoid_synchronized_modifier_in_method_violation
{
public synchronized void writeToStream(String s)throws IOException // VIOLATION
{
//....
}
}
Should be written as:
package com.rule;

import java.io.ObjectOutputStream;
import java.io.IOException;

class Avoid_synchronized_modifier_in_method_correction
{
public void writeToStream(String s)throws IOException // CORRECTION
{
//....
synchronized (this)// CORRECTION
{
//....
}

//....
}
}
Reference:  Reference Not Available. 

Rule 16: Avoid_empty_if

Severity:  Low
Rule:  Avoid empty "if" block structure.
Reason:  Avoid empty "if" block structure.
Usage Example: 
package com.rule;

class Avoid_empty_if_violation
{
public void method()
{
final int ZERO = 0;
int i = 10;
if (i < ZERO) // VIOLATION
{
}
i = ZERO;
}
}
Should be written as:
package com.rule;

class Avoid_empty_if_correction
{
public void method()
{
final int ZERO = 0;
int i = 10;
/*
if (i < ZERO) // CORRECTION
{
}
*/
i = ZERO;
}
}
Reference:  Reference Not Available. 

Rule 17: Avoid_empty_static_initializer

Severity:  Low
Rule:  Since the static initializer contains no code, it can be safely removed.
Reason:  Since the static initializer contains no code, it can be safely removed.
Usage Example: 
public class Test
{
static  // VIOLATION
{
   // empty
  }
}
Should be written as:
public class Test
{
// ...
}
Reference:  Not Available. 

Rule 18: Avoid_unnecessary_if

Severity:  Medium
Rule:  Avoid unnecessary if statements.
Reason:  Avoid unnecessary if statements.
Usage Example: 
package com.rule;

public class Avoid_unnecessary_if_Violation
{
public void method()
{
if (true) // Violation.
{
 //Some Code ...
}
if (!true) // Violation.
{
//Some Code ...
}
}

}
Should be written as:
package com.rule;

public class Avoid_unnecessary_if_Correction
{
public void method()
{
boolean flag = true;

if (flag) //Correction.
{
 //Some Code ...
}
}

}
Reference:  Reference not available. 

Rule 19: Avoid_unnecessary_parentheses

Severity:  Medium
Rule:  Avoid unnecessary parentheses in an expression.
Reason:  Avoid unnecessary parentheses in an expression.
Usage Example: 
package com.rule;

public class Avoid_unnecessary_parentheses_violation
{
public void method()
{
if((method())) // Violation.
{
// Do Something..
}
}

}
Should be written as:
package com.rule;

public class Avoid_unnecessary_parentheses_correction
{
public void method()
{
if(method()) //Correction.
{
// Do Something..
}
}

}
Reference:  Reference not available. 

Rule 20: Avoid_unnecessary_implementing_Clonable_interface

Severity:  Medium
Rule:  Avoid unnecessary implementing Clonable interface.
Reason:  Avoid unnecessary implementing Clonable interface.
Usage Example: 
package com.rule;

public class Avoid_unnecessary_implementing_Clonable_interface_violation implements Clonable
{
public void method() //Violation.
{

}

}
Should be written as:
package com.rule;

public class Avoid_unnecessary_implementing_Clonable_interface_correction implements Clonable
{
public void method()
{
void_unnecessary_implementing_Clonable_interface theClone = new void_unnecessary_implementing_Clonable_interface();

Object o = theClone.clone(); //Correction.
}

}
Reference:  Reference not available. 

Rule 21: Avoid_using_MessageFormat

Severity:  Low
Rule:  Avoid using MessageFormat as it is slow.
Reason:  Avoid using MessageFormat as it is slow.
Usage Example: 
package com.rule;

import java.text.MessageFormat;

public class Avoid_using_MessageFormat_violation
{
public void method()
{
final int N = 25000;
Object argvec[] = new Object[2];
MessageFormat f = new MessageFormat("The square of {0,number,#} is {1,number,#}");
for (int i = 1; i <= N; i++)
{
argvec[0] = new Integer(i);
argvec[1] = new Integer(i * i);
String s = f.format(argvec);
System.out.println(s);
}
}
}
Should be written as:
package com.rule;
public class Avoid_using_MessageFormat_correction
{
public void method()
{
final int N = 25000;
String s;
for (int i = 1; i <= N; i++)
{
s = "The square of " + i + " is " + (i * i);
System.out.println(s);
}
}
}
Reference:  Reference Not Available. 

Rule 22: Avoid_writeByte_method_in_loop

Severity:  High
Rule:  Avoid writing single byte in loop
Reason:  Avoid writing single byte in loop
Usage Example: 
package com.rule;
class Avoid_writeByte_method_violation
{
public static void main(String args[])
{
final int ZERO = 0;
final int ONE = 1;
final int TEN = 10;
String strFileName = "C:\\demo.java"; //$NON-NLS-1$
try
{
java.io.FileOutputStream fos = new java.io.FileOutputStream(strFileName);
java.io.DataOutputStream ds = new java.io.DataOutputStream(fos);

int i = ZERO;
while(i < TEN)
{
ds.writeByte(ONE); // VIOLATION
i++;
}

for(i=ZERO; i<TEN; i++)
{
ds.writeByte(ONE); // VIOLATION
}

i = ZERO;

do
{
ds.writeByte(ONE); // VIOLATION
i++;
}
while(i<TEN);
}
catch(java.io.IOException e)
{
e.printStackTrace();
}
}
}
Should be written as:
package com.rule;
class Avoid_writeByte_method_correction
{
public static void main(String args[])
{
final int ZERO = 0;
final char ONE = '1';
final int TEN = 10;

String strFileName = "C:\\demo.java"; //$NON-NLS-1$
byte bArr[] = new byte[10];

try
{
java.io.FileOutputStream fos = new java.io.FileOutputStream(strFileName);
java.io.DataOutputStream ds = new java.io.DataOutputStream(fos);

int i = ZERO;
while(i < TEN)
{
bArr[i] = ONE;
i++;
}

ds.write(bArr, ZERO, bArr.length); // CORRECTION
}
catch(java.io.IOException e)
{
e.printStackTrace();
}
}
}
Reference:  Reference Not Available. 

Rule 23: Avoid_repeated_casting

Severity:  High
Rule:  Avoid repeated casting by casting it once and keeping its reference
Reason:  Avoid repeated casting by casting it once and keeping its reference
Usage Example: 
package com.rule;

import java.awt.Component;
import java.awt.TextField;

class Avoid_repeated_casting_violation
{
public void method(Component comp)
{
((TextField) comp).setText(""); // VIOLATION
((TextField) comp).setEditable(false); // VIOLATION
}
}
Should be written as:
package com.rule;

import java.awt.Component;
import java.awt.TextField;

class Avoid_repeated_casting_correction
{
public void method(Component comp)
{
final TextField tf = (TextField) comp; // CORRECTION
tf.setText("");
tf.setEditable(false);
}
}
Reference:  http://www.javaperformancetuning.com/tips/rawtips.shtml 
Java Performance tunning by Jack Shirazi 

Rule 24: Use_ternary_operator

Severity:  Medium
Rule:  Use ternary operator for improved performance
Reason:  Use ternary operator for improved performance
Usage Example: 
package com.rule;
class Use_ternary_operator_correction
{
public boolean test(String value)
{
if(value.equals("AppPerfect")) // VIOLATION
{
return true;
}
else
{
return false;
}
}
}
Should be written as:
package com.rule;
class Use_ternary_operator_correction
{
public boolean test(String value)
{
return value.equals("AppPerfect"); // CORRECTION
}
}
Reference:  Reference Not Available. 

Rule 25: Remove_unnecessary_if_then_else_statement

Severity:  Medium
Rule:  It could be simplified to enhance the code's efficiency and reduce its size.
Reason:  It could be simplified to enhance the code's efficiency and reduce its size.
Usage Example: 
public class Test 
{
 boolean b;
 public boolean isTrue() 
{
  if (b) //VIOLATION
  {
return true;
  }
  else
  {
return false;
  }
 }
}
Should be written as:
public class Test 
{
 boolean b;
 public boolean isTrue() 
{
  return b; //FIXED
 }

}
Reference:  Not available. 

Rule 26: Always_dispose_SWT_Control

Severity:  High
Rule:  Always dispose SWT Control.
Reason:  Always dispose SWT Control.
Usage Example: 
package com.rule;

import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;

public class Always_dispose_SWT_Control_violation 
{
public void createControl(Composite cmp, int style)
{
Control ct = new Button(cmp, style);  // Violation
//...do something with ct

}

}
Should be written as:
package com.rule;

import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;

public class Always_dispose_SWT_Control_correction 
{
public void createControl(Composite cmp, int style)
{
Control ct = new Button(cmp, style);
//...
ct.dispose();  // Correction
}
}

Rule 27: Always_declare_constant_field_static

Severity:  Medium
Rule:  The constant fields that are declared final should be declared static.
Reason:  The constant fields that are declared final should be declared static.
Usage Example: 
package com.rule;

public class Always_declare_constant_field_static_violation
{
final int MAX = 1000; // VIOLATION
final String NAME = "Noname"; // VIOLATION
}
Should be written as:
package com.rule;

public class Always_declare_constant_field_static_correction
{
static final int MAX = 1000; // CORRECTION
static final String NAME = "Noname"; // VIOLATION
}

Rule 28: Use_buffered_IO

Severity:  Critical
Rule:  Use BufferedInputStream and BufferedOutputStream or equivalent buffered methods wherever possible.
Doing I/O a single byte at a time is generally too slow.
Note that I/O operation uses lots of synchronization, hence you can get better performance by reading / writing in bulk.
Reason:  Use BufferedInputStream and BufferedOutputStream or equivalent buffered methods wherever possible.
Doing I/O a single byte at a time is generally too slow.
Note that I/O operation uses lots of synchronization, hence you can get better performance by reading / writing in bulk.
Usage Example: 
package com.rule;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

class Use_buffered_IO_violation
{
public static void copy(String from, String to) throws IOException
{
final int NEGATIVE = -1;
InputStream in = null;
OutputStream out = null;
try
{
in = new FileInputStream(from); // VIOLATION
out = new FileOutputStream(to); // VIOLATION
while (true)
{
int data = in.read();
if (data == NEGATIVE)
{
break;
}
out.write(data);
}
in.close();
out.close();
}
finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
  }
}
}
Should be written as:
package com.rule;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
class Use_buffered_IO_correction
{
public static void copy(String from, String to) throws IOException
{
final int NEGATIVE = -1;
InputStream in = null;
OutputStream out = null;
try
{
in = new BufferedInputStream(new FileInputStream(from)); // CORRECTION
out = new BufferedOutputStream(new FileOutputStream(to)); // CORRECTION
while (true)
{
int data = in.read();
if (data == NEGATIVE)
{
break;
}
out.write(data);
}
}
 finally
 {
  if (in != null)
  {
   in.close();
  }
  if (out != null)
  {
   out.close();
  }
}
}
}
Reference:  java.sun.com\docs\books\performance\1st_edition\html\JPIOPerformance.fm.html 

Rule 29: Avoid_unnecessary_casting

Severity:  High
Rule:  Avoid unnecessary casting.
Reason:  Avoid unnecessary casting.
Usage Example: 
package com.rule;

class Avoid_unnecessary_casting_violation
{
public Object method()
{
String str = "AppPerfect"; //$NON-NLS-1$
Object obj = (Object)str; // VIOLATION
return obj;
}
}
Should be written as:
package com.rule;
class Avoid_unnecessary_casting_correction
{
public Object method()
{
String str = "AppPerfect"; //$NON-NLS-1$
Object obj = str;  // CORRECTION
return obj;
}
}

Rule 30: Avoid_instantiation_of_class_with_only_static_members

Severity:  Medium
Rule:  Avoid instantiation of class with only static members.
Reason:  Avoid instantiation of class with only static members.
Usage Example: 
package com.rule;

public class Avoid_instantiation_of_static_class_violation 
{
MyClassInner mcInner = new MyClassInner();  // Violation
}

class MyClasss
{
public static void foo()
{
}
}
Should be written as:
Avoid instantiation of static classes having only static members.
Reference:  Reference not available. 

Rule 31: Close_jdbc_connections

Severity:  High
Rule:  Always close the database connections opened.
Reason:  Always close the database connections opened.
Usage Example: 
package com.rule;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Close_Jdbc_Connections_violation
{
public void method (String url) throws SQLException
{
try
{
Connection conn = DriverManager.getConnection(url); // VIOLATION
// some operations on connection

}
catch (java.lang.Exception e)
{
e.printStackTrace();
}
}
}
Should be written as:
package com.rule;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Close_Jdbc_Connections_correction
{
public void method (String url) throws SQLException
{
Connection conn = null;
try
{
conn = DriverManager.getConnection(url);
// some operations on connection
}
catch (java.lang.Exception e)
{
e.printStackTrace();
}
finally
{
conn.close(); // CORRECTION
}
}
}
Reference:  Reference not available. 

Rule 32: Close_jdbc_connections_Only_In_finally_Block

Severity:  High
Rule:  Always close the database connections opened. The one of the places to close the connection is in finally block.
Reason:  Always close the database connections opened. The one of the places to close the connection is in finally block.
Usage Example: 
package com.rule;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Close_Jdbc_Connections_only_in_finllay_block_violation
{
public void method (String url) throws SQLException
{
try
{
Connection conn = DriverManager.getConnection(url);
// some operations on connection

conn.close (); // VIOLATION
}
catch (java.lang.Exception e)
{
e.printStackTrace();
}
}
}
Should be written as:
package com.rule;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Close_Jdbc_Connections_only_in_finllay_block_correction
{
public void method (String url) throws SQLException
{
Connection conn = null;
try
{
conn = DriverManager.getConnection(url);
// some operations on connection
}
catch (java.lang.Exception e)
{
e.printStackTrace();
}
finally
{
conn.close(); // CORRECTION
}
}
}
Reference:  Reference not available. 

Rule 33: Avoid_synchronized_readObject_method

Severity:  Medium
Rule:  Avoid synchronized readObject() method.
Reason:  Avoid synchronized readObject() method.
Usage Example: 
package com.rule;

import java.io.Serializable

class Avoid_synchronized_readObject_method implements Serializable
{
private synchronized void readObject(ObjectInputStream s) throws IOException,ClassNotFoundException //Violation
{
 s.defaultReadObject();
   
 // customized deserialization code
}

}
Should be written as:
package com.rule;

import java.io.Serializable

class Avoid_synchronized_readObject_method implements Serializable
{
private void readObject(java.io.ObjectInputStream in)throws IOException, ClassNotFoundException //Correction
{
 s.defaultReadObject();
 
 // customized deserialization code
}

}
Reference:  Reference Not Available 

Rule 34: Avoid_boolean_array

Severity:  Low
Rule:  Do not use array of boolean.
Reason:  Do not use array of boolean.
Usage Example: 
package com.rule;

public class Avoid_boolean_array_violation
{
public void method()
{
boolean[] b = new boolean[]{true, false, true}; // VIOLATION
}
}
Should be written as:
package com.rule;

public class Avoid_boolean_array_correction
{
public void method()
{
BitSet bs = new BitSet(3); // CORRECTION
bs.set(0);
bs.set(2);
}
}

Rule 35: Avoid_string_concatenation_in_loop

Severity:  Critical
Rule:  Use 'StringBuffer' instead of 'String' for non-constant strings.
Reason:  Use 'StringBuffer' instead of 'String' for non-constant strings.
Usage Example: 
package com.rule;
class String_concatenation_violation
{
public void concatValues()
{
String result = "";
for (int i = 0; i < 20; i++) 
{
 result += getNextString(); // VIOLATION
}
}
}
Should be written as:
package com.rule;
class String_concatenation_correction
{
public void concatValues(String strMainString, String strAppend1, String strAppend2)
{
String result = "";
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < 20; i++) 
{
 buffer.append(getNextString()); // CORRECTION
}
result = buffer.toString(); // CORRECTION
}
}

Rule 36: Avoid_method_calls_in_loop

Severity:  High
Rule:  If possible avoid using length(), size() etc. method calls in loop condition statement, there can be a performance hit.
Reason:  If possible avoid using length(), size() etc. method calls in loop condition statement, there can be a performance hit.
Usage Example: 
package com.rule;

class Avoid_method_calls_in_loop_violation
{
public void method()
{
String str = "Hello";
for (int i = 0; i < str.length(); i++) // VIOLATION
   {
i++;
}
}
}
Should be written as:
package com.rule;

class Avoid_method_calls_in_loop_correction
{
public void method()
{
String str = "Hello";
int len = str.length(); // CORRECTION
for (int i = 0; i < len ; i++)
   {
i++;
}
 }
}
Reference:  Reference Not Available. 

Rule 37: Avoid_new_with_string

Severity:  Medium
Rule:  Avoid using new with String objects.
Reason:  Avoid using new with String objects.
Usage Example: 
package com.rule;

class Avoid_new_with_string_violation
{
public int action(String str)
{
String s = new String(str); // VIOLATION
return s.length();
}
}
Should be written as:
package com.rule;

class Avoid_new_with_string_correction
{
public int action(String str)
{
String s = str; // CORRECTION
return s.length();
}
}

Rule 38: Loop_invariant_code_motion

Severity:  Medium
Rule:  The code that is going to result in same value over the iterations of loop, should be moved out of the loop.
Reason:  The code that is going to result in same value over the iterations of loop, should be moved out of the loop.
Usage Example: 
package com.rule;
class Loop_invariant_code_motion_violation
{
public void method(int x, int y, int[] z)
{
for(int i = 0; i < z.length; i++)
{
z[i] = x * Math.abs(y); // VIOLATION
}
}
}
Should be written as:
package com.rule;
class Loop_invariant_code_motion_correction
{
public void method(int x, int y, int[] z)
{
int t1 = x * Math.abs(y); // CORRECTION
for(int i = 0; i < z.length; i++)
{
z[i] = t1;
}
}
}
Reference:  Java Performance Tunning by Jack Shirazi 

Rule 39: Use_short_circuit_boolean_operators

Severity:  High
Rule:  Short-circuit booleans should be used as that speeds up the test slightly in almost every case.
Reason:  Short-circuit booleans should be used as that speeds up the test slightly in almost every case.
Usage Example: 
package com.rule;
class Use_short_circuit_boolean_operators_violation
{
public void method()
{
if(sValue.equals("true")  | sValue.equals("false")) // VIOLATION
{
System.out.println("valid boolean");
}
}
}
Should be written as:
package com.rule;
class Use_short_circuit_boolean_operators_correction
{
public void method()
{
if(sValue.equals("true") || sValue.equals("false")) // CORRECTION
{
System.out.println("valid boolean");
}
}
}
Reference:  Java Performance Tunning by Jack Shirazi
http://java.oreilly.com/news/javaperf_0900.html 

Rule 40: Avoid_using_StringTokenizer

Severity:  Critical
Rule:  Avoid using StringTokenizer to improve performace
Reason:  Avoid using StringTokenizer to improve performace
Usage Example: 
package com.rule;
class Avoid_using_StringTokenizer_violation
{
public void method(String str)
{
StringTokenizer strtok = new StringTokenizer(str); // VIOLATION
while(strtok.hasMoreTokens())
{
System.out.println(strtok.nextToken());
}
}
}
Should be written as:
package com.rule;
class Avoid_using_StringTokenizer_correction
{
public void method(String str)
{
String[] parts = breakUp(str); // CORRECTION
int len = parts.length;
for(int i=len; i>0; i--)
{
System.out.println(parts[len-i]);
}
}

String[] breakUp(String str)
{
String strParts[];
// break the string into parts
return strParts;
}
}

Rule 41: Use_instanceof_only_on_interfaces

Severity:  Medium
Rule:  Use instanceof only on interfaces.
Reason:  Use instanceof only on interfaces.
Usage Example: 
package com.rule;

class MyClass { }

public class Use_instanceof_only_on_interfaces
{
 private void method (Object o)
 {
  if (o instanceof MyClass) { }// VIOLATION
 }
}
Should be written as:
package com.rule;

interface MyInterface {}
class MyClass implements MyInterface {}

public class Use_instanceof_only_on_interfaces
{
 private void method (Object o)
 {
  if (o instanceof MyInterface) { }// Correction
 }
}
Reference:  Reference not available. 

Rule 42: Avoid_null_check_before_instanceof

Severity:  Medium
Rule:  Avoid null check before checking instanceof.
Reason:  Avoid null check before checking instanceof.
Usage Example: 
package com.rule;

public class Avoid_null_check_before_instanceof_violation
{
public void method(Object o)
{
if(o != null &&  o instanceof Object) // Violation.
{
// Do Something.
}
}

}
Should be written as:
package com.rule;

public class Avoid_null_check_before_instanceof_correction
{
public void method(Object o)
{
if(o instanceof Object) // Correction
{
// Do Something.
}
}

}
Reference:  Reference not available. 

Rule 43: Stream_not_closed

Severity:  High
Rule:  Always close the streams opened.
Reason:  Always close the streams opened.
Usage Example: 
package com.rule;

import java.io.FileInputStream;
import java.io.IOException;

public class Stream_not_closed
{
public void method (java.io.File f) throws IOException
{
FileInputStream fileInputStream = null;
try
{
fileInputStream = new java.io.FileInputStream(f); //Violation
fileInputStream.read ();
}
catch (java.io.FileNotFoundException e1)
{
System.out.println("Exception : File not found");
}
}
}
Should be written as:
package com.rule;

import java.io.FileInputStream;
import java.io.IOException;

public class Stream_not_closed
{
public void method (java.io.File f) throws IOException
{
FileInputStream fileInputStream = null;
try
{
fileInputStream = new java.io.FileInputStream(f);
fileInputStream.read ();
fileInputStream.close (); // Correction
}
catch (java.io.FileNotFoundException e1)
{
System.out.println("Exception : File not found");
}
}
}
Reference:  Reference not available. 

Rule 44: Close_streams_only_in_finally

Severity:  High
Rule:  Always close the streams opened, in finally block.
Reason:  Always close the streams opened, in finally block.
Usage Example: 
package com.rule;
import java.io.FileInputStream;
import java.io.IOException;

public class Close_streams_only_in_finally
{
public void method (java.io.File f) throws IOException
{
FileInputStream fileInputStream = null;
try
{
fileInputStream = new java.io.FileInputStream(f);
fileInputStream.read ();
fileInputStream.close (); // VIOLATION
}
catch (java.io.FileNotFoundException e1)
{
System.out.println("Exception : File not found");
}
catch (java.lang.Exception e)
{
e.printStackTrace();
}
}
}
Should be written as:
package com.rule;
import java.io.FileInputStream;
import java.io.IOException;

public class Close_streams_only_in_finally
{
public void method (java.io.File f) throws IOException
{
FileInputStream fileInputStream = null;
try
{
fileInputStream = new java.io.FileInputStream(f);
fileInputStream.read ();

}
catch (java.io.FileNotFoundException e1)
{
System.out.println("Exception : File not found");
}
catch (java.lang.Exception e)
{
e.printStackTrace();
}
finally
{
fileInputStream.close (); // CORRECTION
}
}
}
Reference:  Reference not available. 

Rule 45: Avoid_instantiation_for_getClass

Severity:  High
Rule:  Do not create instances just to call getClass on it.
Reason:  Do not create instances just to call getClass on it.
Usage Example: 
package com.rule;

public class Avoid_instantiation_for_getClass_violation
{
public void method()
{
Class c = (new Avoid_instantiation_for_getClass_violation()).getClass(); // VIOLATION
}
}
Should be written as:
package com.rule;

public class Avoid_instantiation_for_getClass_correction
{
public void method()
{
Class c = Avoid_instantiation_for_getClass_correction.class; // CORRECTION
}
}

Rule 46: Use_System_arrayCopy

Severity:  Critical
Rule:  Use 'System.arraycopy ()' instead of a loop to copy array. This rule disallows the copying of arrays inside a loop
Reason:  Use 'System.arraycopy ()' instead of a loop to copy array. This rule disallows the copying of arrays inside a loop
Usage Example: 
package com.rule;
class Use_System_arrayCopy_violation
{
public int[] copyArray (int[] array)
{
int length = array.length;
int[] copy = new int [length];
for(int i=0;i<length;i++)
{
copy [i] = array[i]; // VIOLATION
}
return copy;
}
}
Should be written as:
package com.rule;
class Use_System_arrayCopy_correction
{
public int[] copyArray (int[] array)
{
final int ZERO = 0;
int length = array.length;
int[] copy = new int [length];
System.arraycopy(array, ZERO, copy, ZERO, length); // CORRECTION
return copy;
}
}

Rule 47: Use_String_length_to_compare_empty_string

Severity:  High
Rule:  The String.equals() method is overkill to test for an empty string. It is quicker to test if the length of the string is 0.
Reason:  The String.equals() method is overkill to test for an empty string. It is quicker to test if the length of the string is 0.
Usage Example: 
package com.rule;
class Use_String_length_to_compare_empty_string_violation
{
public boolean isDocEmpty()
{
return doc.getContents().equals(""); // VIOLATION
}
}
Should be written as:
package com.rule;
class Use_String_length_to_compare_empty_string_correction
{
public boolean isDocEmpty()
{
return doc.getContents().length() == 0; // CORRECTION
}
}

Rule 48: Use_String_equalsIgnoreCase

Severity:  High
Rule:  Use String.equalsIgnoreCase() method.
Reason:  Use String.equalsIgnoreCase() method.
Usage Example: 
package com.rule;

public class Use_String_equalsIgnoreCase_violation
{
public void method()
{
String str = "APPPERFECT";
String str1 = "appperfect";

if(str1.toUpperCase().equals(str)) // Violation
{
System.out.println("Strings are equals");
}
}

}
Should be written as:
package com.rule;

public class Use_String_equalsIgnoreCase_correction
{
public void method()
{
String str = "APPPERFECT";
String str1 = "appperfect";

if(str1.equalsIgnoreCase(str)) // Correction.
{
System.out.println("Strings are equals");
}
}

}
Reference:  Reference not available. 

Rule 49: Place_try_catch_out_of_loop

Severity:  Medium
Rule:  Placing "try/catch/finally" blocks inside loops can slow down the execution of code.
Reason:  Placing "try/catch/finally" blocks inside loops can slow down the execution of code.
Usage Example: 
package com.rule;

import java.io.InputStream;
import java.io.IOException;

class Place_try_catch_out_of_loop_violation
{
void method (InputStream is)
 {
 int ZERO = 0;
 int TEN = 10;
 int count = 0;

 for (int i = ZERO; i < TEN; i++)
 {
 try // VIOLATION
 {
 count += is.read();
 }
 catch (IOException ioe)
 {
  ioe.printStackTrace();
 }
 }
 }
}
Should be written as:
package com.rule;

import java.io.InputStream;
import java.io.IOException;

class Place_try_catch_out_of_loop_correction
{
  void method (InputStream is)
 {
 int ZERO = 0;
 int TEN = 10;
 int count = 0;

 try // CORRECTION
 {
 for (int i = ZERO; i < TEN; i++)
 {
 count += is.read ();
 }
 }
 catch (IOException ioe)
 {
ioe.printStackTrace();
 }
 }
}

Rule 50: Declare_inner_class_static

Severity:  Medium
Rule:  The inner class that doesn't require the outer class reference, should be declared static.
Reason:  The inner class that doesn't require the outer class reference, should be declared static.
Usage Example: 
package com.rule;

public class Declare_inner_class_static_violation
{
class Declare_inner_class_static_violation_INNER // VIOLATION
{
// no reference for Declare_inner_class_static_violation.this or its fields, methods.
}
}
Should be written as:
package com.rule;

public class Declare_inner_class_static_correction
{
static class Declare_inner_class_static_correction_INNER // CORRECTION
{
// no reference for Declare_inner_class_static_correction.this or its fields, methods.
}
}

Rule 51: Declare_inner_class_using_outer_class_only_in_constructor_static

Severity:  Medium
Rule:  The inner class which uses outer class in constructor, should be declared static.
Reason:  The inner class which uses outer class in constructor, should be declared static.
Usage Example: 
package com.rule;

public class Declare_inner_class_using_outer_class_only_in_constructor_static_violation
{
int x = 0;
class Declare_inner_class_using_outer_class_only_in_constructor_static_violation_INNER // VIOLATION
{
int x = 0;
public Declare_inner_class_using_outer_class_only_in_constructor_static_violation_INNER()
{
x = Declare_inner_class_using_outer_class_only_in_constructor_static_violation.this.x;
}
}
}
Should be written as:
package com.rule;

public class Declare_inner_class_using_outer_class_only_in_constructor_static_correction
{
int x = 0;
static class Declare_inner_class_using_outer_class_only_in_constructor_static_correction_INNER // CORRECTION
{
public Declare_inner_class_using_outer_class_only_in_constructor_static_correction_INNER(Declare_inner_class_using_outer_class_only_in_constructor_static_correction outer)
{
this.x = outer.x;
}
}
}
Reference:  Reference not available. 

Rule 52: Avoid_nested_Synchronized_blocks

Severity:  Critical
Rule:  Avoid nested Synchronized blocks to improve performance
Reason:  Avoid nested Synchronized blocks to improve performance
Usage Example: 
package com.rule;
class Avoid_nested_synchronized_blocks_violation
{
public void doTest()
{
//......
synchronized (getClass())
{
//.....
synchronized (this) // VIOLATION
{
//.....
}
//.....
}
//......
}
}
Should be written as:
Avoid nested synchronized blocks.

Rule 53: Avoid_empty_try_blocks

Severity:  Low
Rule:  Avoid empty "try" block structure.
Reason:  Avoid empty "try" block structure.
Usage Example: 
package com.rule;

class Avoid_empty_try_blocks_violation
{
void method (int i, int j)
{
try // VIOLATION
{
}
catch(ArithmeticException ae)
{
i = j;
ae.printStackTrace();
}
}

}
Should be written as:
package com.rule;

class Avoid_empty_try_blocks_correction
{
void method (int i, int j)
{
/*
try // CORRECTION
{
}
catch(ArithmeticException ae)
{
i = j;
ae.printStackTrace();
}
*/
}
}
Reference:  Reference Not Available. 

Rule 54: Declare_accessor_methods_final

Severity:  High
Rule:  Declare accessor methods for instance fields as "final".
Reason:  Declare accessor methods for instance fields as "final".
Usage Example: 
package com.rule;

public class Decalre_accessor_methods_final_violation
{
private String name;
public String getName() // VIOLATION
{
return name;
}
}
Should be written as:
package com.rule;

public class Decalre_accessor_methods_final_correction
{
private String name;
public final String getName() // CORRECTION
{
return name;
}
}

Rule 55: Use_batch_update_for_sql_queries

Severity:  Critical
Rule:  Instead of calling executeUpdate, use executeBatch.
Reason:  Instead of calling executeUpdate, use executeBatch.
Usage Example: 
package com.rule;

import java.sql.Connection;
import java.sql.Statement;

public class Use_batch_update_for_sql_queries_violation
{
public void method(Connection conn) throws Exception
{
String[] queries = new String[] {"query1", "query2", "query3"};
Statement stmt = conn.createStatement();
for (int i = 0; i < queries.length; i++)
{
stmt.executeUpdate(queries[i]); // VIOLATION
}
}
}
Should be written as:
package com.rule;

import java.sql.Connection;
import java.sql.Statement;

public class Use_batch_update_for_sql_queries_correction
{
public void method(Connection conn) throws Exception
{
String[] queries = new String[] {"query1", "query2", "query3"};
Statement stmt = conn.createStatement();
for (int i = 0; i < queries.length; i++)
{
stmt.addBatch(queries[i]); // CORRECTION
}
stmt.executeBatch();
}
}

Rule 56: Declare_private_constant_fields_final

Severity:  Medium
Rule:  A private constant fields should be declared final for performance reasons
Reason:  A private constant fields should be declared final for performance reasons
Usage Example: 
package com.rule;

class Declare_private_constant_fields_final_violation
{
private int i = 5;  // VIOLATION
public void method()
{
int j = i;
j = j + i;
}
}
Should be written as:
package com.rule;

class Declare_private_constant_fields_final_correction
{
private final int i = 5;  // CORRECTION
public void method()
{
int j = i;
j = j + i;
}
}
Reference:  Reference Not Available. 

Rule 57: Always_declare_constant_local_variables_final

Severity:  Medium
Rule:  A constant local variable should be declared final for performance reasons
Reason:  A constant local variable should be declared final for performance reasons
Usage Example: 
public class Test 
{
 private int foo (int x) 
{
int size = 5;  // VIOLATION
   return size + x;
 }
}
Should be written as:
public class Test 
{
 private int foo (int x) 
{
final int size = 5;  // FIXED
   return size + x;
 }
}
Reference:  Not available. 

Rule 58: Reduce_number_of_exception_creations

Severity:  Low
Rule:  Reduce number of exception creations for performace reasons
Reason:  Reduce number of exception creations for performace reasons
Usage Example: 
class Reduce_number_of_exception_creations_violation
{

public static final int TEN = 10;


public void method() throws Exception
{
if(true)
{
throw new Exception("1");
}
if(true)
{
throw new Exception("2");
}
if(true)
{
throw new Exception("3");
}
if(true)
{
throw new Exception("4");
}
if(true)
{
throw new Exception("5");
}
if(true)
{
throw new Exception("6");
}
if(true)
{
throw new Exception("7");
}
if(true)
{
throw new Exception("8");
}
if(true)
{
throw new Exception("9");
}
if(true)
{
throw new Exception("10");
}
if(true)
{
throw new Exception("11");// VIOLATION, it is the 11th exception.
}
}

}
Should be written as:
class Reduce_number_of_exception_creations_correction
{

public static final int TEN = 10;


public void method() throws Exception
{
if(true)
{
throw new Exception("1");
}
if(true)
{
throw new Exception("2");
}
if(true)
{
throw new Exception("3");
}
if(true)
{
throw new Exception("4");
}
if(true)
{
throw new Exception("5");
}
if(true)
{
throw new Exception("6");
}
if(true)
{
throw new Exception("7");
}
if(true)
{
throw new Exception("8");
}
if(true)
{
throw new Exception("9");
}
if(true)
{
throw new Exception("10");
}
// CORRECTION.
}

}

Rule 59: Reduce_switch_density

Severity:  Medium
Rule:  Reduce switch density for performance reasons.
Reason:  Reduce switch density for performance reasons.
Usage Example: 
package com.rule;

public class Reduce_switch_density_violation
{
public void method()
{
switch (x) // Violation.
{
 case 1:
 {
 if(status)
 {
// More Statements
 }
    break;
 }
 case 2:
 {
    // More Statements    
break;
 }
 default :
 {
 
 }
}
}

}
Should be written as:
package com.rule;

public class Reduce_switch_density_correction
{
public void method()
{
switch (x) //Correction.
{
 case 1:
 {
 if(status)
 {
method1();
 }
    break;
 }
 case 2:
 {
method2();
   
break;
 }
 default :
 {
 
 }
}
i--;
}
public method1()
{
// Do Something.
}
public method2()
{
// Do Something.
}


}
Reference:  Reference not available. 

Rule 60: Avoid_empty_loops

Severity:  Low
Rule:  Avoid empty loops.
Reason:  Avoid empty loops.
Usage Example: 
package com.rule;

class Avoid_empty_loops_violation
{
public void method()
{
int i = -5;
final int ZERO = 0;
final int NEGATIVE = -1;

while (i < ZERO) // VIOLATION
{
}

i = NEGATIVE;

for(;i < ZERO;) // VIOLATION
{
}
}
}
Should be written as:
package com.rule;

class Avoid_empty_loops_correction
{

public void method()
{
int i = -5;
final int ZERO = 0;
final int NEGATIVE = -1;

/*
while (i < ZERO) // CORRECTION
{
}
*/

i = NEGATIVE;

/*
for(;i < ZERO;) // CORRECTION
{
}
*/
}
}
Reference:  Reference Not Available. 

Rule 61: Avoid_new_Integer_toString

Severity:  High
Rule:  Avoid creating objects of primitive types to call the toString() method instead use valueOf(...) in String class to convert primitive types into their String equivalent.
Reason:  Avoid creating objects of primitive types to call the toString() method instead use valueOf(...) in String class to convert primitive types into their String equivalent.
Usage Example: 
package com.rule;

class Avoid_new_Integer_toString_violation
{
public void print()
{
String str = new Integer(1).toString(); // VIOLATION
}
}
Should be written as:
package com.rule;

class Avoid_new_Integer_toString_correction
{
public void print()
{
String str = String.valueOf(1); // CORRECTION
}
}
Reference:  Reference Not Available. 

Rule 62: Avoid_passing_primitive_int_to_Integer_constructor

Severity:  High
Rule:  Avoid creating objects of primitive types using the constructor.
Reason:  Avoid creating objects of primitive types using the constructor.
Usage Example: 
public class Test
{
public void fubar()
{
Integer i = new Integer(3); // VIOLATION
//...
}
}
Should be written as:
public class Test
{
public void fubar()
{
Integer i = Integer.valueOf(3); // FIXED
//...
}
}
Reference:  Not Available. 

Rule 63: Avoid_passing_primitive_long_to_Long_constructor

Severity:  High
Rule:  Avoid creating objects of primitive types using the constructor.
Reason:  Avoid creating objects of primitive types using the constructor.
Usage Example: 
public class Test
{
public void fubar()
{
Long i = new Long(3); // VIOLATION
//...
}
}
Should be written as:
public class Test
{
public void fubar()
{
Long i = Long.valueOf(3); // FIXED
//...
}
}
Reference:  Not Available. 

Rule 64: Avoid_passing_primitive_double_to_Double_constructor

Severity:  High
Rule:  Avoid creating objects of primitive types using the constructor.
Reason:  Avoid creating objects of primitive types using the constructor.
Usage Example: 
public class Test
{
public void fubar()
{
Double i = new Double(3.0); // VIOLATION
//...
}
}
Should be written as:
public class Test
{
public void fubar()
{
Double i = Double.valueOf(3.0); // FIXED
//...
}
}
Reference:  Not Available. 

Rule 65: Avoid_passing_primitive_short_to_Short_constructor

Severity:  High
Rule:  Avoid creating objects of primitive types using the constructor.
Reason:  Avoid creating objects of primitive types using the constructor.
Usage Example: 
public class Test
{
public void fubar()
{
Short i = new Short(3); // VIOLATION
//...
}
}
Should be written as:
public class Test
{
public void fubar()
{
Short i = Short.valueOf(3); // FIXED
//...
}
}
Reference:  Not Available. 

Rule 66: Avoid_passing_primitive_byte_to_Byte_constructor

Severity:  High
Rule:  Avoid creating objects of primitive types using the constructor.
Reason:  Avoid creating objects of primitive types using the constructor.
Usage Example: 
public class Test
{
public void fubar()
{
Byte i = new Byte(3); // VIOLATION
//...
}
}
Should be written as:
public class Test
{
public void fubar()
{
Byte i = Byte.valueOf(3); // FIXED
//...
}
}
Reference:  Not Available. 

Rule 67: Avoid_passing_primitive_char_to_Character_constructor

Severity:  High
Rule:  Avoid creating objects of primitive types using the constructor.
Reason:  Avoid creating objects of primitive types using the constructor.
Usage Example: 
public class Test
{
public void fubar()
{
Character i = new Character('a'); // VIOLATION
//...
}
}
Should be written as:
public class Test
{
public void fubar()
{
Character i = Character.valueOf('a'); // FIXED
//...
}
}
Reference:  Not Available. 

Rule 68: Avoid_using_String_toString

Severity:  High
Rule:  Avoid calling toString() on Strings.Instead use String.
Reason:  Avoid calling toString() on Strings.Instead use String.
Usage Example: 
package com.rule;

class Avoid_using_String_toString
{
public void print()
{
String str="AppPerfect";

System.out.println(str.toString()); // Violation.
}
}
Should be written as:
package com.rule;

class Avoid_using_String_toString
{
public void print()
{
String str="AppPerfect";

System.out.println(str); // Correction
}
}
Reference:  Reference Not Available. 

Rule 69: Avoid_unnecessary_substring

Severity:  High
Rule:  Avoid using String.substring(0).
Reason:  Avoid using String.substring(0).
Usage Example: 
package com.rule;

public class Avoid_unnecessary_substring_violation
{
public void method()
{
String str="AppPerfect";

String str1 = str.substring(0); // Violation.
}

}
Should be written as:
package com.rule;

public class Avoid_unnecessary_substring_correction
{
public void method()
{
String str="AppPerfect";

String str1 = str; //Correction.
}

}
Reference:  Reference not available. 

Rule 70: Use_toArray_with_array_as_parameter

Severity:  High
Rule:  Use toArray(Object[] ) instead of toArray() on collection.
Reason:  Use toArray(Object[] ) instead of toArray() on collection.
Usage Example: 
package com.rule;

import java.util.Collection;
import java.util.List;
import java.util.ArrayList;

class Use_toArray_with_array_as_parameter
{
public void print()
{
Collection c = new ArrayList();

c.add("AppPerfect");
c.add("TestStudio");

Object[] obj  = c.toArray(); // Violation
}
}
Should be written as:
package com.rule;

import java.util.Collection;
import java.util.List;
import java.util.ArrayList;

class Use_toArray_with_array_as_parameter
{
public void print()
{
Collection c = new ArrayList();

c.add("AppPerfect");
c.add("TestStudio");

String[] x = (String[]) c.toArray(new String[2]); //Correction
}
}
Reference:  Reference Not Available. 

Rule 71: Do_lazy_initialization

Severity:  High
Rule:  Do Lazy initialization.
Reason:  Do Lazy initialization.
Usage Example: 
package com.rule;

public class Do_lazy_initialization_violation
{
private Do_lazy_initialization_violation  instance  =  new Do_lazy_initialization_violation();  //Violation

}
Should be written as:
package com.rule;

public class Do_lazy_initialization_correction
{
private Do_lazy_initialization_violation instance;

public Do_lazy_initialization_violation getInstance()
{
if(doLazy == null)
instance  =  new Do_lazy_initialization_violation();  // Correction
return instance;
}

}

Rule 72: Avoid_using_Thread_yield

Severity:  Medium
Rule:  Avoid using Thread.yield().
Reason:  Avoid using Thread.yield().
Usage Example: 
package com.rule;
public class Avoid_using_Thread_yield_violation
{
public void method()
{
//......
Thread.yield(); // VIOLATION
//......
}
}
Should be written as:
package com.rule;
public class Avoid_using_Thread_yield_correction
{
public void method()
{
//......
this.wait(); // CORRECTION
//......
}
}

Rule 73: Avoid_unread_fields

Severity:  Medium
Rule:  Avoid unread fields.
Reason:  Avoid unread fields.
Usage Example: 
package com.rule;

public class Avoid_unread_fields_violation
{
private static String name = "AppPerfect"; //Violation.
private static int i = 10;

public static void method()
{
name = "AppPerfect USA";
System.out.println(i);
}

}
Should be written as:
Reference:  Reference not available. 

Rule 74: Avoid_equality_with_boolean

Severity:  Medium
Rule:  Avoid comparing a boolean with "true".
Reason:  Avoid comparing a boolean with "true".
Usage Example: 
package com.rule;

class Avoid_equality_with_boolean_violation
{
boolean method(String value)
{
boolean b = false;
String str = "S";

if (value.endsWith(str) == true) // VIOLATION
{
b = true;
}

return b;
}
}
Should be written as:
package com.rule;

class Avoid_equality_with_boolean_correction
{
boolean method(String value)
{
boolean b = false;
String str = "S";
//....
//........
if ( value.endsWith(str) ) // CORRECTION
{
b = true;
}

return b;
}
}
Reference:  Reference Not Available. 

Rule 75: Avoid_startsWith

Severity:  Critical
Rule:  Avoid calling String.startsWith() for performance reasons
Reason:  Avoid calling String.startsWith() for performance reasons
Usage Example: 
package com.rule;
class Avoid_startsWith_violation
{
public void method()
{
String sTemp="Data";
if (sTemp.startsWith("D")) // VIOLATION
{
sTemp = "data";
}
}
}
Should be written as:
package com.rule;

class Avoid_startsWith_correction
{
public void method()
{
final int ZERO = 0;
final char D = 'D';
String sTemp="Data"; 

if (sTemp.length () > ZERO && sTemp.charAt(ZERO) == D)  // CORRECTION
{
sTemp = "data"; 
}
}
}

Rule 76: Avoid_readByte_method_in_loop

Severity:  High
Rule:  Avoid reading single byte in loop
Reason:  Avoid reading single byte in loop
Usage Example: 
package com.rule;

class Avoid_readByte_method_in_loop_violation
{
public static void main(String args[])
{
String strFilePath = "c:\temp.java"; //$NON-NLS-1$
final int ZERO = 0;
final int TEN = 10;

try
{

java.io.FileInputStream fis = new java.io.FileInputStream(strFilePath);
java.io.DataInputStream ds = new java.io.DataInputStream(fis);

int i = ZERO;
while(i < TEN)
{
ds.readByte(); // VIOLATION
i++;
}

for(i=ZERO; i<TEN; i++)
{
ds.readByte(); // VIOLATION
}

i = ZERO;

do
{
ds.readByte(); // VIOLATION
i++;
}
while(i<TEN);
}
catch(java.io.IOException e)
{
e.printStackTrace();
}
}
}
Should be written as:
package com.rule;

class Avoid_readByte_method_in_loop_correction
{
public static void main(String args[])
{

final int TEN = 10;
byte bArr[] = new byte[TEN];
String strFilePath = "c:\temp.java"; //$NON-NLS-1$

try
{
java.io.FileInputStream fis = new java.io.FileInputStream(strFilePath);
java.io.DataInputStream ds = new java.io.DataInputStream(fis);

ds.read(bArr); // CORRECTION

}
catch(java.io.IOException e)
{
e.printStackTrace();
}
}
}
Reference:  Reference Not Available. 

Rule 77: Avoid_instantiation_of_boolean

Severity:  High
Rule:  Avoid instantiation of Boolean instead use the static constants defined in Boolean class.
Reason:  Avoid instantiation of Boolean instead use the static constants defined in Boolean class.
Usage Example: 
package com.rule;

class Avoid_instantiation_of_boolean_violation
{
public Boolean method()
{
Boolean b = new Boolean(true); // VIOLATION
return b;
}
}
Should be written as:
package com.rule;

class Avoid_instantiation_of_boolean_correction
{
public Boolean method()
{
Boolean b = Boolean.TRUE; // CORRECTION
return b;
 }
}
Reference:  Reference Not Available. 

Rule 78: Avoid_Synchronized_blocks

Severity:  Critical
Rule:  Do not use synchronized blocks to avoid synchronization overheads
Reason:  Do not use synchronized blocks to avoid synchronization overheads
Usage Example: 
package com.rule;
class Avoid_synchronized_blocks_violation
{
public void doTest()
{
synchronized (getClass()) // VIOLATION
{
//.....
}
}
}
Should be written as:
package com.rule;

class Avoid_synchronized_blocks_correction
{
public synchronized void doTest() // CORRECTION
{
//.....
}

}

Rule 79: Declare_package_private_method_final

Severity:  Medium
Rule:  A package-private method that is not overridden should be declared final.
Reason:  A package-private method that is not overridden should be declared final.
Usage Example: 
package com.rule;

class Declare_package_private_method_final_violation
{
void method() // VIOLATION
{
}
}
Should be written as:
package com.rule;

class Declare_package_private_method_final_correction
{
final void method() // CORRECTION
{
}
}

Rule 80: Declare_public_or_protected_method_final

Severity:  Medium
Rule:  It optimizes the code and makes the code self documenting.
Reason:  It optimizes the code and makes the code self documenting.
Usage Example: 
class Declare_public_or_protected_method_final_violation
{
public void method() // VIOLATION
{
}
}
Should be written as:
class Declare_public_or_protected_method_final_correction
{
public final void method() // CORRECTION
{
}
}

Rule 81: Declare_public_or_protected_class_final

Severity:  Medium
Rule:  It optimizes the code and makes the code self documenting.
Reason:  It optimizes the code and makes the code self documenting.
Usage Example: 
public class Test // VIOLATION
{
public void fubar()
{
//....
}
}
Should be written as:
public final class Test // FIXED
{
public void fubar()
{
//....
}
}

Rule 82: Use_array_of_primitive_type_insteadof_collection

Severity:  Medium
Rule:  Instead of using some 'Collection' for wrapper classes of primitive types, use arrays of primitive types.
Reason:  Instead of using some 'Collection' for wrapper classes of primitive types, use arrays of primitive types.
Usage Example: 
package com.rule;

import java.util.Vector;

public class Use_array_of_primitive_type_insteadof_collection_violation
{
public void method()
{
Vector vInt = new Vector(); // VIOLATION
vInt.add(new Integer(1));
vInt.add(new Integer(2));
vInt.add(new Integer(3));
}
}
Should be written as:
package com.rule;

public class Use_array_of_primitive_type_insteadof_collection_correction
{
public void method()
{
int[] arrInt = new int[3]; // CORRECTION
arrInt[0] = 1;
arrInt[1] = 2;
arrInt[2] = 3;
}
}
Reference:  No reference available. 

Rule 83: Avoid_using_Double_toString

Severity:  High
Rule:  Avoid using Double toString for performance reasons
Reason:  Avoid using Double toString for performance reasons
Usage Example: 
package com.rule;
class Avoid_using_Double_toString_violation
{
public void method(double d)
{
String dStr = Double.toString(d); // VIOLATION
System.out.println(dStr);
}
}
Should be written as:
Avoid Using Double.toString() instead use custom conversion algorithm.

Rule 84: Avoid_debugging_code

Severity:  Low
Rule:  Avoid debugging code.
Reason:  Avoid debugging code.
Usage Example: 
package com.rule;

public void Avoid_debugging_code_violation
{
private int count =0;
public int getCount()
{
//...
System.out.println("count ="+count);  // Violation
return count;
}
}
Should be written as:
package com.rule;

public void Avoid_debugging_code_correction
{
private int count =0;
public int getCount()
{
if (Debug.ON) 
{
System.out.println("count ="+count);  //correction
}
return count;
}
}

Rule 85: Avoid_using_Thread_dumpStack

Severity:  Low
Rule:  Avoid using Thread.dumpStack() in production code since it is typically associated at the time of manual profiling activities.
Reason:  Avoid using Thread.dumpStack() in production code since it is typically associated at the time of manual profiling activities.
Usage Example: 
public class Test 
{
public static void main( String[] args ) 
{
for ( int i = 0; i < args.length; i++ ) 
{
System.out.println( args[ i ] );
}
Thread.dumpStack(); // VIOLATION
}
}
Should be written as:
Use some profiling tool instead.
Reference:  No references available. 

Rule 86: Avoid_using_java_lang_Runtime_freeMemory

Severity:  Low
Rule:  Avoid using java.lang.Runtime.freeMemory() in production code since it is typically associated at the time of manual profiling activities.
Reason:  Avoid using java.lang.Runtime.freeMemory() in production code since it is typically associated at the time of manual profiling activities.
Usage Example: 
public class Test 
{
public static void main(String[] args) 
{
System.out.println( Runtime.getRuntime().freeMemory() ); // VIOLATION
int[] values = new int[ args.length ];
for ( int i = 0; i < values.length; i++ ) 
{
values[ i ] = Integer.parseInt( args[ i ] );
}
System.out.println( Runtime.getRuntime().freeMemory() ); // VIOLATION
}
}
Should be written as:
Use some profiling tool instead.
Reference:  No references available. 

Rule 87: Avoid_using_java_lang_Runtime_totalMemory

Severity:  Low
Rule:  Avoid using java.lang.Runtime.totalMemory() in production code since it is typically associated at the time of manual profiling activities.
Reason:  Avoid using java.lang.Runtime.totalMemory() in production code since it is typically associated at the time of manual profiling activities.
Usage Example: 
public class Test 
{
public static void main(String[] args) 
{
System.out.println( Runtime.getRuntime().totalMemory() ); // VIOLATION
int[] values = new int[ args.length ];
for ( int i = 0; i < values.length; i++ ) 
{
values[ i ] = Integer.parseInt( args[ i ] );
}
System.out.println( Runtime.getRuntime().totalMemory() ); // VIOLATION
}
}
Should be written as:
Use some profiling tool instead.
Reference:  No references available. 

Rule 88: Avoid_using_java_lang_Runtime_traceInstructions

Severity:  Low
Rule:  Avoid using java.lang.Runtime.traceInstructions(boolean on) in production code since it is typically associated at the time of manual profiling activities.
Reason:  Avoid using java.lang.Runtime.traceInstructions(boolean on) in production code since it is typically associated at the time of manual profiling activities.
Usage Example: 
public class Test 
{
public static void main(String[] args) 
{
Runtime.getRuntime().traceInstructions(true); // VIOLATION
traced();
}

private static void traced() 
{
System.out.println( "Traced" );  //$NON-NLS-1$
}

}
Should be written as:
Use some profiling tool instead.
Reference:  No references available. 

Rule 89: Avoid_using_java_lang_Runtime_traceMethodCalls

Severity:  Low
Rule:  Avoid using java.lang.Runtime.traceMethodCalls(boolean on) in production code since it is typically associated at the time of manual profiling activities.
Reason:  Avoid using java.lang.Runtime.traceMethodCalls(boolean on) in production code since it is typically associated at the time of manual profiling activities.
Usage Example: 
public class Test 
{
public static void main(String[] args) 
{
Runtime.getRuntime().traceMethodCalls(true); // VIOLATION
traced();
}

private static void traced() 
{
System.out.println( "Traced" );  //$NON-NLS-1$
}

}
Should be written as:
Use some profiling tool instead.
Reference:  No references available. 

Rule 90: Avoid_using_java_lang_Class_getMethod

Severity:  Low
Rule:  Instead of hardcoding the method name, directly invoking the method would improve performance and reduce the chances of possible bugs.
Reason:  Instead of hardcoding the method name, directly invoking the method would improve performance and reduce the chances of possible bugs.
Usage Example: 
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test 
{
public static void main(String[] args)
{
try 
{
Method method = GetMethod.class.getMethod( "setValue", new Class[] { int.class } ); // VIOLATION  //$NON-NLS-1$
GetMethod obj = new GetMethod();
method.invoke( obj, new Object[] {new Integer(1)} );
System.out.println( obj.getValue() );
}
catch (IllegalAccessException e) 
{
System.out.println( "Can't access private method 'getValue'"); //$NON-NLS-1$

catch (InvocationTargetException e1) 
{
System.out.println( "Problem calling method" ); //$NON-NLS-1$

catch (NoSuchMethodException e2) 
{
System.out.println( "No method getValue"); //$NON-NLS-1$
}
}
}

class GetMethod
{
public void setValue( int value ) 
{
this.value = value;
}

public int getValue() 
{
return value;
}

private int value;
}
Should be written as:
public class Test 
{
public static void main(String[] args)
{
GetMethod obj = new GetMethod();
obj.setValue(1); // CORRECTION
System.out.println( obj.getValue() );
}
}

class GetMethod
{
public void setValue( int value ) 
{
this.value = value;
}

public int getValue() 
{
return value;
}

private int value;
}
Reference:  No references available. 

Rule 91: Avoid_using_java_lang_Class_getField

Severity:  Low
Rule:  Instead of hardcoding the field name, directly accessing the field would improve performance and reduce the chances of possible bugs.
Reason:  Instead of hardcoding the field name, directly accessing the field would improve performance and reduce the chances of possible bugs.
Usage Example: 
import java.lang.reflect.Field;


public class Test 
{

public static void main(String[] args)
{
try 
{
Field field = GetField.class.getField( "value" );  // VIOLATION //$NON-NLS-1$
GetField obj = new GetField();
field.set( obj, new Integer( 1 ) );
System.out.println( obj.getValue() );

catch (SecurityException e) 
{
System.out.println( "Can't access field 'value'"); //$NON-NLS-1$

catch (NoSuchFieldException e1) 
{
System.out.println( "No field 'value'"); //$NON-NLS-1$

catch (IllegalArgumentException e2) 
{
System.out.println( e2.getMessage() );

catch (IllegalAccessException e3) 
{
System.out.println( "Can't access private field 'value'" ); //$NON-NLS-1$
}
}

}


class GetField
{
public int value;

public void setValue( int value ) 
{
this.value = value;
}

public int getValue() 
{
return value;
}

}
Should be written as:
public class Test 
{

public static void main(String[] args)
{
GetField obj = new GetField();
obj.setValue(1);
System.out.println( obj.getValue() );
}

}


class GetField
{
public int value;

public void setValue( int value ) 
{
this.value = value;
}

public int getValue() 
{
return value;
}

}
Reference:  No references available. 

Rule 92: Avoid_using_java_lang_Class_getDeclaredMethod

Severity:  Low
Rule:  Instead of hardcoding the method name, directly invoking the method would improve performance and reduce the chances of possible bugs.
Reason:  Instead of hardcoding the method name, directly invoking the method would improve performance and reduce the chances of possible bugs.
Usage Example: 
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test 
{
public static void main(String[] args)
{
try 
{
Method method = GetMethod.class.getDeclaredMethod( "setValue", new Class[] { int.class } ); // VIOLATION  //$NON-NLS-1$
GetMethod obj = new GetMethod();
method.invoke( obj, new Object[] {new Integer(1)} );
System.out.println( obj.getValue() );
}
catch (IllegalAccessException e) 
{
System.out.println( "Can't access private method 'getValue'"); //$NON-NLS-1$

catch (InvocationTargetException e1) 
{
System.out.println( "Problem calling method" ); //$NON-NLS-1$

catch (NoSuchMethodException e2) 
{
System.out.println( "No method getValue"); //$NON-NLS-1$
}
}
}

class GetMethod
{
public void setValue( int value ) 
{
this.value = value;
}

public int getValue() 
{
return value;
}

private int value;
}
Should be written as:
public class Test 
{
public static void main(String[] args)
{
GetMethod obj = new GetMethod();
obj.setValue(1); // CORRECTION
System.out.println( obj.getValue() );
}
}

class GetMethod
{
public void setValue( int value ) 
{
this.value = value;
}

public int getValue() 
{
return value;
}

private int value;
}
Reference:  No references available. 

Rule 93: Avoid_using_java_lang_Class_getDeclaredField

Severity:  Low
Rule:  Instead of hardcoding the field name, directly accessing the field would improve performance and reduce the chances of possible bugs.
Reason:  Instead of hardcoding the field name, directly accessing the field would improve performance and reduce the chances of possible bugs.
Usage Example: 
import java.lang.reflect.Field;

public class Test 
{

public static void main(String[] args)
{
try 
{
Field field = GetField.class.getDeclaredField( "value" );  // VIOLATION //$NON-NLS-1$
GetField obj = new GetField();
field.set( obj, new Integer( 1 ) );
System.out.println( obj.getValue() );

catch (SecurityException e) 
{
System.out.println( "Can't access field 'value'"); //$NON-NLS-1$

catch (NoSuchFieldException e1) 
{
System.out.println( "No field 'value'"); //$NON-NLS-1$

catch (IllegalArgumentException e2) 
{
System.out.println( e2.getMessage() );

catch (IllegalAccessException e3) 
{
System.out.println( "Can't access private field 'value'" ); //$NON-NLS-1$
}
}

}


class GetField
{
public int value;

public void setValue( int value ) 
{
this.value = value;
}

public int getValue() 
{
return value;
}

}
Should be written as:
public class Test 
{

public static void main(String[] args)
{
GetField obj = new GetField();
obj.setValue(1);
System.out.println( obj.getValue() );
}

}


class GetField
{
public int value;

public void setValue( int value ) 
{
this.value = value;
}

public int getValue() 
{
return value;
}

}
Reference:  No references available. 

Rule 94: Always_Access_Fields_In_Same_Class_Directly

Severity:  Medium
Rule:  Avoid accessing fields in the same class through accessor methods.
Reason:  Avoid accessing fields in the same class through accessor methods.
Usage Example: 
class Always_Access_Fields_In_SameClass_Directly_Violation
{
boolean bModified = false;

public boolean isModified()
{
return bModified;
}

public void save()
{
if (isModified()) //violation
{
//..save
}
}
}
Should be written as:
class Always_Access_Fields_In_SameClass_Directly_Correction
{
boolean bModified = false;

public boolean isModified()
{
return bModified;
}

public void save()
{
if (bModified) //correction
{
//..save
}
}
}
Reference:  No reference 

Rule 95: Use_arrayList_inplace_of_vector

Severity:  Medium
Rule:  Use 'ArrayList' in place of 'Vector' wherever possible ArrayList is faster than Vector except when there is no lock acquisition required in HotSpot JVMs (when they have about the same performance)
Reason:  Use 'ArrayList' in place of 'Vector' wherever possible ArrayList is faster than Vector except when there is no lock acquisition required in HotSpot JVMs (when they have about the same performance)
Usage Example: 
package com.rule;
import java.util.Vector;

class Use_arrayList_inplace_of_vector_violation
{
  final int SIZE = 10;
  private Vector v = new Vector(SIZE); // VIOLATION

  public int method()
  {
  return v.size();
 }
}
Should be written as:
package com.rule;
import java.util.ArrayList;
class Use_arrayList_inplace_of_vector_correction
{
final int SIZE = 10;
private ArrayList al = new ArrayList(SIZE); // CORRECTION

public int method()
{
return al.size();
}
}

Rule 96: Avoid_unnecessary_exception_throwing

Severity:  Low
Rule:  Avoid unnecessary exception throwing for performance reasons
Reason:  Avoid unnecessary exception throwing for performance reasons
Usage Example: 
class Avoid_unnecessary_exception_throwing_violation
{
public void method() throws java.io.IOException // VIOLATION
{
// no code that throws IOException
}
}
Should be written as:
class Avoid_unnecessary_exception_throwing_correction
{
public void method() // CORRECTION
{
// no code that throws IOException
}
}
Reference:  Reference Not Available. 

Rule 97: Avoid_LinkedLists

Severity:  High
Rule:  Avoid LinkedLists instead use Vector / ArrayList as LinkedList implementation has a performance overhead for indexed access.
Reason:  Avoid LinkedLists instead use Vector / ArrayList as LinkedList implementation has a performance overhead for indexed access.
Usage Example: 
package com.rule;

import java.util.LinkedList; // VIOLATION

class Avoid_LinkedLists_violation
{
public void method()
{
LinkedList list = new LinkedList();
if(list != null)
{
list = null;
}
}
}
Should be written as:
package com.rule;

import java.util.ArrayList; // CORRECTION

class Avoid_LinkedLists_correction
{
public void method()
{
 final int SIZE = 10;
 ArrayList list = new ArrayList(SIZE);

 if(list != null)
 {
  list = null;
 }
}
}
Reference:  www.onjava.com/pub/a/onjava/2001/05/30/optimization.html 

Rule 98: Use_single_quotes_when_concatenating_character_to_String

Severity:  Medium
Rule:  Use single quotes instead of double qoutes when concatenating single character to a String.
Reason:  Use single quotes instead of double qoutes when concatenating single character to a String.
Usage Example: 
package com.rule;
public class Use_single_quotes_when_concatenating_character_to_String_violation
{
Use_single_quotes_when_concatenating_character_to_String_violation()
{
String s = "a";
s = s + "a"; // VIOLATION
}
}
Should be written as:
package com.rule;
public class Use_single_quotes_when_concatenating_character_to_String_correction
{
Use_single_quotes_when_concatenating_character_to_String_correction()
{
String s = "a";
s = s + 'a'; // CORRECTION
}
}
Reference:  Reference Not Available. 

Rule 99: Use_PreparedStatement_instead_of_Statement

Severity:  High
Rule:  PreparedStatements should be used where dynamic queries are involved.
Reason:  PreparedStatements should be used where dynamic queries are involved.
Usage Example: 
package com.rule;

import java.sql.Connection;
import java.sql.Statement;

public class Use_PreparedStatement_instead_of_Statement_violation
{
public void method(Connection conn) throws Exception
{
Statement stmt = conn.createStatement();
for (int i = 0; i < empCount; i++)
{
String sQry = "SELECT * FROM employee WHERE id = " + i;
ReultSet rs = stmt.execute(sQry);
//...
}
}
}
Should be written as:
package com.rule;

import java.sql.Connection;
import java.sql.PreparedStatement;

public class Use_PreparedStatement_instead_of_Statement_correction
{
public void method(Connection conn) throws Exception
{
String sQry = "SELECT * FROM employee WHERE id = ?";
PreparedStatement pstmt = con.prepareStatement(sQry);
for (int i = 0; i < empCount; i++)
{
pstmt.setString(1,""+i);
ResultSet rs = pstmt.executeQuery();
//...
}
}
}

Rule 100: Avoid_multi_dimensional_arrays

Severity:  Medium
Rule:  Try to use single dimensional arrays inplace of multidimensional arrays.
Reason:  Try to use single dimensional arrays inplace of multidimensional arrays.
Usage Example: 
package com.rule;

public class Aviod_multidimensional_arrays_violation
{
public void method1(int[][] values) // VIOLATION
{
for (int i = 0; i < values.length; i++)
{
System.out.println(values[i][0] + ":" + values[i][1]);
}
}

public void method2()
{
int[][] arr = new int[][]{ // VIOLATION
{1,2},
{2,4},
{3,6},
{4,8}
};
method1(arr);
}
}
Should be written as:
package com.rule;

public class Aviod_multidimensional_arrays_correction
{
public void method1(int[] values1, int[] values2) // CORRECTION
{
for (int i = 0; i < values1.length; i++)
{
System.out.println(values1[i] + ":" + values2[i]);
}
}

public void method2()
{
int[] arr1 = new int[]{1,2,3,4}; // CORRECTION
int[] arr2 = new int[]{2,4,6,8}; // CORRECTION
method1(arr1, arr2);
}
}

Rule 101: Avoid_empty_synchronized_block

Severity:  Low
Rule:  Remove empty synchronized blocks to avoid unnecessary overheads
Reason:  Remove empty synchronized blocks to avoid unnecessary overheads
Usage Example: 
package com.rule;

class Avoid_empty_synchronized_block_violation
{
void method()
{
synchronized(this)
{
}
}
}
Should be written as:
package com.rule;

class Avoid_empty_synchronized_block_violation
{
void method()
{
/*
synchronized(this)
{
}
*/
}
}
Reference:  Reference Not Available. 

Rule 102: Use_DataSource_instead_of_DriverManager

Severity:  High
Rule:  Using DataSource is a preferred way for obtaining the Connection objects.
Reason:  Using DataSource is a preferred way for obtaining the Connection objects.
Usage Example: 
package com.rule;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Use_DataSource_instead_of_DriverManager_violation
{
public void method(String url) throws SQLException
{
Connection conn = DriverManager.getConnection(url); // VIOLATION
// use conn
}

public void initDriverManager()
{
// load driver class
}
}
Should be written as:
package com.rule;

import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;

class Use_DataSource_instead_of_DriverManager_correction
{
DataSource ds;

public void method() throws SQLException
{
Connection conn = ds.getConnection(); // CORRECTION
// use conn
}

public void initDataSource()
{
// initialize ds
}
}

Rule 103: Avoid_call_to_Thread.sleep()

Severity:  Critical
Rule:  Do not call Thread.sleep() for performance reasons
Reason:  Do not call Thread.sleep() for performance reasons
Usage Example: 
package com.rule;
class Avoid_call_to_Thread_sleep_violation
{
public void doTest() throws InterruptedException
{
//......
Thread.sleep(100); // VIOLATION
//......
}
}
Should be written as:
package com.rule;
class Avoid_call_to_Thread_sleep_correction
{
public void doTest()
{
//......
this.wait(100); // CORRECTION
//......
}
}
Reference:  Reference Not Available. 

Rule 104: Use_String_instead_StringBuffer_for_constant_strings

Severity:  Critical
Rule:  Use String instead of StringBuffer for constant Strings
Reason:  Use String instead of StringBuffer for constant Strings
Usage Example: 
package com.rule;

class Use_String_instead_StringBuffer_for_constant_strings_violation
{
public String getSign(int i)
{
final StringBuffer even = new StringBuffer("EVEN"); // violation
final StringBuffer odd = new StringBuffer("ODD"); // violation
final StringBuffer msg = new StringBuffer("The number is ");
if ((i / 2)*i == i)
{
msg.append(even);
}
else
{
msg.append(odd);
}
return msg.toString();
}
}
Should be written as:
package com.rule;

class Use_String_instead_StringBuffer_for_constant_strings_correction
{
public String getSign(int i)
{
final String even = "EVEN";   // correction
final String odd = "ODD";   // correction
final StringBuffer msg = new StringBuffer("The number is ");
if ((i / 2)*i == i)
{
msg = msg.append(even);
}
else
{
msg.append(odd);
}
return msg.toString();
}
}

Rule 105: Avoid_using_String_charAt

Severity:  High
Rule:  Use char[] representation of the string instead of using String.charAt().
Reason:  Use char[] representation of the string instead of using String.charAt().
Usage Example: 
package com.rule;
class Avoid_using_String_charAt_violation
{
public void method(String str)
{
for(int i=0; i<str.length(); i++)
{
System.out.println(str.charAt(i)); // VIOLATION
}
}
}
Should be written as:
package com.rule;
class Avoid_using_String_charAt_correction
{
public void method(String str)
{
char[] carr = str.toCharArray(); // CORRECTION
for(int i=0; i<carr.length; i++)
{
System.out.println(carr[i]); // CORRECTION
}
}
}
Reference:  ftp://ftp.glenmccl.com/pub/free/jperf.pdf
http://www.javaperformancetuning.com/tips/rawtips.shtml 

Rule 106: Avoid_Extending_java_lang_Object

Severity:  Low
Rule:  Avoid empty "finally" block structure.
Reason:  Avoid empty "finally" block structure.
Usage Example: 
package com.rule;

class Avoid_empty_finally_blocks_violation
{
void method (int i)
{
final int ZERO =0;
try
{
i = ZERO;
}
catch(ArithmeticException ae)
{
ae.printStackTrace();
}
finally // VIOLATION
{
}
}
}
Should be written as:
package com.rule;

class Avoid_empty_finally_blocks_correction
{
void method (int i)
{
final int ZERO = 0;
try
{
i = ZERO;
}
catch(ArithmeticException ae)
{
ae.printStackTrace();
}
/*
finally // COORECTION
{

}
*/
}
}
Reference:  Reference Not Available. 

Rule 107: Use_compound_operators

Severity:  Medium
Rule:  Use compound operators for improved performance
Reason:  Use compound operators for improved performance
Usage Example: 
package com.rule;
class Use_compound_operators_violation
{
public void method(int[] a, int x)
{
for (int i = 0; i < a.length; i++)
{
a[i] = a[i] + x; // VIOLATION
}
}
}
Should be written as:
package com.rule;
class Use_compound_operators_correction
{
public void method(int[] a, int x)
{
for (int i = 0; i < a.length; i++)
{
a[i] += x; // CORRECTION
}
}
}

Rule 108: Avoid_concatenating_Strings_in_StringBuffer

Severity:  Medium
Rule:  Avoid concatenating Strings in StringBuffer's constructor or append(..) method.
Reason:  Avoid concatenating Strings in StringBuffer's constructor or append(..) method.
Usage Example: 
public class AvoidStringConcat
{
public void aMethod()
{
StringBuffer sb = new StringBuffer("Hello" + getWorld()); // VIOLATION
sb.append("Calling From " + getJava()); // VIOLATION
}

public String getWorld()
{
return " World";
}

public String getJava()
{
return " Java";
 }
}
Should be written as:
public class AvoidStringConcat
{
public void aMethod()
{
StringBuffer sb = new StringBuffer("Hello");
sb.append(getWorld());
sb.append("Calling From ");
sb.append(getJava());
}

public String getWorld()
{
return " World";
}

public String getJava()
{
return " Java";
 }
}

Rule 109: Declare_package_private_class_final

Severity:  Medium
Rule:  Declare package private class as final.
Reason:  Declare package private class as final.
Usage Example: 
package com.rule;

class Declare_package_private_method_final_Violation  // Violation
{
}
Should be written as:
package com.rule;

final class Declare_package_private_method_final_Correction  // Correction
{
}

Rule 110: Use_hashMap_inplace_of_hashTable

Severity:  Medium
Rule:  Use 'HashMap' in place of 'HashTable' wherever possible
Reason:  Use 'HashMap' in place of 'HashTable' wherever possible
Usage Example: 
package com.rule;
import java.util.Hashtable;
class Use_hashMap_inplace_of_hashTable_violation
{
private static final int SIZE = 10;
private Hashtable ht = new Hashtable(SIZE); // VIOLATION

public void method()
{
ht.clear();
}
}
Should be written as:
package com.rule;
import java.util.HashMap;
class Use_hashMap_inplace_of_hashTable_correction
{
private static final int SIZE = 10;
private HashMap ht = new HashMap(SIZE); // CORRECTION

public void method()
{
ht.clear();
}
}
Reference:  Reference Not Available. 

Rule 111: Avoid_creating_double_from_string

Severity:  High
Rule:  Avoid creating double from string for improved performance
Reason:  Avoid creating double from string for improved performance
Usage Example: 
public class Avoid_creating_double_from_string_violation 
{

public void method()
{
Double db = new Double("3.44");  // VIOLATION
Double.valueOf("3.44"); // VIOLATION

if(db == null)
{
// Do Something
db = null;
}
}
}
Should be written as:
Avoid converting String to Double

Rule 112: Always_use_right_shift_operator_for_division_by_powers_of_two

Severity:  Low
Rule:  It is more efficient and improves performance if shift operators are used.
Reason:  It is more efficient and improves performance if shift operators are used.
Usage Example: 
public class Test
{
public int calculate (int num) 
{
  return num / 4;  // VIOLATION
  }
}
Should be written as:
public class Test
{
public int calculate (int num) 
{
   return num >> 2;  // FIXED *
}

}

// * Replace the division with an equivalent '>> power', where 'power' is the power
// of two such that 2 ^ power = divisor.
Reference:  Not available. 

Rule 113: Use_shift_operators

Severity:  High
Rule:  Shift operators are faster than multiplication and division
Reason:  Shift operators are faster than multiplication and division
Usage Example: 
package com.rule;
class Use_shift_operators_violation
{
public void method()
{
int x = 0;
int X = x / 4; // VIOLATION
int Y = x * 2; // VIOLATION
X++;
Y++;
}
}
Should be written as:
package com.rule;
class Use_shift_operators_correction
{
public void method()
{
int x = 0;
int X = x >> 2; // CORRECTION
int Y = x << 1; // CORRECTION
X++;
Y++;
}
}
Reference:  www.javaworld.com/javaworld/jw-04-1997/jw-04-optimize_p.html 

Rule 114: Avoid_java_lang_reflect_package

Severity:  High
Rule:  Avoid java.lang.reflect package.
Reason:  Avoid java.lang.reflect package.
Usage Example: 
package com.rule;

public class Avoid_java_lang_reflect_package_violation
{
 public Object getData(String classname)
 {
  try 
  {
    Class c = Class.forName(classname);
 Method m = c.getMethod("getData",null);
   m.invoke(c.newInstance(), null);// Violation
  }
  catch (Exception e)
  {
//....
  }
 }
}
Should be written as:
package com.rule;

public class Avoid_java_lang_reflect_package_correction
{
 public Object getData(String classname)
 {
  try {
Class c = Class.forName(classname);
IDataProvider dataprovider = (IDataProvider) c.newInstance();  // Correction
return dataprovider.getData();
  }
  catch (Exception e)
  {
  }
 }
}

interface IDataProvider
{
Object getData(String name);
}
Reference:  Reference not available. 

Rule 115: Use_NIO_in_server

Severity:  High
Rule:  Using NIO for server is better than using traditional java.net package.
Reason:  Using NIO for server is better than using traditional java.net package.
Usage Example: 
package com.rule;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Use_NIO_in_server_violation
{
public void method(ServerSocket ss) throws IOException
{
Socket soc = ss.accept(); // VIOLATION
// use soc
}
}
Should be written as:
Use classes in java.nio.channels in the server code.

Rule 116: Avoid_object_instantiation_in_loops

Severity:  Critical
Rule:  Avoid object instantiation in frequently executed code for performance reasons
Reason:  Avoid object instantiation in frequently executed code for performance reasons
Usage Example: 
package com.rule;

import java.util.ArrayList;

class Avoid_object_instantiation_violation
{
public void action()
{
ArrayList al = getNameAndValues();
for (int i = 0; i < al.size(); i++)
{
ClassName cn = (ClassName) al.get(i);
String sArr[] = new String[] { cn.getName(), cn.getValue() }; //Violation
//...
}
}

private ArrayList getNameAndValues()
{
ArrayList al = new ArrayList();
// populate list
return al;
}

private class ClassName
{
String name;
String value;

String getName()
{
return name;
}
String getValue()
{
return value;
}
}
}
Should be written as:
package com.rule;

import java.util.ArrayList;

class Avoid_object_instantiation_correction
{
public void action()
{
ArrayList al = getNameAndValues();
String sArr[] = new String[2]; //Correction
for (int i = 0; i < al.size(); i++)
{
ClassName cn = (ClassName) al.get(i);
sArr[0] = cn.getName();
sArr[1] = cn.getValue();
//...
}
}

private ArrayList getNameAndValues()
{
ArrayList al = new ArrayList();
// populate list
return al;
}

private class ClassName
{
String name;
String value;

String getName()
{
return name;
}
String getValue()
{
return value;
}
}
}

Rule 117: Avoid_unnecessary_instanceof

Severity:  High
Rule:  Avoid unnecessary "instanceof" evaluations.
Reason:  Avoid unnecessary "instanceof" evaluations.
Usage Example: 
package com.rule;

class Avoid_unnecessary_instanceof_violation
{
private String obj = "String"; //$NON-NLS-1$
public void method()
{
if (obj instanceof Object) // VIOLATION
{
obj.getClass();
}
}
}
Should be written as:
package com.rule;

class Avoid_unnecessary_instanceof_correction
{
private String obj = "String"; //$NON-NLS-1$

public void method()
{
/* // CORRECTION
if (obj instanceof Object)
{
obj.getClass();
}
*/
obj.getClass();
}
}
Reference:  Reference Not Available. 

Rule 118: Define_initial_capacities

Severity:  Medium
Rule:  Expansion of array capacity involves allocating a larger array and copying the contents of the old array to a new one.
Eventually, the old array object gets reclaimed by the garbage collector. Array expansion is an expensive operation.
Usually one may have a pretty good guess at the expected size which should be used instead of the default.
Reason:  Expansion of array capacity involves allocating a larger array and copying the contents of the old array to a new one.
Eventually, the old array object gets reclaimed by the garbage collector. Array expansion is an expensive operation.
Usually one may have a pretty good guess at the expected size which should be used instead of the default.
Usage Example: 
package com.rule;

import java.util.ArrayList;

class Define_initial_capacities_violation
{
private ArrayList al = new ArrayList(); // VIOLATION

public int method()
{
return al.size();
}
}
Should be written as:
package com.rule;

import java.util.ArrayList;

class Define_initial_capacities_correction
{
private final int SIZE = 10;
private ArrayList al = new ArrayList(SIZE); // CORRECTION

public int method()
{
return al.size();
}
}
Reference:  http://www.oreilly.com/catalog/javapt/chapter/ch04.html 
Dov Bulka, "Java Performance and Scalability Volume 1: Server-Side Programming Techniques" Addison Wesley, ISBN: 0-201-70429-3 pp.55 57
Neal Ford, "Performance Tuning With Java Technology" JavaOne 2001 Conference 

Rule 119: Avoid_empty_catch_blocks

Severity:  Low
Rule:  Avoid empty "catch" block structure.
Reason:  Avoid empty "catch" block structure.
Usage Example: 
package com.rule;

class Avoid_empty_catch_blocks_violation
{
void method(int i)
{
try
{
i++;
}
catch(ArithmeticException ae) // VIOLATION
{
}
}
}
Should be written as:
package com.rule;

class Avoid_empty_catch_blocks_correction
{
void method (int i)
{
try
{
i++;
}
catch(ArithmeticException ae)
{
ae.printStackTrace(); // CORRECTION
}
}
}
Reference:  Reference Not Available. 

Rule 120: Avoid_synchronized_methods_in_loop

Severity:  High
Rule:  Avoid synchronized methods in loop for performance reasons
Reason:  Avoid synchronized methods in loop for performance reasons
Usage Example: 
package com.rule;
class Avoid_synchronized_methods_in_loop_violation
{
public synchronized Object remove()
{
Object obj = null;
//...
return obj;
}
public void removeAll()
{
for(;;)
{
remove(); // VIOLATION
}
}
}
Should be written as:
package com.rule;
class Avoid_synchronized_methods_in_loop_correction
{
public Object remove() // CORRECTION
{
Object obj = null;
//....
return obj;
}
public synchronized void removeAll()
{
for(;;)
{
remove(); // CORRECTION
}
}
}
Reference:  Reference Not Available. 

Rule 121: Avoid_synchronized_blocks_in_loop

Severity:  High
Rule:  Avoid synchronized blocks in loop for performance reasons
Reason:  Avoid synchronized blocks in loop for performance reasons
Usage Example: 
package com.rule;
class Avoid_synchronized_blocks_in_loop_violation
{
public static void main(String[] args)
{
Object lock = new Object();
 
for ( int i = < 0; i < args.length; i ++)
{
synchronized ( lock ) // VIOLATION
{
System.out.println( args[ i ] );
}
}
}

}
Should be written as:
package com.rule;
class Avoid_synchronized_blocks_in_loop_correction
{
public static void main(String[] args)
{
Object lock = new Object();
 
synchronized ( lock ) // CORRECTION
{
for ( int i = < 0; i < args.length; i ++)
{
System.out.println( args[ i ] );
}
}
}

}
Reference:  Reference Not Available. 

Rule 122: Close_jdbc_resources

Severity:  High
Rule:  Always close the JDBC resources opened.
Reason:  Always close the JDBC resources opened.
Usage Example: 
package com.rule;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Close_jdbc_resources_violation
{
public void method(String url, String query)
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try
{
conn = DriverManager.getConnection(url);
stmt = conn.createStatement(); // VIOLATION
rs = stmt.executeQuery(query); // VIOLATION
}
catch (Exception e)
{
}
finally
{
try
{
conn.close();
}
catch (Exception e)
{
}
}
}
}
Should be written as:
package com.rule;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Close_jdbc_resources_correction
{
public void method(String url, String query)
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

try
{
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
}
catch (Exception e)
{
}
finally
{
try
{
rs.close(); // CORRECTION
stmt.close(); // CORRECTION
conn.close();
}
catch (Exception e)
{
}
}
}
}
Reference:  Reference not available. 

Rule 123: Close_jdbc_resources_only_in_finally_block

Severity:  High
Rule:  The place to close jdbc resources is finally block.
Reason:  The place to close jdbc resources is finally block.
Usage Example: 
package com.rule;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Close_jdbc_resources_only_in_finally_block_violation
{
public void method(String url, String query)
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try
{
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
rs = stmt.executeQuery(query);

rs.close(); // VIOLATION
stmt.close(); // VIOLATION
conn.close(); // VIOLATION

}
catch (Exception e)
{
}
finally
{

}
}
}
Should be written as:
package com.rule;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Close_jdbc_resources_only_in_finally_block_correction
{
public void method(String url, String query)
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

try
{
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
}
catch (Exception e)
{
}
finally
{
try
{
rs.close(); // CORRECTION
stmt.close(); // CORRECTION
conn.close(); // CORRECTION
}
catch (Exception e)
{
}
}
}
}
Reference:  Reference not available. 

Rule 124: Specify_StringBuffer_capacity

Severity:  Medium
Rule:  The Default 'StringBuffer' constructor will create a character array of a default size(16).
When size exceeds its capacity, it has to allocate a new character array with a larger capacity, it copies the old contents into the new array,
and eventually discard the old array.By specifying enough capacity during construction prevents the 'StringBuffer' from ever needing expansion.
Reason:  The Default 'StringBuffer' constructor will create a character array of a default size(16).
When size exceeds its capacity, it has to allocate a new character array with a larger capacity, it copies the old contents into the new array,
and eventually discard the old array.By specifying enough capacity during construction prevents the 'StringBuffer' from ever needing expansion.
Usage Example: 
package com.rule;

class Specify_StringBuffer_capacity_violation
{
private StringBuffer sb = new StringBuffer(); // VIOLATION

public void method(int i)
{
sb.append(i);
}
}
Should be written as:
package com.rule;

class Specify_StringBuffer_capacity_correction
{
private final int SIZE = 10;
private StringBuffer sb = new StringBuffer(SIZE); // CORRECTION

public void method(int i)
{
sb.append(i);
}
}
Reference:  Reference Not Available. 

Rule 125: Avoid_using_exponentiation

Severity:  Medium
Rule:  Do not use exponentiation.
Reason:  Do not use exponentiation.
Usage Example: 
package com.rule;

public class Avoid_using_exponentiation_violation
{
public int getPower(int iBase, int iPow)
{
int iRet = (int) Math.pow(iBase, iPow); // VIOLATION
return iRet;
}
}
Should be written as:
package com.rule;

public class Avoid_using_exponentiation_correction
{
public int getPower(int iBase, int iPow)
{
int iRet = 1;
for (int i = 0; i < iPow; i++) // CORRECTION
{
iRet *= iBase;
}
return iRet;
}
}
Reference:  www.javaperformancetuning.com/tips/rawtips.shtml 

Rule 126: Use_transient_keyword

Severity:  High
Rule:  Serialization can be very costly. Using the transient keyword reduces the amount of data serialized
Reason:  Serialization can be very costly. Using the transient keyword reduces the amount of data serialized
Usage Example: 
package com.rule;
import java.io.Serializable;
class Use_transient_keyword_violation implements Serializable
{
final String field1; // VIOLATION
private String field2;
private String field3;

Use_transient_keyword_violation(int i, int j)
{
field2 = i;
field3 = j;
field1 = field2 + field3;
}
}
Should be written as:
package com.rule;

import java.io.Serializable;
class Use_transient_keyword_correction implements Serializable
{
final transient String field1; // CORRECTION 
private String field2;
private String field3;

Use_transient_keyword_violation(int i, int j)
{
field2 = i;
field3 = j;
field1 = field2 + field3;
}
}
Reference:  java.sun.com\docs\books\performance\1st_edition\html\JPIOPerformance.fm.html 

Rule 127: Avoid_new_inside_getTableCellRendererComponent

Severity:  Critical
Rule:  Avoid new inside the method getTableCellRendererComponent.
Reason:  Avoid new inside the method getTableCellRendererComponent.
Usage Example: 
package com.rule;

import javax.swing.table.*;
import javax.swing.*;
import java.awt.*;

public class AvoidNewInside_getTableCellRendererComponent_violation extends DefaultTableCellRenderer
{
  public Component getTableCellRendererComponent(JTable aTable, Object  aNumberValue,boolean aIsSelected,boolean aHasFocus,int aRow, int aColumn)
  {
test tt =new test();  // Violation
tt.fillColour();
return aTable;
  }
}
class test
{
public void fillColour()
{
//...
}
}
Should be written as:
Avoid new inside getTableCellRendererComponent.

Rule 128: Avoid_Integer_valueOf_intValue

Severity:  High
Rule:  Avoid using Integer.valueOf(String).intValue() instead call Integer.parseInt(String).
Reason:  Avoid using Integer.valueOf(String).intValue() instead call Integer.parseInt(String).
Usage Example: 
package com.rule;

class Avoid_Integer_valueOf_intValue_violation
{
public int getValue(String s)
{
return Integer.valueOf(s).intValue(); // VIOLATION
}
}
Should be written as:
package com.rule;

class Avoid_Integer_valueOf_intValue_correction
{
public int getValue(String s)
{
return Integer.parseInt(s); // CORRECTION
}
}
Reference:  Reference Not Available. 

Rule 129: Use_ternary_operator_for_assignment

Severity:  Medium
Rule:  Use ternary operator for assignment.
Reason:  Use ternary operator for assignment.
Usage Example: 
package com.rule;

public class Use_ternary_operator_for_assignment_violation 
{
int iVal;
private void foo(int a, int b)
{
if(a<b) // Violation
{
iVal = a;
}
else
{
iVal = b;
}
}
}
Should be written as:
package com.rule;

public class Use_ternary_operator_for_assignment_violation 
{
int iVal;
private void foo(int a, int b)
{
iVal = (a<b )? a:b;// Correction
}
}
Reference:  Reference not available. 

Rule 130: Avoid_Serialized_class_with_no_instance_variables

Severity:  Low
Rule:  A class with no instance variables, doesn't have any state information that needs to be preserved
Reason:  A class with no instance variables, doesn't have any state information that needs to be preserved
Usage Example: 
package com.rule;

import java.io.Serializable;

class Avoid_Serialized_class_with_no_instance_variables_violation implements Serializable
{
}
Should be written as:
package com.rule;

import java.io.Serializable;

class Avoid_Serialized_class_with_no_instance_variables_violation // implements Serializable
{
}
Reference:  Reference Not Available. 

Rule 131: Avoid_Vector_elementAt_inside_loop

Severity:  Medium
Rule:  Avoid calling Vector.elementAt() inside loop
Reason:  Avoid calling Vector.elementAt() inside loop
Usage Example: 
package com.rule;

import java.util.Vector;

class Avoid_Vector_elementAt_inside_loop_violation
{
public void method(Vector v)
{
int size = v.size();
for(int i=size; i>0; i--)
{
System.out.println((String) v.elementAt(size-i)); // VIOLATION
}
}
}
Should be written as:
package com.rule;

import java.util.Vector;

class Avoid_Vector_elementAt_inside_loop_correction
{
public void method(Vector v)
{
int size = v.size();
Object vArr[] = v.toArray();
for(int i=0; i<size; i++)
{
System.out.println((String) vArr[i]); // CORRECTION
}
}
}

Rule 132: Declare_variable_final

Severity:  Medium
Rule:  Any variable that is initialized and never assigned to should be declared final.
Reason:  Any variable that is initialized and never assigned to should be declared final.
Usage Example: 
package com.rule;

class Declare_variable_final_violation
{
public void method()
{
int i = 5;  // VIOLATION
int j = i;
j = j + i;
}
}
Should be written as:
package com.rule;

class Declare_variable_final_correction
{
public void method()
{
final int i = 5;  // CORRECTION
int j = i;
j = j + i;
}
}
Reference:  Reference Not Available. 

Rule 133: Declare_method_arguments_final

Severity:  Medium
Rule:  Any method argument which is neither used nor assigned should be declared final.
Reason:  Any method argument which is neither used nor assigned should be declared final.
Usage Example: 
package com.rule;

class Declare_method_arguments_final_violation
{
public void method(int i,int j)  // VIOLATION
{
j = j + i;
}
}
Should be written as:
package com.rule;

class Declare_method_arguments_final_correction
{
public void method(final int i,int j)  // CORRECTION
{
j = j + i;
}
}
Reference:  Reference not available. 

Rule 134: Avoid_polling_loops

Severity:  High
Rule:  Do not use polling loops / busy waiting.
Reason:  Do not use polling loops / busy waiting.
Usage Example: 
package com.rule;

public class Avoid_polling_loops_violation
{
boolean bContinue;

void doSomething()
{
while(!bContinue)
{
try
{
Thread.sleep(250); // VIOLATION
}
catch (InterruptedException e)
{ }
}

// take action
}
}
Should be written as:
package com.rule;

public class Avoid_polling_loops_correction
{
boolean bContinue;
Object objLock; // notifyAll() will be called on this object from some other thread

void doSomething()
{
synchronized(objLock)
{
while(!bContinue)
{
try
{
objLock.wait(); // CORRECTION
}
catch (InterruptedException e)
{ }
}
}

// take action
}
}
Reference: 

Rule 135: Avoid_Serialized_class_with_only_transient_fields

Severity:  Low
Rule:  The class with only transient fields doesn't have any state information that needs to be preserved
Reason:  The class with only transient fields doesn't have any state information that needs to be preserved
Usage Example: 
package com.rule;

import java.io.Serializable;

class Avoid_Serialized_class_with_only_transient_fields_violation implements Serializable
 //Violation
{
transient int count = 0;
}
Should be written as:
package com.rule;

import java.io.Serializable;

class Avoid_Serialized_class_with_only_transient_fields_violation // implements Serializable 
//Correction
{
transient int count = 0;
}
Reference:  Reference Not Available. 

Alphabetic Profile Pic like Gmail in Android

$
0
0
This light-weight library provides images with letter/text like the Gmail app. It extends the Drawable class thus can be used with existing/custom/network ImageView classes.

Also included is a fluent interface for creating drawables and a customizable ColorGenerator.

How to use

Import with Gradle:

repositories{
maven {
url 'http://dl.bintray.com/amulyakhare/maven'
}
}

dependencies {
compile 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1'
}

1. Create simple tile:

<ImageViewandroid:layout_width="60dp"
android:layout_height="60dp"
android:id="@+id/image_view"/>
Note: Specify width/height for the ImageView and the drawable will auto-scale to fit the size.
TextDrawable drawable =TextDrawable.builder()
.buildRect("A", Color.RED);

ImageView image = (ImageView) findViewById(R.id.image_view);
image.setImageDrawable(drawable);

2. Create rounded corner or circular tiles:

TextDrawable drawable1 =TextDrawable.builder()
.buildRoundRect("A", Color.RED, 10); // radius in px

TextDrawable drawable2 =TextDrawable.builder()
.buildRound("A", Color.RED);

3. Add border:

TextDrawable drawable =TextDrawable.builder()
.beginConfig()
.withBorder(4) /* thickness in px */
.endConfig()
.buildRoundRect("A", Color.RED, 10);

4. Modify font style:

TextDrawable drawable =TextDrawable.builder()
.beginConfig()
.textColor(Color.BLACK)
.useFont(Typeface.DEFAULT)
.fontSize(30) /* size in px */
.bold()
.toUpperCase()
.endConfig()
.buildRect("a", Color.RED)

5. Built-in color generator:

ColorGenerator generator =ColorGenerator.MATERIAL; // or use DEFAULT
// generate random color
int color1 = generator.getRandomColor();
// generate color based on a key (same key returns the same color), useful for list/grid views
int color2 = generator.getColor("user@gmail.com")

// declare the builder object once.
TextDrawable.IBuilder builder =TextDrawable.builder()
.beginConfig()
.withBorder(4)
.endConfig()
.rect();

// reuse the builder specs to create multiple drawables
TextDrawable ic1 = builder.build("A", color1);
TextDrawable ic2 = builder.build("B", color2);

6. Specify the width / height:

<ImageViewandroid:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/image_view"/>
Note: The ImageView could use wrap_content width/height. You could set the width/height of the drawable using code.
TextDrawable drawable =TextDrawable.builder()
.beginConfig()
.width(60) // width in px
.height(60) // height in px
.endConfig()
.buildRect("A", Color.RED);

ImageView image = (ImageView) findViewById(R.id.image_view);
image.setImageDrawable(drawable);

7. Other features:

  1. Mix-match with other drawables. Use it in conjunction with LayerDrawableInsetDrawableAnimationDrawable,TransitionDrawable etc.
  2. Compatible with other views (not just ImageView). Use it as background drawable, compound drawable for TextView,Button etc.
  3. Use multiple letters or unicode characters to create interesting tiles.

Create Gmail Like Text Avatars Using Javascript

$
0
0
initial.js is a lightweight jQuery plugin used to generate a SVG based user profile picture from the data-name attribute of your IMG tag, just like the text avatars as you see on Gmail.


How to use it:

Include the jQuery javascript and initial.js in the html document.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="initial.js"></script>

Create an image in your document and use data-name attribute to specify the name of the user which the profile picture should be generated.

<imgdata-name="jQuery"class="demo"/>

Initialize the plugin with default options.

<script type="text/javascript">
$(document).ready(function(){
$('.demo').initial({width:80,height:80});
})
</script>

Style the user profile picture in the CSS as you wish.

.demo{
...
}
If you want it for Android : Alphabetic Profile Pic like Gmail in Android

Available options to customize the profile picture (text avatar).

<script type="text/javascript">
$(document).ready(function(){
$('.demo').initial({
name: 'Name', // Name of the user
charCount: 1, // Number of characherts to be shown in the picture.
textColor: '#ffffff', // Color of the text
seed: 0, // randomize background color
height: 100,
width: 100,
fontSize: 60,
fontWeight: 400,
fontFamily: 'HelveticaNeue-Light,Helvetica Neue Light,Helvetica Neue,Helvetica, Arial,Lucida Grande, sans-serif',
radius: 0
});
})
</script>

Full Source Code

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="initial.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.demo').initial({
name: 'Name', // Name of the user
charCount: 2, // Number of characherts to be shown in the picture.
textColor: '#ffffff', // Color of the text
seed: 2, // randomize background color
height: 100,
width: 100,
fontSize: 60,
fontWeight: 400,
fontFamily: 'HelveticaNeue-Light,Helvetica Neue Light,Helvetica Neue,Helvetica, Arial,Lucida Grande, sans-serif',
radius: 500
});
})
</script>
</head>
<body>
<imgdata-name="GeekOnJava"class="demo"/>


</body>
</html>
Happy coding !!

How to Export HTML Table to Excel, CSV, JSON, PDF, PNG using jQuery

$
0
0
My readers endlessly asked me to work on how to export HTML table information instead of copying the records manually. So i believed to share this excellent Jquery plugin I actually have bump into via google to my readers.

This plugin is incredibly simple to implement it in your comes who desires to export the HTML table data instantly.
"table2JSON", "table2XML", "table2PNG","table2CSV","table2Excel","table2Word","table2Powerpoint","table2txt","table2PDF"
Beauty of this jQuery plugin is that permits you to download any html table data into all downloadable formats. this can be the must required plugin for any reporting / statistics kind of projects.


Plugin Features

We can easily export any html tables to these 10 following formats

  1. JSON
  2. XML
  3. PNG
  4. CSV
  5. TXT
  6. SQL
  7. MS-Word
  8. Ms-Excel
  9. Ms-Powerpoint
  10. PDF

Installation

You need an jquery plugin to support this feature

<script type="text/javascript"src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript"src="tableExport.js"/>
<script type="text/javascript"src="jquery.base64.js"/>

For exporting html table to PNG format

You need an below script to export html table data to PNG format. html2canvas.js
<script type="text/javascript"src="html2canvas.js"/>

For exporting html table data into PDF format

<script type="text/javascript"src="jspdf/libs/sprintf.js"/>
<script type="text/javascript"src="jspdf/jspdf.js"/>
<script type="text/javascript"src="jspdf/libs/base64.js"/>

Usage

<ahref="#"onClick ="$('#tableID').tableExport({type:'json',escape:'false'});">JSON</a>
<ahref="#"onClick ="$('#tableID').tableExport({type:'excel',escape:'false'});">XLS</a>
<ahref="#"onClick ="$('#tableID').tableExport({type:'csv',escape:'false'});">CSV</a>
<ahref="#"onClick ="$('#tableID').tableExport({type:'pdf',escape:'false'});">PDF</a>

Other Types

{type:'json',escape:'false'}
{type:'json',escape:'false',ignoreColumn:'[2,3]'}
{type:'json',escape:'true'}
{type:'xml',escape:'false'}
{type:'sql'}
{type:'csv',escape:'false'}
{type:'txt',escape:'false'}
{type:'excel',escape:'false'}
{type:'doc',escape:'false'}
{type:'powerpoint',escape:'false'}
{type:'png',escape:'false'}
{type:'pdf',pdfFontSize:'7',escape:'false'}

Hope you enjoy !!


[Working] Increase JIO Sim Internet Speed Upto 20 Mbps

$
0
0
Reliance industry brought a revolution in telecommunication field by launching JIO Welcome offer. JIO sim supported only in LTE or voLTE supported handsets. And it offers unlimited internet, free voice call and unlimited SMS for 31st December.
They claim to provides 4G speed internet to all users. And their speed is truly good in comparison of other network internet. But as per increasing the connected people with JIO network their internet speed is going down dramatically.
And if you also suffer with low internet speed in your JIO network and want to increase your internet speed mean speed of actual 4G internet (10-30 Mbps) in India.
And you just need to add some configuration in your Android APN (Access Point Name) setting


First of all open android Setting >> Tap on mobile networks options >> Here you got APN or access point name setting and click on them >>  Select + button in right hand top and add below information in field >> At last click on save setting.



check values below  :

Name: geekonjava.net
APN: jionet ( use all small letters)
Proxy: Not Set ( if ur using VPN Service disable it)
Port: Not Set Username: Not Set
Password: Not Set
Server: www.google.com/ www.jio4g.com
MMSC: not set
MMS Proxy: Not Set
MMS Port: Not Set
MCC: 405 MNC: 857 or 863 or 874
Authentication type: not set
APN Protocol: IPv4 / IPv6 

Note: 

Not Set means no changed need. Default options are available. Another alternative method to get High speed internet from JIO 4G Sim UC Browser Changing proxy by using Private VPN Services. use France IP VPN Service install it on UC Mini browser. you can get high speed internet.

Android 7.1 Nought Developer Preview

$
0
0
After declaring name of latest Android 7 version is Nought with some best upcoming features like drag and drop in gmail, smart deal with notifications, cancel option in Android default downloader and many some interesting post which you can see here : Best 16 Features of Android 7 Nougat You Should Know



And now Google announce some updates in Android 7 Nought for developer with including new features for consumers and developers — from platform Daydream VR support and A/B system updates to app shortcuts and image keyboard support.

What's new in Android 7.1 Nought? 

It conveys the profitability, security, and execution of Android 7.0, alongside an assortment of enhancements and bug fixes, highlights, and new APIs (API level 25).

For engineers, Android 7.1 adds new capacities to help you drive engagement in your application and convey an enhanced client experience, for example,

Application shortcut API

It gives you a chance to surface key activities specifically in the launcher and take your clients profound into your application in a split second. You can make up to 5 alternate ways, either statically or progressively.


Circular application icon support

It gives you a chance to give extraordinary looking adjusted icon assets that match the look of Pixel and different launchers.

Upgraded live wallpaper metadata

It gives you a chance to give metadata about your live wallpaper to any picker showing the wallpaper as a review. You can indicate existing metadata, for example, name, depiction, and creator, and additionally another setting URL and title to connection to more data.


Android 7.1 likewise includes these abundantly asked for engineer components to the stage: 

Image Keyboard support

It grows the sorts of content that clients can enter from their keyboards, letting them convey what needs be through custom stickers, animated gifs, and that's just the beginning. Applications can tell the keyboard what sorts of contents they acknowledge, and consoles can convey the majority of the images  and other content that they offer to the client. For wide similarity, this API will likewise be accessible in the support library.

Storage manager Intent

It provides an application take the client specifically to another Settings screen to clear unused records and free up storage room on the gadget.

For bearers and calling applications, the stage incorporates new APIs to support multi-endpoint calling and new communication design alternatives.

Get your applications prepared 


Android 7.1 is an incremental release, yet it's constantly vital to ensure your applications look and run awesome — particularly as gadgets begin to achieve buyers.

The Android 7.1 Developer Preview will give you everything you need to test your apps or extend them with new features like shortcuts or keyboard images. Included are the SDK with new APIs, build tools, documentation and samples, as well as emulators and device system images for running your apps on supported Nexus devices. We’ll also include a launcher and apps that support app shortcuts, and a keyboard and apps that support keyboard images.

Why Google Pixel replace Nexus and iPhone 7

$
0
0
Hello friends, Today i am telling you some smart features of world's best company mobile and you'll forgot the features of Apple iPhone 7. Its Google pixel and pixel XL which meets all your requirement in your smartphone and will not see that features yourself ever.

In this post im am telling you best feature of that phones which you never get in any other smartphones.


Unique Feature Of Google Pixel and Pixel XL:

Google Assistant:

This is an assistant app which gather all information which you want. Recently Google launched their Google Allo Messenger and if you install this app then you know the real features of this app. From my experience i can live alone for several hour with Google Assistant app.

But Google add  four extra features in this in-build application.

Get Answer :

If you want to know about anything, definition, information etc you'll get on your fingertip.

Manage Every Day Task :

Now you're free to set Alarm or Reminder manually. You can set them by send simple text in this application.

Find Photo Faster :

If you want to search your old pic and don't want hassle with heap of images then just text to this application. It'll work for you.

Translate on the go :

Before this app if you want to translate any word or sentence then you need to download extra application and their result may be not correct. But this application you can translate easily and more accurate than ever.


Smart and easy switch :

This is also a great feature of this phone. Before this phone if we want to share any file then we need to conncet phone with PC via USB cable. But in this phone you can directly connect with your iPhone or Android phone and share your file easily with them.


Google Pixel And Google Pixel XL Full Specification:

Everything are same in both phone except display size and battery

Google Pixel Display Size:


  • 5.0″ inch , Full HD (FHD) AMOLED at ~441 ppi (pixel per inch).
  • 2.5D Corning Gorilla Glass 5 with >75% Active Area

Google pixel XL Display Size:


  • 5.5″ inch ,2K(QHD) AMOLED at ~534 ppi (pixel per inch).
  • 2.5D Corning Gorilla Glass 5 with >75% Active Area

Google Pixel Battery:


  • 27,70 mAh
  • Standby (LTE): maximum 19 Day
  • Internet Use Wifi and LTE: 13 hour
  • Fast Charge: 7 Hour ke Liye 15 minute charge.

Google Pixel XL Battery:


  • 34,50mAh
  • Standby (LTE): maximum 23 Day
  • Internet Use Wifi and LTE: 14 Hour
  • Fast Charge: 7 Hour ke Liye 15 minute charge.

Design:

In both smartphone you got Unibody Metal design  with Corning Gorilla Glass 4. It has great look than iPhone and scratch proof.

Memory And Storage:

In Google's both smartphone Pixel and Pixel XL has 4GB LPDDR4 RAM and their storage 32GB and  128GB with 256GB expandable.

Processor and OS:

They have Best Processor Snapdragon 821,MSM8996 pro AB Quad Core 2+2 kryo 2.15GHz/1.5GHz  with latest Android OS 7 Nought.

Cameras:


  • Camera (Rear Camera): 12.3MP IMX378 (You can take HD image in low light), PDAF+LDAF (Phase Detection Auto Focus + Laser Detection Auto Focus) , 1.55µm (Pixel  size), f/2.0 Aperture ( for large background) .
  • Front Camera: 8MP IMX378 (You can take HD image in low light), 1.4µm (Pixel  size),f/2.5 Aperture (for large background) .

Video Play and Recording Quality:


  • Recording Quality: 1080p @ 30fps, 60fps, 120fps720p @ 30fps, 60fps, 240fps,4K @ 30fps.
  • Video Play Quality: 1080p @ 30fps, 60fps, 120fps720p @ 30fps, 60fps, 240fps,4K @ 30fps.

Sensors:


  • Proximity/ALS
  • Accelerometer / Gyrometer
  • Magnetometer
  • Pixel Imprint – Back-mounted fingerprint sensor for fast unlocking
  • Barometer
  • Hall sensor
  • Sensor Hub: CHRE V2 with GPS/Wi-Fi/BT
  • Advanced x-axis haptics for sharper / defined response

Ports:


  • USB Type-C
  • USB 3.0
  • 3.5mm Audio jack

Connectivity:


  • WiFi 802.11 a/b/g/n/ac 2×2 MIMO
  • BT 4.2
  • NFC
  • Supports up to CAT 11 (600Mbps DL / 75Mbps UL) depending upon carrier.




How to Add Android Fingerprint Authentication in Your Project

$
0
0
Fingerprint authentication utilizes the touch sensor incorporated with numerous Android gadgets to distinguish the client and give access to both the gadget and application usefulness, for example, in-application installment alternatives. The execution of Fingerprint authentication is a multi-step procedure which can, at initially, appear to be overpowering. At the point when separated into individual strides, in any case, the procedure turns out to be substantially less mind boggling. In fundamental terms, unique mark authentication or Fingerprint authentication is basically a matter of encryption including a key, a figure to play out the encryption and a finger impression director to handle the authentication procedure.



This part gives both a diagram of unique mark authentication and a definite, regulated instructional exercise that shows a handy way to deal with execution.

An Overview of Fingerprint Authentication

There are essentially 10 steps to implementing fingerprint authentication within an Android app. These steps can be summarized as follows:

  1. Request fingerprint authentication permission within the project Manifest file.
  2. Verify that the lock screen of the device on which the app is running is protected by a PIN, pattern or password (fingerprints can only be registered on devices on which the lock screen has been secured).
  3. Verify that at least one fingerprint has been registered on the device.
  4. Create an instance of the FingerprintManager class.
  5. Use a Keystore instance to gain access to the Android Keystore container. This is a storage area used for the secure storage of cryptographic keys on Android devices.
  6. Generate an encryption key using the KeyGenerator class and store it in the Keystore container.
  7. Initialize an instance of the Cipher class using the key generated in step 5.
  8. Use the Cipher instance to create a CryptoObject and assign it to the FingerprintManager instance created in step 4.
  9. Call the authenticate method of the FingerprintManager instance.
  10. Implement methods to handle the callbacks triggered by the authentication process. Provide access to the protected content or functionality on completion of a successful authentication.

Each of the above steps will be covered in greater detail throughout the tutorial outlined in the remainder of this chapter.

Creating the Fingerprint Authentication Project

Begin this example by launching the Android Studio environment and creating a new project, entering FingerprintDemo into the Application name field and geekonjava.blogspot.com as the Company Domain setting before clicking on the Next button.

On the form factors screen, enable the Phone and Tablet option and set the minimum SDK setting to API 23: Android 6.0 (Marshmallow).
Continue through the setup screens, requesting the creation of an empty activity named FingerprintDemoActivity with a corresponding layout named activity_fingerprint_demo.

Configuring Device Fingerprint Authentication

Fingerprint authentication is only available on devices containing a touch sensor and on which the appropriate configuration steps have been taken to secure the device and enroll at least one fingerprint. For steps on configuring an emulator session to test fingerprint authentication, refer to the chapter entitled Using and Configuring the Android Studio 2 AVD Emulator.

  • To configure fingerprint authentication on a physical device begin by opening the Settings app and selecting the Security option. 
  • Within the Security settings screen, select the Fingerprint option. On the resulting information screen click on the Continue button to proceed to the Fingerprint setup screen. Before fingerprint security can be enabled a backup screen unlocking method (such as a PIN number) must be configured.
  • Click on the Set Up Screen Lock button if the lock screen is not already secured and follow the steps to configure either PIN, pattern or password security.

With the lock screen secured, proceed to the fingerprint detection screen and touch the sensor when prompted to do so, repeating the process to add additional fingerprints if required.



Adding the Fingerprint Permission to the Manifest File

Fingerprint authentication requires that the app request the USE_FINGERPRINT permission within the project manifest file.
Within the Android Studio Project tool window locate and edit the app -> manifests -> AndroidManifest.xml file to add the permission request as follows:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.blogspot.geekonjava.fingerprintdemo1">

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

Downloading the Fingerprint Icon

Google provides a standard icon which must be displayed whenever an app requests authentication from a user.



A copy of this icon may be downloaded from the following URL:

https://4.bp.blogspot.com/-zg9r1Lydt54/WAB1TPgdYvI/AAAAAAAACAk/grHl9pagdjUv_nVCGijYSpq83hmQFrkngCLcB/s1600/Android_studio_2_fingerprint_icon.png


  • Open the filesystem navigator for your operating system, select the newly downloaded image and press Ctrl-C (Cmd-C on Mac OS X) to copy the file. 
  • Return to Android Studio, right-click on the app -> res -> drawable folder and select the Paste menu option to add a copy of the image file to the project. When the Copy dialog appears, click on the OK button to use the default settings.

Designing the User Interface

In the interests of keeping the example as simple as possible, the only elements within the user interface will be a TextView and an ImageView. Locate and select the activity_fingerprint_demo.xml layout resource file to load it into the Designer tool. Once loaded, delete the sample TextView object, drag and drop an ImageView object from the panel and position it in the center of the layout canvas.

Within the Properties panel, locate the src attribute, click in the corresponding text field followed by the button highlighted in Figure 62-3 to display the Resources dialog:



From the left hand panel of the dialog select the Drawable option. Within the main panel, enter ic_fp into the search box as illustrated in Figure 62 4 to locate the fingerprint icon. Select the icon from the dialog and click on OK to assign it to the ImageView object.



Locate the Large Text object from the palette and drag and drop it so that it is positioned beneath the ImageView object. Double click on the object and change the text so that it reads “Touch Sensor”. Use the lightbulb icon to extract the string to a resource named touch_sensor.

On completion of the above steps the layout should match that shown below:



Accessing the Keyguard and Fingerprint Manager Services

Fingerprint authentication makes use of two system services in the form of the KeyguardManager and the FingerprintManager. Edit the onCreate method located in the FingerprintDemoActivity.java file to obtain references to these two services as follows:

FingerprintDemoActivity.java

package com.blogspot.geekonjava.fingerprintdemo;

importandroid.support.v7.app.AppCompatActivity;
importandroid.os.Bundle;
importandroid.app.KeyguardManager;
importandroid.hardware.fingerprint.FingerprintManager;

publicclassFingerprintDemoActivityextends AppCompatActivity {

private FingerprintManager fingerprintManager;
private KeyguardManager keyguardManager;

@Override
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fingerprint_demo);

keyguardManager =
(KeyguardManager) getSystemService(KEYGUARD_SERVICE);
fingerprintManager =
(FingerprintManager) getSystemService(FINGERPRINT_SERVICE);

}
}

Checking the Security Settings

Earlier in this chapter steps were taken to configure the lock screen and register fingerprints on the device or emulator on which the app is going to be tested. It is important, however, to include defensive code in the app to make sure that these requirements have been met before attempting to seek fingerprint authentication.
These steps will be performed within the onCreate method residing in the FingerprintDemoActivity.java file, making use of the Keyguard and Fingerprint manager services. Note that code has also been added to verify that the USE_FINGERPRINT permission has been configured for the app:

FingerprintDemoActivity.java

package com.blogspot.geekonjava.fingerprintdemo;

importandroid.support.v7.app.AppCompatActivity;
importandroid.os.Bundle;
importandroid.app.KeyguardManager;
importandroid.hardware.fingerprint.FingerprintManager;
importandroid.widget.Toast;
importandroid.Manifest;
importandroid.content.pm.PackageManager;
importandroid.support.v4.app.ActivityCompat;

publicclassFingerprintDemoActivityextends AppCompatActivity {

private FingerprintManager fingerprintManager;
private KeyguardManager keyguardManager;

@Override
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fingerprint_demo);

keyguardManager =
(KeyguardManager) getSystemService(KEYGUARD_SERVICE);
fingerprintManager =
(FingerprintManager) getSystemService(FINGERPRINT_SERVICE);

if (!keyguardManager.isKeyguardSecure()) {

Toast.makeText(this,
"Lock screen security not enabled in Settings",
Toast.LENGTH_LONG).show();
return;
}

if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.USE_FINGERPRINT) !=
PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this,
"Fingerprint authentication permission not enabled",
Toast.LENGTH_LONG).show();

return;
}

if (!fingerprintManager.hasEnrolledFingerprints()) {

// This happens when no fingerprints are registered.
Toast.makeText(this,
"Register at least one fingerprint in Settings",
Toast.LENGTH_LONG).show();
return;
}
}
.
.
.
}
The above code changes begin by using the Keyguard manager to verify that a backup screen unlocking method has been configured (in other words a PIN or other authentication method can be used as an alternative to fingerprint authentication to unlock the screen). In the event that the lock screen is not secured the code reports the problem to the user and returns from the method.

The fingerprint manager is then used to verify that at least one fingerprint has been registered on the device, once again reporting the problem and returning from the method if necessary.

Accessing the Android Keystore and KeyGenerator

Part of the fingerprint authentication process involves the generation of an encryption key which is then stored securely on the device using the Android Keystore system. Before the key can be generated and stored, the app must first gain access to the Keystore.

A new method named generateKey will now be implemented within the FingerprintDemoActivity.java file to perform the key generation and storage tasks. Initially, only the code to access the Keystore will be added as follows:

FingerprintDemoActivity.java

package com.blogspot.geekonjava.fingerprintdemo;

importandroid.support.v7.app.AppCompatActivity;
importandroid.os.Bundle;
importandroid.app.KeyguardManager;
importandroid.hardware.fingerprint.FingerprintManager;
importandroid.widget.Toast;
importandroid.Manifest;
importandroid.content.pm.PackageManager;
importandroid.support.v4.app.ActivityCompat;

importjava.security.KeyStore;

publicclassFingerprintDemoActivityextends AppCompatActivity {

private FingerprintManager fingerprintManager;
private KeyguardManager keyguardManager;
private KeyStore keyStore;
.
.
.
protectedvoidgenerateKey() {
try {
keyStore = KeyStore.getInstance("AndroidKeyStore");
} catch (Exception e) {
e.printStackTrace();
}
}
}
A reference to the Keystore is obtained by calling the getInstance method of the Keystore class and passing through the identifier of the standard Android keystore container (“AndroidKeyStore”). The next step in the tutorial will be to generate a key using the KeyGenerator service.

Before generating this key, code needs to be added to obtain a reference to an instance of the KeyGenerator, passing through as arguments the type of key to be generated and the name of the Keystore container into which the key is to be saved:

FingerprintDemoActivity.java

package com.blogspot.geekonjava.fingerprintdemo;

importandroid.support.v7.app.AppCompatActivity;
importandroid.os.Bundle;
importandroid.app.KeyguardManager;
importandroid.hardware.fingerprint.FingerprintManager;
importandroid.widget.Toast;
importandroid.Manifest;
importandroid.content.pm.PackageManager;
importandroid.support.v4.app.ActivityCompat;
importandroid.security.keystore.KeyProperties;

importjava.security.KeyStore;
importjava.security.NoSuchAlgorithmException;
importjava.security.NoSuchProviderException;

importjavax.crypto.KeyGenerator;

publicclassFingerprintDemoActivityextends AppCompatActivity {

private FingerprintManager fingerprintManager;
private KeyguardManager keyguardManager;
private KeyStore keyStore;
private KeyGenerator keyGenerator;

protectedvoidgenerateKey() {
try {
keyStore = KeyStore.getInstance("AndroidKeyStore");
} catch (Exception e) {
e.printStackTrace();
}

try {
keyGenerator = KeyGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_AES,
"AndroidKeyStore");
} catch (NoSuchAlgorithmException |
NoSuchProviderException e) {
thrownewRuntimeException(
"Failed to get KeyGenerator instance", e);
}
}
.
.
}

Generating the Key

Now that we have a reference to the Android Keystore container and a KeyGenerator instance, the next step is to generate the key that will be used to create a cipher for the encryption process. Remaining within the FingerprintDemoActivity.java file, add this new code as follows:

FingerprintDemoActivity.java

package com.blogspot.geekonjava.fingerprintdemo;

importandroid.support.v7.app.AppCompatActivity;
importandroid.os.Bundle;
importandroid.app.KeyguardManager;
importandroid.hardware.fingerprint.FingerprintManager;
importandroid.widget.Toast;
importandroid.Manifest;
importandroid.content.pm.PackageManager;
importandroid.support.v4.app.ActivityCompat;
importandroid.security.keystore.KeyProperties;
importandroid.security.keystore.KeyGenParameterSpec;

importjava.security.KeyStore;
importjava.security.InvalidAlgorithmParameterException;
importjava.security.NoSuchAlgorithmException;
importjava.security.cert.CertificateException;
importjava.security.InvalidAlgorithmParameterException;
importjava.io.IOException;

importjavax.crypto.KeyGenerator;

publicclassFingerprintDemoActivityextends AppCompatActivity {

privatestaticfinal String KEY_NAME = "example_key";
private FingerprintManager fingerprintManager;
private KeyguardManager keyguardManager;
private KeyStore keyStore;
private KeyGenerator keyGenerator;
.
.
.
protectedvoidgenerateKey() {
try {
keyStore = KeyStore.getInstance("AndroidKeyStore");
} catch (Exception e) {
e.printStackTrace();
}

try {
keyGenerator = KeyGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_AES,
"AndroidKeyStore");
} catch (NoSuchAlgorithmException |
NoSuchProviderException e) {
thrownewRuntimeException(
"Failed to get KeyGenerator instance", e);
}

try {
keyStore.load(null);
keyGenerator.init(new
KeyGenParameterSpec.Builder(KEY_NAME,
KeyProperties.PURPOSE_ENCRYPT |
KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setUserAuthenticationRequired(true)
.setEncryptionPaddings(
KeyProperties.ENCRYPTION_PADDING_PKCS7)
.build());
keyGenerator.generateKey();
} catch (NoSuchAlgorithmException |
InvalidAlgorithmParameterException
| CertificateException | IOException e) {
thrownewRuntimeException(e);
}
}
.
.
}
The above changes require some explanation. After importing a number of additional modules the code declares a string variable representing the name (in this case “example_key”) that will be used when storing the key in the Keystore container.

Next, the keystore container is loaded and the KeyGenerator initialized. This initialization process makes use of the KeyGenParameterSpec.Builder class to specify the type of key being generated. This includes referencing the key name, configuring the key such that it can be used for both encryption and decryption, and setting various encryption parameters.

The setUserAuthenticationRequired method call configures the key such that the user is required to authorize every use of the key with a fingerprint authentication. Once the KeyGenerator has been configured, it is then used to generate the key via a call to the generateKey method of the instance.

Initializing the Cipher

Now that the key has been generated the next step is to initialize the cipher that will be used to create the encrypted FingerprintManager.CryptoObject instance. This CryptoObject will, in turn, be used during the fingerprint authentication process. Cipher configuration involves obtaining a Cipher instance and initializing it with the key stored in the Keystore container. Add a new method named cipherInit to the FingerprintDemoActivity.java file to perform these tasks:

FingerprintDemoActivity.java

package com.blogspot.geekonjava.fingerprintdemo;

importandroid.security.keystore.KeyProperties;
importandroid.support.v7.app.AppCompatActivity;
importandroid.os.Bundle;
importandroid.app.KeyguardManager;
importandroid.hardware.fingerprint.FingerprintManager;
importandroid.widget.Toast;
importandroid.Manifest;
importandroid.content.pm.PackageManager;
importandroid.support.v4.app.ActivityCompat;
importandroid.security.keystore.KeyGenParameterSpec;
importandroid.security.keystore.KeyPermanentlyInvalidatedException;

importjava.security.KeyStore;
importjava.security.InvalidAlgorithmParameterException;
importjava.security.NoSuchAlgorithmException;
importjava.security.cert.CertificateException;
importjava.security.InvalidAlgorithmParameterException;
importjava.io.IOException;
importjava.security.InvalidKeyException;
importjava.security.KeyStoreException;
importjava.security.UnrecoverableKeyException;

importjavax.crypto.KeyGenerator;
importjavax.crypto.Cipher;
importjavax.crypto.NoSuchPaddingException;
importjavax.crypto.SecretKey;
importjavax.crypto.Cipher;

publicclassFingerprintDemoActivityextends AppCompatActivity {

privatestaticfinal String KEY_NAME = "example_key";
private FingerprintManager fingerprintManager;
private KeyguardManager keyguardManager;
private KeyStore keyStore;
private KeyGenerator keyGenerator;
private Cipher cipher;
.
.
.
publicbooleancipherInit() {
try {
cipher = Cipher.getInstance(
KeyProperties.KEY_ALGORITHM_AES + "/"
+ KeyProperties.BLOCK_MODE_CBC + "/"
+ KeyProperties.ENCRYPTION_PADDING_PKCS7);
} catch (NoSuchAlgorithmException |
NoSuchPaddingException e) {
thrownewRuntimeException("Failed to get Cipher", e);
}

try {
keyStore.load(null);
SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME,
null);
cipher.init(Cipher.ENCRYPT_MODE, key);
returntrue;
} catch (KeyPermanentlyInvalidatedException e) {
returnfalse;
} catch (KeyStoreException | CertificateException
| UnrecoverableKeyException | IOException
| NoSuchAlgorithmException | InvalidKeyException e) {
thrownewRuntimeException("Failed to init Cipher", e);
}
}
}
The getInstance method of the Cipher class is called to obtain a Cipher instance which is subsequently configured with the properties required for fingerprint authentication. The previously generated key is then extracted from the Keystore container and used to initialize the Cipher instance. Errors are handled accordingly and a true or false result returned based on the success or otherwise of the cipher initialization process.

Work is now complete on both the generateKey and cipherInit methods. The next step is to modify the onCreate method to call these methods and, in the event of a successful cipher initialization, create a CryptoObject instance.

Creating the CryptoObject Instance

Remaining within the FingerprintDemoActivity.java file, modify the onCreate method to call the two newly created methods and generate the CryptoObject as follows:

FingerprintDemoActivity.java

publicclassFingerprintDemoActivityextends AppCompatActivity {

privatestaticfinal String KEY_NAME = "example_key";
private FingerprintManager fingerprintManager;
private KeyguardManager keyguardManager;
private KeyStore keyStore;
private KeyGenerator keyGenerator;
private Cipher cipher;
private FingerprintManager.CryptoObject cryptoObject;

@Override
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fingerprint_demo);

.
.
.
if (!fingerprintManager.hasEnrolledFingerprints()) {

// This happens when no fingerprints are registered.
Toast.makeText(this,
"Register at least one fingerprint in Settings",
Toast.LENGTH_LONG).show();
return;
}

generateKey();

if (cipherInit()) {
cryptoObject =
new FingerprintManager.CryptoObject(cipher);
}
}
The final task in the project is to implement a new class to handle the actual fingerprint authentication.

Implementing the Fingerprint Authentication Handler Class

So far in this chapter most of the work has involved preparing for the fingerprint authentication in terms of the key, cipher and crypto object. The actual authentication is triggered via a call to the authenticate method of the FingerprintManager instance.

This method call, however, will trigger one of a number of callback events depending on the success or failure of the authentication. Both the authenticate method call and the callback handler methods need to be implemented in a class that extends the FingerprintManager.AuthenticationCallback class. Such a class now needs to be added to the project.

Navigate to the app -> java -> com.blogspot.geekonjava.fingerprintdemo entry within the Android Studio Project tool window and right-click on it. From the resulting menu, select the New -> Java Class option to display the Create New Class dialog. Name the class FingerprintHandler and click on the OK button to create the class.

Edit the new class file so that it extends FingerprintManager.AuthenticationCallback, imports some additional modules and implements a constructor method that will allow the application context to be passed through when an instance of the class is created (the context will be used in the callback methods to notify the user of the authentication status):

FingerprintHandler.java

package com.blogspot.geekonjava.fingerprintdemo;

importandroid.Manifest;
importandroid.content.Context;
importandroid.content.pm.PackageManager;
importandroid.hardware.fingerprint.FingerprintManager;
importandroid.os.CancellationSignal;
importandroid.support.v4.app.ActivityCompat;
importandroid.widget.Toast;

publicclassFingerprintHandlerextends
FingerprintManager.AuthenticationCallback {

private CancellationSignal cancellationSignal;
private Context appContext;

publicFingerprintHandler(Context context) {
appContext = context;
}
}
Next a method needs to be added which can be called to initiate the fingerprint authentication. When called, this method will need to be passed the FingerprintManager and CryptoObject instances. Name this method startAuth and implement it in the FingerprintHandler.java class file as follows (note that code has also been added to once again check that fingerprint permission has been granted):
publicvoidstartAuth(FingerprintManager manager, 
FingerprintManager.CryptoObject cryptoObject) {

cancellationSignal = new CancellationSignal();

if (ActivityCompat.checkSelfPermission(appContext,
Manifest.permission.USE_FINGERPRINT) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
manager.authenticate(cryptoObject, cancellationSignal, 0, this, null);
}
Next, add the callback handler methods, each of which is implemented to display a toast message indicating the result of the fingerprint authentication:
@Override
publicvoidonAuthenticationError(int errMsgId,
CharSequence errString) {
Toast.makeText(appContext,
"Authentication error\n" + errString,
Toast.LENGTH_LONG).show();
}

@Override
publicvoidonAuthenticationHelp(int helpMsgId,
CharSequence helpString) {
Toast.makeText(appContext,
"Authentication help\n" + helpString,
Toast.LENGTH_LONG).show();
}

@Override
publicvoidonAuthenticationFailed() {
Toast.makeText(appContext,
"Authentication failed.",
Toast.LENGTH_LONG).show();
}

@Override
publicvoidonAuthenticationSucceeded(
FingerprintManager.AuthenticationResult result) {

Toast.makeText(appContext,
"Authentication succeeded.",
Toast.LENGTH_LONG).show();
}
The final task before testing the project is to modify the onCreate method so that it creates a new instance of the FingerprintHandler class and calls the startAuth method. Edit the FingerprintDemoActivity.java file and modify the end of the onCreate method so that it reads as follows:
@Override
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fingerprint);
.
.
.
if (initCipher()) {
cryptoObject = new FingerprintManager.CryptoObject(cipher);
FingerprintHandler helper = new FingerprintHandler(this);
helper.fingerprintHandler(fingerprintManager, cryptoObject);
}
}

Testing the Project

With the project now complete run the app on a physical Android device or emulator session. Once running, either touch the fingerprint sensor or use the extended controls panel within the emulator to simulate a fingerprint touch as outlined the chapter entitled Using and Configuring the Android Studio 2 AVD Emulator. Assuming a registered fingerprint is detected a toast message will appear indicating a successful authentication as shown in Figure 62-6:



Stop the running app and relaunch it, this time using an unregistered fingerprint to attempt the authentication. This time a toast message should appear indicating that the authentication failed.

Summary

Fingerprint authentication within Android is a multistep process that can initially appear to be complex. When broken down into individual steps, however, the process becomes clearer. Fingerprint authentication involves the use of keys, ciphers and key storage combined with the features of the FingerprintManager class. This chapter has provided an introduction to these steps and worked through the creation of an example application project intended to show the practical implementation of fingerprint authentication within Android.

How to Use Google Map like TileView in Android

$
0
0
TileView is a subclass of android.view.ViewGroup that asynchronously displays tile-based images, with pan and zoom functionality, and support for features like markers, hotspots, paths, multiple levels of detail, and arbitrary coordinate systems.




Installation

Gradle:

compile'com.qozix:tileview:'2.2.2'
The library is hosted on jcenter, and is not currently available from maven.
repositories {  
jcenter()
}

Demo

A demo application, built in Android Studio, is available in the demo folder of this repository. Several use-cases are present; the RealMapTileViewActivity is the most substantive.

Quick Setup

  1. Tile an image into image slices of a set size, e.g., 256x256 (instructions)
  2. Name the tiles by the row and column number, e.g., 'tile-1-2.png' for the image tile that would be at the 2nd column from left and 3rd row from top.
  3. Create a new application with a single activity ('Main').
  4. Save the image tiles to your assets directory.
  5. Add compile 'com.qozix:tileview:2.2.2' to your gradle dependencies.
  6. In the Main Activity, use this for onCreate:
@Override
protectedvoidonCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
TileView tileView = new TileView( this );
tileView.setSize( 2000, 3000 ); // the original size of the untiled image
tileView.addDetailLevel( 1f, "tile-%d-%d.png", 256, 256);
setContentView( tileView );
}
That's it. You should have a tiled image that only renders the pieces of the image that are within the current viewport, and pans and zooms with gestures.

Basics

DetailLevels

detail-levels
A TileView instance can have any number of detail levels, which is a single image made up of many tiles; each DetailLevel exists in the same space, but are useful to show different levels of details (thus the class name), and to further break down large images into smaller tiles sets. These tiles are positioned appropriately to show the portion of the image that the device's viewport is displayed - other tiles are recycled (and their memory freed) as they move out of the visible area. Detail levels often show the same content at different magnifications, but may show different details as well - for example, a detail level showing a larger area will probably label features differently than a detail level showing a smaller area (imagine a TileView representing the United States may show the Rocky Mountains at a very low detail level, while a higher detail level may show individual streets or addresses.
Each detail level is passed a float value, indicating the scale value that it represents (e.g., a detail level passed 0.5f scale would be displayed when the TileView was zoomed out by 50%). Additionally, each detail level is passed an arbitrary data object that is attached to each tile and can provide instructions on how to generate the tile's bitmap. That data object is often a String, formatted to provide the path to the bitmap image for that Tile, but can be any kind of Object whatsoever - during the decode process, each tile has access to the data object for the detail level.

Tiles

A Tile is a class instance that represents a Bitmap - a portion of the total image. Each Tile provides position information, and methods to manage the Bitmap's state and behavior. Each Tile instanced is also passed to the TileView's BitmapProviderimplementation, which is how individual bitmaps are generated. Tile instances uses an equals method that compares only row, column and detail level, and are often passed in Set collections, so that Tile instances already in process are simply excluded by the unique nature of the Set if the program or user tries to add a single Tile more than once.
Each TileView instance must reference a BitmapProvider implementation to generate tile bitmaps. The interface defines a single method: public Bitmap getBitmap( Tile tile, Context context );. This method is called each time a bitmap is required, and has access to the Tile instance for that position and detail level, and a Context object to access system resources. The BitmapProvider implementation can generate the bitmap in any way it chooses - assets, resources, http requests, dynamically drawn, SVG, decoded regions, etc. The default implementation, BitmapProviderAssets, parses a String (the data object passed to the DetailLevel) and returns a bitmap found by file name in the app's assets directory.

Markers & Callouts

markers-callouts
A marker is just a View - any type of View - TextView, ImageView, RelativeLayout, whatever. A marker does not scale, but it's position updates as the TileView scales, so it's always attached to the original position. Markers are always laid as as if passed WRAP_CONTENT on both axes. Markers can have anchor points supplied, which are applied to width and height as offsets - to have a marker center horizontally to a point, and align at the bottom edge (like a typical map pin would do), you'd pass -0.5f and -1.0f (thus, left position is offset by half the width, and top is offset by the full height).
Markers can have traditional touch handlers, like View.OnClickListener, but these usually consume the event, so a drag operation might be interrupted when a user's finger crossed a marker View that had a consuming listener. Instead, considerTileView.setMarkerTapListener, which will react when a marker is tapped but will not consume the event.

To use a View as a marker:

tileView.addMarker( someView, 250, 500, -0.5f, -1.0f );
A callout might be better described as an "info window", and is functionally identical to a marker, with 2 differences: 1, all callouts exist on a layer above markers, and 2, any touch event on the containing TileView instance will remove all callouts. This would be prevented if the event is consumed (for example, by a View.OnClickListener on a button inside the Callout). Callouts are often opened in response to a marker tap event.
Callouts use roughly the same API as markers.

HotSpots

A HotSpot represents a region on the TileView that should react when tapped. The HotSpot class extendsandroid.graphics.Region and will virtually scale with the TileView. In addition to the Region API it inherits, a HotSpot also can accept a "tag" object (any arbitrary data structure), and a HotSpotTapListener. HotSpot taps are not consumed and will not interfere with the touch events examined by the TileView.

To create a HotSpot:

HotSpot hotSpot = new HotSpot();
hotSpot.setTag( this );
hotSpot.set( new Rect( 0, 0, 100, 100 ) ); // or any other API to define the region
tileView.addHotSpot( hotSpot, new HotSpot.HotSpotTapListener(){
@Override
publicvoidOnHotSpotTap( HotSpot hotSpot, int x, int y ) {
Activity activity = (Activity) hotSpot.getTag();
Log.d( "HotSpotTapped", "With access through the tag API to the Activity " + activity );
}
});

Paths

paths
TileView uses DrawablePath instances to draw paths above the tile layer. Paths will transform with the TileView as it scales, but do not deform - that's to say that a 10DP wide stroke will always be 10DP wide, but the points of the path will be scaled with the TileView.
DrawablePath instances are objects that relate an instance of android.graphics.Path with an instance ofandroid.graphics.Paint - there is no additional direct access API. Scaling is managed by a singel instance ofCompositePathView, which also supplies a default Paint instance that's used if any individual DrawablePath has a null value for it paint property.
Paths are not Views, and cannot be clicked. It is possible, however, to use the same Path instance on a HotSpot and aDrawablePath.
Note that TileView uses canvas.drawPath to render paths, which creates a higher-quality graphic, but can be a big hit on performance.

To add a path:

DrawablePath drawablePath = new DrawablePath();
drawablePath.path = // generate a Path using the standard android.graphics.Path API
drawablePath.paint = // generate a Paint instance use the standard android.graphics.Paint API
tileView.addPath( drawablePath );

Scaling

The setScale(1) method sets the initial scale of the TileView.
setScaleLimits(0, 1) sets the minimum and maximum scale which controls how far a TileView can be zoomed in or out. 0means completely zoomed out, 1 means zoomed in to the most detailed level (with the pixels of the tiles matching the screen dpi). For example by using setScaleLimits(0, 3) you allow users to zoom in even further then the most detailed level (stretching the image).
setMinimumScaleMode(ZoomPanLayout.MinimumScaleMode.FILL) controls how far a image can be zoomed out based on the dimensions of the image:
  • FILL: Limit the minimum scale to no less than what would be required to fill the container
  • FIT: Limit the minimum scale to no less than what would be required to fit inside the container
  • NONE: Limit to the minimum scale level set by setScaleLimits
When using FILL or FIT, the minimum scale level of setScaleLimits is ignored.

Hooks and Listeners

A TileView can have any number of ZoomPanListeners instances listening for events relating to zoom and pan actions, including: onPanBeginonPanUpdateonPanEndonZoomBeginonZoomUpdate, and onZoomEnd. The last argument passed to each callback is the source of the event, represented by ZoomPanListener.Origin enum: DRAGFLINGPINCH, or null (which indicates a programmatic pan or zoom).

To use a ZoomPanListener:

tileView.addZoomPanListener( new ZoomPanListener(){
voidonPanBegin( int x, int y, Origination origin ){
Log.d( "TileView", "pan started..." );
}
voidonPanUpdate( int x, int y, Origination origin ){}
voidonPanEnd( int x, int y, Origination origin ){}
voidonZoomBegin( float scale, Origination origin ){}
voidonZoomUpdate( float scale, Origination origin ){}
voidonZoomEnd( float scale, Origination origin ){}
});
Additionally, TileView reports most significant operations to hooks. TileView implements ZoomPanLayout.ZoomPanListener,TileCanvasViewGroup.TileRenderListener, and DetailLevelManager.DetailLevelChangeListener, and it's super class implements GestureDetector.OnGestureListener,GestureDetector.OnDoubleTapListener,ScaleGestureDetector.OnScaleGestureListener, andTouchUpGestureDetector.OnTouchUpListener.

As such, the following hooks are available to be overridden by subclasses of TileView:

protectedvoidonScrollChanged( int l, int t, int oldl, int oldt );
publicvoidonScaleChanged( float scale, float previous );
publicvoidonPanBegin( int x, int y, Origination origin );
publicvoidonPanUpdate( int x, int y, Origination origin );
publicvoidonPanEnd( int x, int y, Origination origin );
publicvoidonZoomBegin( float scale, Origination origin) ;
publicvoidonZoomUpdate( float scale, Origination origin );
publicvoidonZoomEnd( float scale, Origination origin );
publicvoidonDetailLevelChanged( DetailLevel detailLevel );
publicbooleanonSingleTapConfirmed( MotionEvent event );
publicvoidonRenderStart();
publicvoidonRenderCancelled();
publicvoidonRenderComplete();
publicbooleanonScroll( MotionEvent e1, MotionEvent e2, float distanceX, float distanceY );
publicbooleanonDown( MotionEvent event );
publicbooleanonFling( MotionEvent event1, MotionEvent event2, float velocityX, float velocityY );
publicvoidonLongPress( MotionEvent event );
publicvoidonShowPress( MotionEvent event );
publicbooleanonSingleTapUp( MotionEvent event );
publicbooleanonSingleTapConfirmed( MotionEvent event );
publicbooleanonDoubleTap( MotionEvent event );
publicbooleanonDoubleTapEvent( MotionEvent event );
publicbooleanonScaleBegin( ScaleGestureDetector scaleGestureDetector );
publicvoidonScaleEnd( ScaleGestureDetector scaleGestureDetector );
publicbooleanonScale( ScaleGestureDetector scaleGestureDetector );
publicbooleanonTouchUp();
Be careful to note where the method was specified, however; for example, onScaleBeginonScale, and onScaleEnd are provided by android.view.GestureDetector.OnScaleGestureListener, so are only aware of scale operations initiated by a gesture (pinch), while onScaleChanged is defined by ZoomPanLayout and will report any changes to scale from any source, so is probably more useful. See the javadocs for specifications.

How Do I...?

...create tiles from an image?

See the wiki entry here.

...use relative coordinates (like latitude and longitude)?

The TileView method defineBounds( double left, double top, double right, double bottom ) establishes a coordinate system for further positioning method calls (e.g., scrollToaddMarker, etc). After relative coordinates are established by invoking the defineBounds method, any subsequent method invocations that affect position and accept double parameters will compute the value as relative of the provided bounds, rather than absolute pixels. That's to say that:
  1. A TileView instance is initialized with setSize( 5000, 5000 );
  2. That TileView instance calls defineBounds( 0, 100, 0, 100 );
  3. That TileView instance calls scrollTo( 25d, 50d );
  4. That TileView will immediately scroll to the pixel at 1250, 2500.
This same logic can be used to supply latitude and longitude values to the TileView, by supplying the left and rightmost longitudes, and the top and bottommost latitudes. Remember that traditional coordinates are expressed (lat, lng), but TileView (and most UI frameworks) expect position values to be expressed as (x, y) - so positioning methods should be sent (lng, lat).

...use a third party image loading library like Picasso, Glide, UIL, etc?

Implement your own BitmapProvider, which has only a single method, then pass an instance of that class toTileView.setImageProvider.

Here's an example using Picasso (untested):

publicclassBitmapProviderPicassoimplements BitmapProvider {
public Bitmap getBitmap( Tile tile, Context context ) {
Object data = tile.getData();
if( data instanceof String ) {
String unformattedFileName = (String) tile.getData();
String formattedFileName = String.format( unformattedFileName, tile.getColumn(), tile.getRow() );
return Picasso.with( context ).load( path ).get();
}
returnnull;
}
}

And tell the TileView to use it:

tileView.setBitmapProvider( new BitmapProviderPicasso() );

...load tile bitmaps from a website?

Again, implement your own BitmapProvider. You could roll your own using URL and BitmapFactory.decodeStream, or leverage a third-party library intended for downloading images. Note that the BitmapProviderPicasso example above would work with network images out of the box, just make sure the string it's getting is a valid URL:
tileView.addDetailLevel( 1.0f, "http://example.com/tiles/%d-%d.png" );

...add my custom View to the TileView, so that it scales?

scaling-layout

Create a layout, add whatever views you want to it, and pass the layout to TileView.addScalingViewGroup:

RelativeLayout relativeLayout = new RelativeLayout( this );
ImageView logo = new ImageView( this );
logo.setImageResource( R.drawable.logo );
RelativeLayout.LayoutParams logoLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT );
logoLayoutParams.addRule( RelativeLayout.CENTER_IN_PARENT );
relativeLayout.addView( logo, logoLayoutParams );
tileView.addScalingViewGroup( relativeLayout );

...add my custom View to the TileView, so that it does not scale?


TileView is a ViewGroup, and views can be added normally. No scaling behavior is passed directly, so unless you do something to make it scale, it will behave as would any other View, although the dimensions passed to it will reflect the size defined by the setSize API, not the dimensions of the TileView on screen.

Create a layout, add whatever views you want to it, and add it using addView:

RelativeLayout relativeLayout = new RelativeLayout( this );
ImageView logo = new ImageView( this );
logo.setImageResource( R.drawable.logo );
RelativeLayout.LayoutParams logoLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT );
logoLayoutParams.addRule( RelativeLayout.CENTER_IN_PARENT );
relativeLayout.addView( logo, logoLayoutParams );
tileView.addView( relativeLayout );

...add a down-sampled image beneath the tile layer?

downsample
Since TileView is a ViewGroup, and it will lay out it's children according to the dimension supplied by the setSize API, adding a standard ImageView at index 0 with the image source a small version of the tiled composite image will create the down-sampled effect. Generally, the image should be low resolution and file size (images smaller than 500 pixels square should be OK).
ImageView downSample = new ImageView( this );
downSample.setImageResource( R.drawable.downsampled_image );
tileView.addView( downSample, 0 );
Hope you like this post and if you can download this library from here.
Subscribe us

WebJars - Life saviour for Java Dev

$
0
0
Nowadays Java web applications are use many web libraries like jQuery, AngularJs, ReactJS, Backbone.js and Twitter Bootstrap. The conventional approach to utilize those libraries is to find and download the JavaScript and CSS source then simply duplicate it into a project.

And it takes more time to find correct js and css file so now i am telling you savior for saving your time for this named WebJars.



Suppose you want use what I call a web artifact library such as bootstrap in your Java based web app. Bootstrap’s Getting started guide describes how you could use it directly from the proposed CDN or via tools like bower or npm.

In this post I might want to demonstrate to you other possibility: webjars.

First I will describe how to use it and then give some background information.

Spring Boot

You can find the source for this example on Github.



To add bootstrap as a webjar to your Spring Boot projects simply add the following dependency to your build file:

For gradle it would be :

build.gradle
dependencies {
compile 'org.webjars:bootstrap:3.3.1'
}

For maven it would be:

pom.xml
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.1</version>
</dependency>
Now when you start your application and point your browser to
http://localhost:8080/webjars/bootstrap/3.3.1/css/bootstrap.css 
you should see bootstrap’s css in the browser. This means that in your html files you can these links to access bootstrap:
<linkrel="stylesheet"href="/webjars/bootstrap/3.3.1/css/bootstrap.min.css">
<script src="/webjars/bootstrap/3.3.1/js/bootstrap.min.js"></script>

Grails 3

Since Grails 3 is based upon Spring Boot you only need to add the bootstrap webjar dependency to your build.gradle as described in the previous section. Everything else also works exactly the same.

Grails 2

For Grails 2 I could not get it running out of the box using the servlet 3 approach. Anyway here are my attempts so far:
Assume you named your grails application grails244_webjar and thus you can access it from
http://localhost:8080/grails244_webjar/
When you add the compile 'org.webjars:bootstrap:3.3.1' dependency to your BuildConfig.groovy and then try to access
http://localhost:8080/grails244_webjar/webjars/bootstrap/3.3.1/css/bootstrap.css 
you will get a HTTP 404. http://localhost:8080/webjars/bootstrap/3.3.1/css/bootstrap.css did not work for me either. My guess is that it has something to do with the way the GrailsDispatcherServlet is working.

Servlet

But: taking the servlet 2.x approach as described on this page works:

add the dependency compile 'org.webjars:webjars-servlet-2.x:1.1' to your BuildConfig.groovy

Add the WebjarServlet to web.xml (first you need to invoke grails install-templates to get a web.xml) and add the following to it:

src/templates/war/web.xml

<servlet>
<servlet-name>WebjarsServlet</servlet-name>
<servlet-class>org.webjars.servlet.WebjarsServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>WebjarsServlet</servlet-name>
<url-pattern>/webjars/*</url-pattern>
</servlet-mapping>
Then the URL
http://localhost:8080/grails244_webjar/webjars/bootstrap/3.3.1/css/bootstrap.min.css 
works.

Background

A webjar is nothing special. The only important thing to know is that since the Servlet Specification 3.0 all files underneath the path META-INF/resources are treated like static resources and can be accessed directly from the browser without having to do anything special.

Example

You take a servlet 3.0 compliant container like a modern Tomcat, Jetty, etc. Then you create a jar with a file META-INF/resources/hello.txt containing the text hello world. Now create a war file and put this jar file into WEB-INF/lib. When you start your Tomcat or Jetty and point your browser to http://localhost:8080/readme.txt it should display the text hello world.

The idea behind webjars is to package all files like css, js, images needed by the browser together in a jar file. This has the following big advantages:

Advantages


  • You can leverage maven repositories e.g. by putting webjars into maven central or bintray as any ordinary jar file
  • You can leverage your build tool’s (gradle, maven) dependency management support.
  • You do not have to check in js or css files anymore and you do not have to copy these files around during at build time

Because you can leverage your build tool’s dependency management support means that you can also define and use transitive dependencies for your web artifacts

Let’s take bootstrap again as an example. 

Note that it has a transitive dependency to jQuery. And if you have a look at the pom file of bootstrap’s webjar you can see that it has a dependency declaration on jQuery including the exact version it wants:

pom.xml (of bootstrap’s webjar)

<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>1.11.1</version>
</dependency>
This means you only have to declare the dependency to bootstrap in your maven/gradle file and get the right jQuery webjar for free.

If you have a look at http://www.webjars.org/ you can see that webjars for many popular Javascript/css frameworks/libraries already exist and are available via maven central.

Conclusion

In my opinion using webjars is a great way to use web artifacts like Javascript and css files because it is possible to leverage the existing maven dependency management tools and it is not necessary to fiddle around with individual files.

Since I discovered webjars they are my preferred way to use web artifacts in Java based projects especially since most of the popular frameworks and libraries are already available as webjars. And even if you want to provide your own web artifacts as webjar you simply have to stick them in a jar file underneath META-INF/resources and you’re done.

Why waste to buy Apples iPhone 7 and iPhone 7 Plus

$
0
0
Tech company Apple's iPhone series launched new iPhone 7 and iPhone 7 Plus. The company has the most sophisticated and innovative features in these iPhones d, whether it be the processor or camera or headphone jack.
But in fact, Apple features already  in cheap Chinese smartphones available in the market exists. Falling sales of its handsets was believed that the Apple will bring a new technology, however, so nothing happened.


The heavy spending on research

Currently, about 85 per cent of the smartphone market is dominated by Samsung and Chinese company Huawei.
Because of this, Apple has launched the iPhone in haste. Samsung's most advanced phone Galaxy Note 7 due to a malfunction in the battery has been recalled that Apple wanted to take advantage of the situation, but it does not do.

With this Apple iPhone 7 audio jack removal company doing such publicity as it is a strong technology. While the world today is obsessed with Pokemon Go run Apple 15 years old Super Mario games is saying.

Apple in 2011 for $ 2.4 billion on research and development (16,000 crore) spent the last year has been increased to Rs 54,000 crore.

These features have already arrived: the iPhone 7

1. Dual Lens Camera

Apple's first iPhone 7 Plus has a dual lens camera. But tell you that the Chinese company Huawei and Honor smartphone has brought this technology several years ago.

2. Fast Charging

This technology already exists in the Android smartphones. Moto G 4 and G-4 plus the Turbo Charging technology has come.
Android phones in the market in addition to several features.

3. Display and Design

The display resolution is 1920 x 1080 pixels of the iPhone 7. However, Samsung is one plus the premium smartphones more resolution.

4. Water and dust-proof

This feature Sony, Samsung, Huawei, has already in their handsets. Let me tell you that the Samsung Galaxy Note 7 is even more water-proof capacity.

5. Headphones jack

Apple has said the bold step to remove headphone audio jack. It is connected to the charging jack. IPhone users ie 7 and 7 Plus will not be able to use headphones while charging. But P-9 of Huawei smartphone with dual camera headphone jack has been delivered separately.

6. capacity MicroSD card

Android smartphones are getting better, though, given the storage capacity is extended by Apple. But Android smartphones nowadays are coming up in 2 terabyte memory card can be fitted.

7. Stereo speakers

The smartphone speaker stereo technology is not new. HTC, Huawei smartphones this technology has already been granted.

Hope you like this post. If you want more then subscribe us.

Run Node.JS in Android app

$
0
0
Android is more customisable and easy to use mobile operating system nowadays. And in upcoming growing language node.js is dramatic up with their great power which uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.

And for developer would be feel good when they integrate Node.Js with their android application to use that power with existing application.



Here is the library which do it same for you named as Node-Android library which is used to run Node.js on Android by rewrite Node.js in Java with the compatible API.

Download this library from here

Now lets dive with process of integrate and their features :

Build

Clone the code, open Android Studio (1.*) and import the project.
For Eclipse ADT user, refer to this.

Javascript code injection

> adb shell amstart-a android.intent.action.VIEW -n com.iwebpp.nodeandroid/.MainActivity -e js "var run = function () { return 'hello world'; } run();"

Features


  • Node.js 0.10.x compatible API
  • Multi-threading: run separate node context in Java thread
  • libUV native support
  • Timer, set/clear Timeout/Interval
  • EventEmitter
  • Stream
  • HttpParser(rewrite http-parser.c in java)
  • HTTP
  • HTTPP(run http over udp)
  • TCP
  • UDT(udp transport)
  • DNS
  • URL
  • IPv6
  • for API usage, check 
  • WebSocket/WebSocketServer supported, check 
  • Connect middleware
  • Crypto: NACL support, public box,secret box,signature/verify
  • SecureWebSocket over NACL

JS runtime


  1. Rhino supported
  2. Exposed node-android packages: com.iwebpp.node.http, com.iwebpp.node.stream, com.iwebpp.node.net, etc
  3. Exposed node-android classes: com.iwebpp.node.EventEmitter2, com.iwebpp.node.Dns, com.iwebpp.node.Url, etc
  4. Exposed node-android native context in JS standard scope as NodeCurrentContext alias NCC
  5. Exposed Android API: android.util.Log
  6. NodeJS compatible internal modules are available in JS standard scope
  7. Exposed WebSocket classes: com.iwebpp.wspp.WebSocket, com.iwebpp.wspp.WebSocketServer


JS usage

In case Rhino, create class 'MyScript' extends from com.iwebpp.node.js.rhino.Host
Implement 'public String content()' in 'MyScript' to return user script
Execute JS engine in a separate Java Thread with 'MyScript.execute()'
When authoring script, please use NodeCurrentContext(alias NCC) in node-android API

Hope you like this tutorial and if you use this library then please hand on this blog with sample app. Just send us sample app source code. So we can help more people easily.
Subscribe us to get more juicy and fresh article like this.

How to add Dynamic Navigation Drawer Items

$
0
0
In the last few posts, we have executed material navigation drawer with or without using the design support library where items of the navigation drawer were static, that is, they were predefined.
In any case, there are times when you need things to change as indicated by certain client activities or prefrences. In this post, we will progressively add things to a navigation drawer from a database with design support library, MySQLi and PHP scripts.

1)Creating some database tables:

This should always be the very first step whenever there’s a database involved. Here, we create a demo database hosted locally via Apache Web Server using XAMPP to serve the purpose of this post. For XAMPP – https://www.apachefriends.org/index.html.
Below is the screenshot of a demo table  – ‘test‘ – just holding some string values in column ‘Items‘.


2)PHP Script:

Here, We return a JSON response containing names of all the great houses from ASOIAF as declared in the above table.

getItems.php

$db_name = 'test';
$host_name = 'localhost';
$username = 'root';
$password = '';
$table_name = 'test_table';


$db = new mysqli($host_name,$username,$password,$db_name);

if($db->connect_errno>0){

die('Unable to connect -> '.$db->error);
}

$queryString="Select * from $table_name";

if(!$result = $db->query($queryString)){

die('error'. $db->error);

}

$temp=0;
$itemArray = array();

while ($row = $result->fetch_assoc()) {
$itemArray[$temp] = $row['Items'];
$temp++;
}

echo json_encode($itemArray);

$result->free();

The response from the above script:

[“House Lannister”,”House Stark”,”House Targaryen”,”House Martell”,”House Tyrell”,”House Tully”]

3)Include Desing Support Library Dependency:

Now, fire up the Android Studio, select an ‘EMPTY‘ activity and include the design support library in your Gradle. Open Module(App) Gradle file and add the below dependencies. (If prompted update your android SDK).
//Code : compile ‘com.android.support:design:23.1.1’

dependencies {
compile fileTree(dir:'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
}

4)Creating a Blank Menu Resource:


  1. Create a new Android Resouce Directory of resource type ‘menu‘ in res and name it ‘menu‘.
  2. Create a new menu resource file – ‘drawer_menu.xml‘ in the menu directory.

This blank menu is attached with navigationalView to inflate menu items. We will programmatically add items to this menu later in this post.

5)Modifying Styles:

Open your style.xml file from the values directory and change the parent theme to ‘Theme.AppCompat.NoActionBar’ since we will be implementing a toolbar.

styles.xml

<resources>

<!-- Base application theme. -->
<stylename="AppTheme"parent="Theme.AppCompat.NoActionBar">
<!-- Customize your theme here. -->
<itemname="colorPrimary">@color/colorPrimary</item>
<itemname="colorPrimaryDark">@color/colorPrimaryDark</item>
<itemname="colorAccent">@color/colorAccent</item>
</style>

</resources>

6)Adding the internet permission:

Open up your AndroidManifest.xml file and add
<uses-permissionandroid:name=”android.permission.INTERNET”/>
above the application declaration.

7)Designing the Navigation Drawer:

Navigation View inflates navigation items from a menu resource. The hierarchy of elements is shown below:

Basically, a DrawerLayout holds two items – one is the NavigationView and the other Container view.
Container view includes a frameLayout to inflate fragment view and a toolbar. The app: menu attribute of navigation view refers to the blank menu resource created above.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">


<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
/>

<FrameLayout
android:id="@+id/containerView"
android:background="#FFF"
android:layout_width="match_parent"
android:layout_height="match_parent"/>



</LinearLayout>

<android.support.design.widget.NavigationView
android:id="@+id/navigationView"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_gravity="left"
app:headerLayout="@drawable/header"/>

</android.support.v4.widget.DrawerLayout>

6)Retrieving required data from the database.

Now the thing is: To dynamically add navigation items, we first get all the elements to be inflated from the database and then add those to the menu by passing our menu as a parameter to an async task.
Here, JsonReader is used to parse the response from the PHP script.

MainActivity.java

package com.blogspot.geekonjava.navdrawer;

importandroid.support.design.widget.NavigationView;
importandroid.support.v4.widget.DrawerLayout;
importandroid.support.v7.app.ActionBarDrawerToggle;
importandroid.support.v7.app.AppCompatActivity;
importandroid.os.Bundle;
importandroid.support.v7.widget.Toolbar;
importandroid.util.JsonReader;
importandroid.util.Log;
importandroid.view.Menu;
importandroid.view.MenuItem;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.net.URL;
importjava.net.URLConnection;
importjava.util.ArrayList;

publicclassMainActivityextends AppCompatActivity {


@Override
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

/**
* Setting up the DrawerLayout,NavigationView and Toolbar.
*/


final DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

/**
* Accessing the NavigationView menu.
* The getMenu method returns menu resource used by navigationView.
* Later,we will add items to this menu.
*/

Menu drawerMenu = navigationView.getMenu();

/**
* Creating an ArrayList to hold items for the above Menu.
*/
ArrayList items = new ArrayList();

/**
* Creating object of NavMenuClass defined later.
* We pass our drawerMenu and ArrayList items to NavMenuClass.
* And later , use this object to access both arrayList holding the items and the drawer menu.
*/

NavMenuClass navMenuObject = new NavMenuClass(drawerMenu,items);

/**
* Creating object of AsyncClass - 'PopulateMenuItems' defined later to get items from the database.
* Here,we pass the above navMenuObject as parameter to async class.
*/

PopulateMenuItems populateMenuItems = new PopulateMenuItems();
populateMenuItems.execute(navMenuObject);

/**
* This is required to handle the onItemClick on Navigation Drawer Items.
*/

NavigationView.OnNavigationItemSelectedListener item_click_listener = new NavigationView.OnNavigationItemSelectedListener() {
@Override
publicbooleanonNavigationItemSelected(MenuItem item) {

/** This a sample code to change fragments depending on the menu item.
*
* if(item.toString="someConditionalText")
* {
* FragmentManager mFragmentManager;
* FragmentTransaction mFragmentTransaction;
*
* mFragmentManager = getSupportFragmentManager();
* mFragmentTransaction = mFragmentManager.beginTransaction();
*
* mFragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();
* }
*/
drawerLayout.closeDrawers();
returntrue;
}
};

/**
* Attaching the above listener to NavigationView
*/

navigationView.setNavigationItemSelectedListener(item_click_listener);

/**
* Setting up Drawer Toggle for Toolbar.
*/


ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout, toolbar,R.string.app_name,
R.string.app_name);

drawerLayout.setDrawerListener(mDrawerToggle);

mDrawerToggle.syncState();




}

/**
* NavMenuClass holds the NavigationView menu and an ArrayList which holds items to be populated in menu.
*/

classNavMenuClass{
Menu menu;
ArrayList items;

publicNavMenuClass(Menu menu,ArrayList items){

this.items = items;
this.menu = menu;

}

public Menu getMenu(){
return menu;
}

public ArrayList getItems(){
return items;
}

}

/**
* An async task accepts 3 parameters:
* Params -> the type of the parameters sent to the task upon execution.
* Progress -> the type of the progress units published during the background computation.
* Result -> the type of the result of the background computation.
*
* For more on asyncTack checkout this answer from stackOverflow :
* http://stackoverflow.com/a/6053673/5087027
*
**/


publicclassPopulateMenuItemsextends android.os.AsyncTask<navmenuclass,void,navmenuclass>{

@Override
protected NavMenuClass doInBackground(final NavMenuClass... params) {

/**
* Accessing the navMenuObject passed to this class.
*/
NavMenuClass navMenuObject = params[0];

/**
* Accessing arrayList passed with this object to add items.
*/

ArrayList items = navMenuObject.getItems();

try {

/**
* Here, declare the URL. If on localhost, just write the localhost ip and add the path.
* The url object parses the urlString and throws 'MalformedURLException' if URL could not be parsed.
* OpenConnection returns a connection referred by URL.
*/

String urlString = "http://192.168.0.100/getItems.php";
URL url = new URL(urlString);
URLConnection urlConnection = url.openConnection();

/**
* InputStream reads the response in bytes and by InputStreamReader it is converted into characters.
*/

InputStream inputStream = urlConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");

/**
* JsonReader is used to parse the below output.
* ["House Lannister","House Stark","House Targaryen","House Martell","House Tyrell","House Tully"]
* In JSON , array stats with '['(Square Bracket) and object with '{'(Curly Bracket)).
* More on JsonReader : http://developer.android.com/reference/android/util/JsonReader.html.
*/

JsonReader jsonReader = new JsonReader(inputStreamReader);

jsonReader.beginArray();
while (jsonReader.hasNext()){
/**
* Get the nextString of the JSON array and add it to the arrayList - 'items'.
*/
String name = jsonReader.nextString();
items.add(name);
}
jsonReader.endArray();

return params[0];
}

catch (Exception e){
Log.e("Exception", e.toString());
}

returnnull;
}

/**
* @param NavMenuClass accepted by onPostExecute is returned by the above doInBackground method.
* Here, we add ArrayList items added in doInBackground to Menu.
*/

@Override
protectedvoidonPostExecute(NavMenuClass NavMenuObject) {
/**
* Accessing menu of NavMenuObject.
*/

Menu menu = NavMenuObject.getMenu();

/**
* Accessing items of ArrayList from NavMenuObject.
*/

ArrayList arrayList = NavMenuObject.getItems();

/**
* Adding items to menu by iterating the ArrayList.
*/

for(int temp=0;temp<=arrayList.size()-1;temp++){
menu.add(arrayList.get(temp).toString());
}

}
}
}

//Ignore

</navmenuclass,void,navmenuclass>

Hope you enjoy this tutorial and if it useful for you and want some more interesting article then subscribe us.

Drag and Drop 3D Objects Using Three.js

$
0
0
In my previous article on Three.js in which i teach you how to make 3D objects with WebGL using Three.js and if you're new for this then you can read that article from here.
But today we're taking some extra step in this field and now you can learn how to drag drop that 3d objects which you made in previous tutorial.



The Drag and Drop feature is one of important features of nearly every interactive environment. Use the mouse to interact and drag and drop objects is very native. However this feature is not supported in three.js by default. In our tenth lesson we explain how to implement this drag-and-drop function.

Demo



The demo generates randomly located spheres that you can move with your mouse. Simply drag a sphere, move it to another place, and then drop it. To rotate the scene, you can use the mouse as well (we use THREE.OrbitControls).

Preparation

To start with, please create a new index.html file with the following code:

index.html

<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="utf-8"/>
<metaname="author"content="Script Tutorials"/>
<title>WebGL With Three.js - Lesson 10 - Drag and Drop Objects | Script Tutorials</title>
<metaname="viewport"content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<linkhref="css/main.css"rel="stylesheet"type="text/css"/>
</head>
<body>
<script src="js/three.min.71.js"></script>
<script src="js/THREEx.WindowResize.js"></script>
<script src="js/OrbitControls.js"></script>
<script src="js/stats.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
This basic code connects all the necessary libraries.

Skeleton of the scene

Now create another file – ‘script.js’ and put it into ‘js’ folder. Place the following code into the file:

js/script.js

var lesson10 = {
scene: null, camera: null, renderer: null,
container: null, controls: null,
clock: null, stats: null,
plane: null, selection: null, offset: new THREE.Vector3(), objects: [],
raycaster: new THREE.Raycaster(),
init: function() {
// Create main scene
this.scene = new THREE.Scene();
this.scene.fog = new THREE.FogExp2(0xcce0ff, 0.0003);
var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
// Prepare perspective camera
var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 1, FAR = 1000;
this.camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
this.scene.add(this.camera);
this.camera.position.set(100, 0, 0);
this.camera.lookAt(new THREE.Vector3(0,0,0));
// Prepare webgl renderer
this.renderer = new THREE.WebGLRenderer({ antialias:true });
this.renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
this.renderer.setClearColor(this.scene.fog.color);
// Prepare container
this.container = document.createElement('div');
document.body.appendChild(this.container);
this.container.appendChild(this.renderer.domElement);
// Events
THREEx.WindowResize(this.renderer, this.camera);
document.addEventListener('mousedown', this.onDocumentMouseDown, false);
document.addEventListener('mousemove', this.onDocumentMouseMove, false);
document.addEventListener('mouseup', this.onDocumentMouseUp, false);
// Prepare Orbit controls
this.controls = new THREE.OrbitControls(this.camera);
this.controls.target = new THREE.Vector3(0, 0, 0);
this.controls.maxDistance = 150;
// Prepare clock
this.clock = new THREE.Clock();
// Prepare stats
this.stats = new Stats();
this.stats.domElement.style.position = 'absolute';
this.stats.domElement.style.left = '50px';
this.stats.domElement.style.bottom = '50px';
this.stats.domElement.style.zIndex = 1;
this.container.appendChild( this.stats.domElement );
// Add lights
this.scene.add( new THREE.AmbientLight(0x444444));
var dirLight = new THREE.DirectionalLight(0xffffff);
dirLight.position.set(200, 200, 1000).normalize();
this.camera.add(dirLight);
this.camera.add(dirLight.target);
....
},
addSkybox: function() {
....
},
onDocumentMouseDown: function (event) {
....
},
onDocumentMouseMove: function (event) {
....
},
onDocumentMouseUp: function (event) {
....
}
};
// Animate the scene
function animate() {
requestAnimationFrame(animate);
render();
update();
}
// Update controls and stats
function update() {
var delta = lesson10.clock.getDelta();
lesson10.controls.update(delta);
lesson10.stats.update();
}
// Render the scene
function render() {
if (lesson10.renderer) {
lesson10.renderer.render(lesson10.scene, lesson10.camera);
}
}
// Initialize lesson on page load
function initializeLesson() {
lesson10.init();
animate();
}
if (window.addEventListener)
window.addEventListener('load', initializeLesson, false);
elseif (window.attachEvent)
window.attachEvent('onload', initializeLesson);
elsewindow.onload = initializeLesson;
With this code, we prepared the scene – camera (THREE.PerspectiveCamera), renderer (THREE.WebGLRenderer), controller (THREE.OrbitControls), light (THREE.DirectionalLight), and various event handlers (empty for now, we will add it’s code further).

Skybox

Now, let’s add the skybox – blue-white gradient with shader. First of all, add two shaders in the beginning of our script.js file:
sbVertexShader = [
"varying vec3 vWorldPosition;",
"void main() {",
" vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
" vWorldPosition = worldPosition.xyz;",
" gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"}",
].join("\n");
sbFragmentShader = [
"uniform vec3 topColor;",
"uniform vec3 bottomColor;",
"uniform float offset;",
"uniform float exponent;",
"varying vec3 vWorldPosition;",
"void main() {",
" float h = normalize( vWorldPosition + offset ).y;",
" gl_FragColor = vec4( mix( bottomColor, topColor, max( pow( h, exponent ), 0.0 ) ), 1.0 );",
"}",
].join("\n");
So both shaders (vertex and fragment shaders) will be added to our page. Now we can add
// Display skybox
this.addSkybox();
right after we added our light. Here is the code for the ‘addSkybox’ function:
addSkybox: function() {
var iSBrsize = 500;
var uniforms = {
topColor: {type: "c", value: new THREE.Color(0x0077ff)}, bottomColor: {type: "c", value: new THREE.Color(0xffffff)},
offset: {type: "f", value: iSBrsize}, exponent: {type: "f", value: 1.5}
}
var skyGeo = new THREE.SphereGeometry(iSBrsize, 32, 32);
skyMat = new THREE.ShaderMaterial({vertexShader: sbVertexShader, fragmentShader: sbFragmentShader, uniforms: uniforms, side: THREE.DoubleSide, fog: false});
skyMesh = new THREE.Mesh(skyGeo, skyMat);
this.scene.add(skyMesh);
},

Additional objects

After the skybox, we can add spheres with random radius and position:
// Add 100 random objects (spheres)
var object, material, radius;
var objGeometry = new THREE.SphereGeometry(1, 24, 24);
for (var i = 0; i < 50; i++) {
material = new THREE.MeshPhongMaterial({color: Math.random() * 0xffffff});
material.transparent = true;
object = new THREE.Mesh(objGeometry.clone(), material);
this.objects.push(object);
radius = Math.random() * 4 + 2;
object.scale.x = radius;
object.scale.y = radius;
object.scale.z = radius;
object.position.x = Math.random() * 50 - 25;
object.position.y = Math.random() * 50 - 25;
object.position.z = Math.random() * 50 - 25;
this.scene.add(object);
}
As you see, all the objects were added to the ‘objects’ array. We will use this array for raycaster (THREE.Raycaster) to determinate if an object is intersected with our mouse.

Now pay attention, in order to implement the drag and drop function, we need to determine at what axis (plane) we need to move the selected object. As we know, mouse moves in two dimensions, while our scene works in three. To find an offset of dragging, we will use an invisible ‘helper’ – plane (add this code below the code where we add the spheres):
// Plane, that helps to determinate an intersection position
this.plane = new THREE.Mesh(new THREE.PlaneBufferGeometry(500, 500, 8, 8), new THREE.MeshBasicMaterial({color: 0xffffff}));
this.plane.visible = false;
this.scene.add(this.plane);

onDocumentMouseMove

Now we need to implement the first event handler: onDocumentMouseMove. When we press the mouse button, we need to define position where we pressed the key, then we create a 3D vector of this point, unproject it, set the raycaster position, and find all intersected objects (where we clicked the mouse button). Then we disable the controls (we don’t need to rotate the scene while we are dragging the selection). The first visible element will be set as the selection, and we need to save the offset:
onDocumentMouseDown: function (event) {
// Get mouse position
var mouseX = (event.clientX / window.innerWidth) * 2 - 1;
var mouseY = -(event.clientY / window.innerHeight) * 2 + 1;
// Get 3D vector from 3D mouse position using 'unproject' function
var vector = new THREE.Vector3(mouseX, mouseY, 1);
vector.unproject(lesson10.camera);
// Set the raycaster position
lesson10.raycaster.set( lesson10.camera.position, vector.sub( lesson10.camera.position ).normalize() );
// Find all intersected objects
var intersects = lesson10.raycaster.intersectObjects(lesson10.objects);
if (intersects.length > 0) {
// Disable the controls
lesson10.controls.enabled = false;
// Set the selection - first intersected object
lesson10.selection = intersects[0].object;
// Calculate the offset
var intersects = lesson10.raycaster.intersectObject(lesson10.plane);
lesson10.offset.copy(intersects[0].point).sub(lesson10.plane.position);
}
}

onDocumentMouseMove

Having the selection (sphere), we can change position of the sphere (to another position where our mouse pointer is). But if there is no any selection, we need to update position of our help plane. It always needs to look directly at our camera position:
onDocumentMouseMove: function (event) {
event.preventDefault();
// Get mouse position
var mouseX = (event.clientX / window.innerWidth) * 2 - 1;
var mouseY = -(event.clientY / window.innerHeight) * 2 + 1;
// Get 3D vector from 3D mouse position using 'unproject' function
var vector = new THREE.Vector3(mouseX, mouseY, 1);
vector.unproject(lesson10.camera);
// Set the raycaster position
lesson10.raycaster.set( lesson10.camera.position, vector.sub( lesson10.camera.position ).normalize() );
if (lesson10.selection) {
// Check the position where the plane is intersected
var intersects = lesson10.raycaster.intersectObject(lesson10.plane);
// Reposition the object based on the intersection point with the plane
lesson10.selection.position.copy(intersects[0].point.sub(lesson10.offset));
} else {
// Update position of the plane if need
var intersects = lesson10.raycaster.intersectObjects(lesson10.objects);
if (intersects.length > 0) {
lesson10.plane.position.copy(intersects[0].object.position);
lesson10.plane.lookAt(lesson10.camera.position);
}
}
}

onDocumentMouseUp

When we release our mouse button, we only need to enable the controls again, and reset the selection:
onDocumentMouseUp: function (event) {
// Enable the controls
lesson10.controls.enabled = true;
lesson10.selection = null;
}
That’s it for today. Hope you find our tutorial useful. If it is then subscribe us.

JFoenix - JavaFX Material Design Library

$
0
0
In nowadays web application is on top with mobile application but you can't ignore the desktop applications value. And after this post you can't stop you to make your first desktop application if you didn't make before.
In Java have Swing for desktop application but it is dull as a end user point of view. So they launch JavaFx in which we can add own custom CSS with that technology for better designing.
But here i am not talking about JavaFx its the better version of JavaFx design named - JFoenix which give the power to use Googles Material design in our desktop application.

Example

Floating Button


Listview

Cool isn't it huh ?

Demo



JFoenix is an open source java library, that implements Google Material Design using java components. To start using JFoenix, all you have to is download it from GitHub.
You can find JFoneix source files along with a compiled jar file on the following link:

  1. JavaFX Material Design Library download jar
  2. JFoenix android build download
  3. JFoenix Site

Build

Ant

To build JFoenix, we created an Ant file named build.xml and build.bat. JFoenix uses Java version 1.8 u60. Using the command line, you need to move to the JFoenix/make directory and run the batch file build.bat by typing:
build.bat
To run the main demo, go to the JFoenix/make directory and run the batch file run-demo.bat :
run-demo.bat
NOTE :

  • You need to update the build.bat to point to Java 1.8 and Apache Ant directories.
  • Linux is also supported. In the make directory, use ./build.sh and ./run-demo.sh, respectively.

Gradle

To build JFoenix, execute the following command:
gradlew build
To run the main demo, execute the following command:
gradlew run
NOTE : 

  • You need to set JAVA_HOME environment variable to point to Java 1.8 directory.
  • JFoenix requires Java 1.8 u60 and above.

How Can You Use JFoenix?


  • You can download the source code of the library and build it as mentioned previously. 
  • Building JFoenix will generate jfoenix.jar under the build/dist folder. 
  • To use JFoenix, import jfoenix.jar into your project and start using the new material design Java components :).

Gradle

How to Include In Project
repositories {
    mavenCentral()
}
Reference the repository from this location using:
dependencies {
  compile 'com.jfoenix:jfoenix:1.0.0'
}
Hope you like this article and want more then subscribe us.

Encode String security using MD5 algorithm in Java

$
0
0
The MD5 Message-Digest Algorithm is a widely used cryptographic hash function that produces a 128-bit (16-byte) hash value. It’s very simple and straight forward; the basic idea is to map data sets of variable length to data sets of a fixed length. In order to do this, the input message is split into chunks of 512-bit blocks.


A padding is added to the end so that it’s length can be divided by 512. Now these blocks are processed by the MD5 algorithm, which operates in a 128-bit state, and the result will be a 128-bit hash value. After applying MD5, generated hash is typically a 32-digit hexadecimal number.

Here, the password to be encoded is often called the “message” and the generated hash value is called the message digest or simply “digest”.
publicclassSimpleMD5Example
{
publicstaticvoidmain(String[] args)
{
String passwordToHash = "password";
String generatedPassword = null;
try {
// Create MessageDigest instance for MD5
MessageDigest md = MessageDigest.getInstance("MD5");
//Add password bytes to digest
md.update(passwordToHash.getBytes());
//Get the hash's bytes
byte[] bytes = md.digest();
//This bytes[] has bytes in decimal format;
//Convert it to hexadecimal format
StringBuilder sb = new StringBuilder();
for(int i=0; i< bytes.length ;i++)
{
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
}
//Get complete hashed password in hex format
generatedPassword = sb.toString();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
System.out.println(generatedPassword);
}
}

Console output:

5f4dcc3b5aa765d61d8327deb882cf99


Although MD5 is a widely spread hashing algorithm, is far from being secure, MD5 generates fairly weak hashes. It’s main advantages are that it is fast, and easy to implement. But it also means that it is susceptible to brute-force and dictionary attacks. Rainbow tables with words and hashes generated allows searching very quickly for a known hash and getting the original word.

Also, It is not collision resistant: this means that different passwords can eventually result in the same hash.

Still, if you are using MD5 hash then consider adding some salt to your security.

Making MD5 more secure using salt

Keep in mind, adding salt is not MD5 specific. You can add it to other algorithms also. So, please focus on how it is applied rather than its relation with MD5.

Wikipedia defines salt as random data that are used as an additional input to a one-way function that hashes a password or pass-phrase. In more simple words, salt is some randomly generated text, which is appended to password before obtaining hash.

The original intent of salting was primarily to defeat pre-computed rainbow table attacks that could otherwise be used to greatly improve the efficiency of cracking the hashed password database. A greater benefit now is to slow down parallel operations that compare the hash of a password guess against many password hashes at once.
Important: 
We always need to use a SecureRandom to create good Salts, and in Java, the SecureRandom class supports the “SHA1PRNG” pseudo random number generator algorithm, and we can take advantage of it.

Let’s see how this salt should be generated.

privatestaticbyte[] getSalt() throws NoSuchAlgorithmException
{
//Always use a SecureRandom generator
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
//Create array for salt
byte[] salt = newbyte[16];
//Get a random salt
sr.nextBytes(salt);
//return salt
return salt;
}
SHA1PRNG algorithm is used as cryptographically strong pseudo-random number generator based on the SHA-1 message digest algorithm. Note that if a seed is not provided, it will generate a seed from a true random number generator (TRNG).

Now, lets look at the modified MD5 hashing example:

publicclassSaltedMD5Example
{
publicstaticvoidmain(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException
{
String passwordToHash = "password";
byte[] salt = getSalt();

String securePassword = getSecurePassword(passwordToHash, salt);
System.out.println(securePassword); //Prints 83ee5baeea20b6c21635e4ea67847f66

String regeneratedPassowrdToVerify = getSecurePassword(passwordToHash, salt);
System.out.println(regeneratedPassowrdToVerify); //Prints 83ee5baeea20b6c21635e4ea67847f66
}

privatestatic String getSecurePassword(String passwordToHash, byte[] salt)
{
String generatedPassword = null;
try {
// Create MessageDigest instance for MD5
MessageDigest md = MessageDigest.getInstance("MD5");
//Add password bytes to digest
md.update(salt);
//Get the hash's bytes
byte[] bytes = md.digest(passwordToHash.getBytes());
//This bytes[] has bytes in decimal format;
//Convert it to hexadecimal format
StringBuilder sb = new StringBuilder();
for(int i=0; i< bytes.length ;i++)
{
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
}
//Get complete hashed password in hex format
generatedPassword = sb.toString();
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return generatedPassword;
}

//Add salt
privatestaticbyte[] getSalt() throws NoSuchAlgorithmException, NoSuchProviderException
{
//Always use a SecureRandom generator
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "SUN");
//Create array for salt
byte[] salt = newbyte[16];
//Get a random salt
sr.nextBytes(salt);
//return salt
return salt;
}
}
Important: 
Please note that now you have to store this salt value for every password you hash. Because when user login back in system, you must use only originally generated salt to again create the hash to match with stored hash. If a different salt is used (we are generating random salt), then generated hash will be different.

Also, you might heard of term crazy hashing and salting. It generally refer to creating custom combinations like:
salt+password+salt => hash
Do not practice these things. They do not help in making hashes further secure anyhow. If you want more security, choose a better algorithm.
Viewing all 322 articles
Browse latest View live