Wednesday, 7 November 2012

JAVA interview questions ...

Difference Between get( ) and load( ) 

 

 Get Load
The get( ) methods always hit the database. A call to load( ), on the other hand, does not immediately incur a call to the database.
as soon as the call to get( ) occurs, Hibernate issues an SQL statement to the database in an attempt to fetch the associated data (usually a row in the database) to rebuild the requested persistent object. The load( ) method causes a proxy object to be constructed as a stand-in for the persistent object.  It is only after some state is requested from the proxy that Hibernate issues the appropriate SQL to the database and builds the real persistent object.
When using get( ), the method will return null if no data exists for the requested identifier. The load( ) method does not immediately retrieve the object, if no data exists for the identifier used to retrieve the object, an ObjectNotFoundException is thrown once data is requested of the proxy.



  Difference between forward and sendRedirect

 

NO Forward SendRedirect
1 forward runs on the server side SendRedirect runs on the client as well as on the server side thats why the response generated by sendRedirect() is slow as compared to rd.forward()
2 Incase of forward() the request has to be forwarded to the same web application By using sendRedirect() you can forward the request to any web application either in the same server or to the another one
3 One more difference is that forward() method holds the previous request and response objects sendRedirect(),it will create fresh request and response objects
 

 



JMS

http://publib.boulder.ibm.com/infocenter/wmbhelp/v7r0m0/index.jsp?topic=%2Fcom.ibm.etools.mft.doc%2Fac24862_.htm


There are 6 interfaces, based on he message payload.

1 Message

2 BytesMessage

3 TextMessage

4 StreamMessage

5 MapMessage

6 ObjectMessage



What is a SessionFactory?

The SessionFactory is the concept that is a single data store and thread safe. Because of this feature, many threads can access this concurrently and the sessions are requested, and also the cache that is immutable of compiled mappings for a specific database. A SessionFactory will be built only at the time of its startup. In order to access it in the application code, it should be wrapped in singleton. This wrapping makes the easy accessibility to it in an application code.


What is JMX?

To make it short, JMX is a technology that lets you implement management interfaces for Java applications.
A management interface, as defined by JMX, is composed of named objects - called MBeans (Management Beans). MBeans are registered with a name (an ObjectName) in an MBeanServer. To manage (a) resource(s) in your application, you will write an MBean that defines its management interface, and then register that MBean in your MBeanServer.


 


 

 

 


 


 

Wednesday, 22 August 2012

Being Interviewed ...

This is actually nothing got to do with JDK ... Just my idea on the development of software.

Firstly

I have Joined a new startup company, I mean to say my company(Mindchain Solutions Ltd) had signed up a contract  with another company to work on a new product in the betting arena. I am going to write a few of my rumble (or my  expression of dissatisfaction).

I am a hardcore developer ( Architect, Analyst, Coder(senior)) the only thing which does not come to me is the business of making money. And how idiotic these days the interviews are,

They ask candidates to write tests (online or in house)

Ask some idiotic technical questions like ( what is difference between Interface and Abstract class?) or sometime go a bit further and ask questions from the Java API like

in the ConcurrentHashMap

Can you tell me what the method putifabsent does and the interviewer not being English has a weird pronunciation,

And if with difficulty even if we answer that question call us for face to face and if we give the best solution, reject us because we gave a very good answer, and they don't have any other reason to reject.

For example, I was asked to write a program to see if the input text was a palindrome and if so create a user and add his count as one.

when I gave them the solution as we can use StringBuffer.reverse() and then compare both the original text and reversed text. Which is the best solution which can exist. Reject the candidate.


A person with experience will have worked on technologies, his experience will be an assert to the company.


My Startup experience has to come to a end ... the main reason is Recession :) ...

Thursday, 2 August 2012

php tomcat mac jee

How to install tomcat in mac

# Add the wget alias for curl to the end of the bash_profile file
#----------------------------------------------------------------------------#
echo 'alias wget="curl -O"' >> ~/.bash_profile
 
 
Create a Projects Directory 

mkdir projects
 
cd projects 

mkdir tomcats
 
cd tomcats 
 
 
Download Apache Tomcat
 
wget http://mirror.rmg.io/apache/tomcat/tomcat-7/v7.0.29/bin/apache-tomcat-7.0.29.tar.gz 


Unpack tomcat

tar -xzvf apache-tomcat-7.0.29.tar.gz
 
rm apache-tomcat-7.0.29.tar.gz
 
 
I have renamed the apache-tomcat-7.0.29 to tomcat7029 (7029 as the version of the tomcat)
 
 edit startup.sh
 
Add JAVA_HOME
 
1) Check to see the list of Java VMs in your machine
 
ls /System/Library/Frameworks/JavaVM.framework/Versions/
 
I had 1.6 version

2) check if Home dir is present

ls /System/Library/Frameworks/JavaVM.framework/Versions/1.6
 
open the startup.sh file in the tomcat/bin folder
 
Add this line after the one which starts with EXECUTABLE=
 
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home
 
 
then starting tomcat 
 
tomcats > sh tomcat7029/bin/startup.sh 


Open a Browser

Type in http://localhost:8080 in the address bar

Tomcat Installed !!!


Now installing PHP

there is a PHP java bridge library and only catch is we have to use Tomcat 6 and Java JDK 1.6 as this inly contains a JSR 223 command line script interpreter called jrunscript.


installation details http://php-java-bridge.sourceforge.net/pjb/tomcat6.php

First to install php5 and php-cgi (along with all its dependencies!) with:
sudo apt-get install php5 php-cgi

Wednesday, 27 June 2012

Public JCP Executive Committee Meeting

Public JCP Executive Committee Meeting - June 2012

Hi all finally there was Public JCP meeting Yesterday, 26th June, 2012. I should have blogged this information once I got to know about the meeting(:facepalm). Here after once I am aware of this information, would blog and make sure we in the (Java) community participate more in such meetings.

You can click on this link, for more information.

I had prepared to go to office (very) early, 7 AM i was at my desk so that I could leave home for the meeting.

This is the first ever meeting, I am attending as part of JCP. The meeting was scheduled to be started by 4 PM. There were 2 meeting in the jcp webex one read private, and another public. The private one had been already started. The timing on the page read

Private 7 AM ( GMT + 7)

Public 8 AM (GMT + 7), I guess it should hve been GMT + 8 ;).


I tried to log in the phone line, I was not able to join the audio (its a shame). Therefore I had joined the web interface and was following the slides.

Bruno Souza  had posted on the chat that he will be in the chat, and we could even ask questions in the chat window.

I was able to see 2 other familiar faces Martijn and Jim from my very own LJC.

Maybe next time I will try to log on the audio, and update you guys more on the discussions.

Monday, 21 May 2012

Sample Spring TTD BDD

Mvn

Command for starting a project

mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.geethsangam.music -DartifactId=Geethsangam

cd to the created directory

 mvn compile
 mvn test
 mvn package
 mvn install
 mvn eclipse:clean eclipse:eclipse


To create a sub project

Change the packaging type from jar to pom

  <groupId>com.geethsangam.music</groupId>
  <artifactId>Geethsangam</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>


  <groupId>com.geethsangam.music</groupId>
  <artifactId>Geethsangam</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>pom</packaging>

Now Mvn for sub modules
(after that do the mvn compile test package install & mvn eclipse:clean eclipse:eclipse)

Domain Layer

mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.geethsangam.music -DartifactId=geethsangam-domain

DAO Layer

mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.geethsangam.music -DartifactId=geethsangam-dao

Service

mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.geethsangam.music -DartifactId=geethsangam-service

Controller

mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.geethsangam.music -DartifactId=geethsangam-presentation

WAR Layer

mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.geethsangam.music -DartifactId=geethsangam-war


For Cucumber (BDD testing)

Mkdir cucumber

cd cucumber

 (in Cento OS linux use yum command to install)

1) yum install libxml2-devel libxslt-devel git
2) yum --enablerepo=install jruby
3) jruby -S gem install bundler



 (in MacOs use yum command to install) if using port else install mac port

1)  $ sudo port install cmake   $ sudo port install gsl-devel   $ sudo port install libxml2   $ sudo port install qt3 qt3-shlibs qt3mac qt3mac-shlibs
2) Check if Jruby is installed else install it
3) jruby -S gem install bundler

Windows

If you are on a Windows machine (why are you on a Windows machine?), you need to install Cygwin (from its website) with the following packages: subversion, gcc, g++, make, gsl, gsl-devel, cmake, libxml2, libxml2-devel. Although they are not needed for most of the things, you can also install qt3, qt3-devel, bc (the latter is used by some scripts) (http://openrdk.sourceforge.net/index.php?n=Docs.Installation)


== Installing

cd Geethsangam/cucumber
jruby -S bundle install --path=vendor/bundle --binstubs



domain class User.java


package com.geethsangam.music.model;
import java.io.Serializable;
import org.codehaus.jackson.map.JsonMappingException.Reference;

public class User extends Reference implements Serializable {
    private static final long serialVersionUID = 1L;
//    @Id
//    @GeneratedValue
//    @Column(name = "id")
    private long id;
//    @NotEmpty
//    @Size(min = 1, max = 20)
    private String name;
    private String username;
   
    public long getId() {
        return id;
    }
   
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
}


In domain pom.xml add

        <dependency>
        <groupId>javax.persistence</groupId>
        <artifactId>persistence-api</artifactId>
        <version>1.0</version>
    </dependency>
    <dependency>
     <groupId>org.codehaus.jackson</groupId>
     <artifactId>jackson-mapper-asl</artifactId>
     <version>1.4.1</version>
    </dependency>  




package  com.geethsangam.music;

public class UsersDaoTest {

    private UsersDao mockUsersDao;
    private User userMock;
    private List < User > userListMock;

    @Before
    public void prepareMocks() {
       
        mockUsersDao = mock(UsersDao.class);
        userMock = mock(User.class);
        userMock.setId(1L);
        userMock.setName("test");
       
        userListMock = new ArrayList < User >(1);
        userListMock.add(userMock);
    }

    @Test
    public void insertTest() {
        when(mockUsersDao.insert(userMock)).thenReturn(userMock);
        assertEquals(userMock, mockUsersDao.insert(userMock));
    }
}




Service layer test

    private UsersServiceImpl usersService;
    private UsersDao usersDaoMock;
    private User userMock;
    private List < User > userListMock;

    @Before
    public void prepareMocks() {
              
        // set up the DAO mock object
        usersDaoMock = mock(UsersDao.class);

        // Prepare the class to be tested.
        usersService = new UsersServiceImpl();
        usersService.usersDao = usersDaoMock;

        // Set up the mock user
        userMock = mock(User.class);
        userMock.setId(1L);
        userMock.setName("test");
        userMock.setUsername("uSerName");
        when(userMock.getUsername()).thenReturn("uSerName");

        userListMock = new ArrayList < User >(1);
        userListMock.add(userMock);
    }

    @Test
    public void insertTest() {
        when(usersDaoMock.insert(userMock)).thenReturn(userMock);       
        assertEquals(userMock, usersService.insert(userMock));
    }


Service

@Service
public class UsersServiceImpl implements UsersService {

    /**
     * UsersDao.
     */
    @Autowired
     UserDao userDao;
   
    /**
     * Insert User.
     * @param user The user Object.
     * @return Users.
     */
    @Override
    public User insert(User newUser) {

        String newUserName = newUser.getUsername();
        User preExistingUser = fetch(newUserName);
        if (preExistingUser == null) {
            //No users found with this username, so add.
            return usersDao.insert(newUser);
        } else {
            return null;
        }
    }



package com.geethsangam.music.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sf.json.util.CycleDetectionStrategy;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.view.json.JsonWriterConfiguratorTemplateRegistry;



/**
 *
 * @author sadhap01
 *
 */
@Controller
public abstract class BaseController {

    /**
     * hex HexUtils.
     */
    protected static HexUtils hex = new HexUtils();

    /**
     * logger Log.
     */
    protected final Log logger = LogFactory.getLog(getClass());
    /**
     * validate Validate.
     */
    protected static Validate validate = new Validate();

    /**
     * keyGen KeyGenerator.
     */
    static KeyGenerator keygen = new KeyGenerator();

    @Autowired
    private UrlKeysService urlKeysService;

    /**
     * Creates JSon Configuration.
     * @param request HttpServletRequest.
     */
    protected void setJSONPreProcessors(HttpServletRequest request) {
        JsonWriterConfiguratorTemplateRegistry registry =
                        JsonWriterConfiguratorTemplateRegistry.load(request);
        PropertyExclusionSojoJsonWriterConfiguratorTemplate template =
                    new PropertyExclusionSojoJsonWriterConfiguratorTemplate();

        //TODO Get the processor to map all Longs and Dates to
        // the relevant config

        template.getJsonConfig().registerJsonValueProcessor("artist_gid",
                                          new StringNullJsonValueProcessor());
        template.getJsonConfig().registerJsonValueProcessor("brand_pid",
                new StringNullJsonValueProcessor());
       template.getJsonConfig().registerJsonValueProcessor("featured_position",
                new StringNullJsonValueProcessor());
        template.getJsonConfig().registerJsonValueProcessor("created_at",
                                          new DateJsonValueProcessor());
        template.getJsonConfig().registerJsonValueProcessor("updated_at",
                                          new DateJsonValueProcessor());
        template.getJsonConfig().registerJsonValueProcessor("promoted_at",
                                          new DateJsonValueProcessor());
        template.getJsonConfig().registerJsonValueProcessor("status",
                                          new IntJsonValueProcessor());

        template.getJsonConfig().setCycleDetectionStrategy(
                                            CycleDetectionStrategy.LENIENT);

        registry.registerConfiguratorTemplate(template);

    }


    @InitBinder
    public void initBinder(HttpServletRequest request, WebDataBinder binder)
                                                            throws Exception {
        setJSONPreProcessors(request);
    }

    public void validationErrors(HttpServletResponse res, JSONObject errs)
                                                           throws IOException {

        PrintWriter out;
        out = new PrintWriter(res.getOutputStream());

        out.println(errs.toString());

        res.setStatus(res.SC_BAD_REQUEST);
        out.close();

    }
protected String generateUrlKey() throws Exception {
    return keygen.getUrlKey(urlKeysService.generate());
}
}



@Controller
public class UsersController extends BaseController {
    /**
     * UsersService Service Object To Call DAO Layer.
     */
    @Autowired
    private UsersService usersService;

    /**
     * Create User.
     * @param modelMap ModelMap.
     * @param body Json String.
     * @param request Request.
     * @param response Response.
     * @return User JSON.
     * @throws JSONException JSONException.
     * @throws Exception Exception.
     */
    @RequestMapping(value = { "/users", "/users/" } ,
                                                   method = RequestMethod.POST)
    public String createUser(ModelMap modelMap, @RequestBody String body,
                      HttpServletRequest request, HttpServletResponse response)
                                              throws JSONException, Exception {
        JSONObject json;
        User user = new User();
        setJSONPreProcessors(request);
        try {
            json = JSONObject.fromObject(body);
            user.setPropertiesFromJSON(json);
            user = usersService.insert(user);
        } catch (JSONException je) {
            response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
        }
        response.setStatus(HttpServletResponse.SC_OK);
        modelMap.put("user", user);
        return "jsonView";
    }



public class UsersControllerTest {

    private UsersController classToTest;

    private String body;

    private String userName;

    HttpServletRequest request;

    HttpServletResponse response;

    @Mock
    ModelMap modelMap;

    @Before
    public void prepareMocks() {

        body = new String("test");

        userName = new String("testuser");

        request = mock(HttpServletRequest.class);

        response = mock(HttpServletResponse.class);

        classToTest = mock(UsersController.class);


    }

    @Test
    public void createUserTest() throws JSONException, Exception {

        when(classToTest.createUser(modelMap, body, request, response)).thenReturn("jsonView");

        assertEquals("jsonView", classToTest.createUser(modelMap, body, request, response));
    }



cuc/support/api_steps.rb

require 'jsonpath'

# TODO: is there a cleaner way of doing this?
class Capybara::Driver::Mechanize < Capybara::Driver::RackTest
  def post_body(url, body, headers = {})
    if remote?(url)
      process_remote_request(:post, url, body, headers)
    else
      register_local_request
      super
    end
  end
 
  def put_body(url, body, headers = {})
    if remote?(url)
      process_remote_request(:put, url, body, headers)
    else
      register_local_request
      super
    end
  end
end

def expand_path(path)
  if path =~ /(:\w+)/
    field = $1
    collection_path = path[0,path.index(field)]
    response = RestClient.get "#{Capybara.app_host}#{collection_path}", :content_type => :json, :accept => :json
    objects = JSON.parse(response.body).values.detect { |o| o.kind_of? Array }
    url_key = objects.last[field.sub(':','')]
    path.sub(field, url_key)
  elsif path =~ /(@\w+)/
    path.gsub(/@\w+/) { |i| instance_variable_get(i) }
  else
    path
  end
end

Given /^I send and accept XML$/ do
  page.driver.header 'Accept', 'text/xml'
  page.driver.header 'Content-Type', 'text/xml'
end

Given /^I send and accept JSON$/ do
  page.driver.header 'Accept', 'application/json'
  page.driver.header 'Content-Type', 'application/json'
end

When /^I authenticate as the user "([^\"]*)" with the password "([^\"]*)"$/ do |user, pass|
  page.driver.authorize(user, pass)
end

When /^I send a GET request (?:for|to) "([^\"]*)"$/ do |path|
  page.driver.get expand_path(path)
end

When /^I send a POST request to "([^\"]*)"$/ do |path|
  page.driver.post expand_path(path)
end

When /^I send a POST request to "([^\"]*)" with the following:$/ do |path, body|
  url = expand_path(path)
  puts url if ENV['DEBUG']
  page.driver.post_body url, body
end

When /^I send a PUT request to "([^\"]*)" with the following:$/ do |path, body|
  page.driver.put_body expand_path(path), body
end

When /^I send a DELETE request to "([^\"]*)"$/ do |path|
  page.driver.delete expand_path(path)
end

Then /^show me the response$/ do
  puts page.driver.response.body
end

Then /^the response status should be "([^\"]*)"$/ do |status|
  if page.respond_to? :should
    page.driver.response.status.should == status.to_i
  else
    assert_equal status.to_i, page.driver.response.status
  end
end

Then /^the response should be empty$/ do
  page.driver.response.body.should be_empty
end

Then /^the JSON response should have "([^\"]*)" with the text "([^\"]*)"$/ do |json_path, text|
  json    = JSON.parse(page.driver.response.body)
  results = JsonPath.new(json_path).on(json).to_a.map(&:to_s)
  if page.respond_to? :should
    results.should include(text)
  else
    assert results.include?(text)
  end
end

Then /^the JSON response should have "([^"]*)" as nil$/ do |json_path|
  json    = JSON.parse(page.driver.response.body)
  results = JsonPath.new(json_path).on(json).to_a
  results.should == [nil]
end

Then /^the JSON response should not have "([^\"]*)" with the text "([^\"]*)"$/ do |json_path, text|
  json    = JSON.parse(page.driver.response.body)
  results = JsonPath.new(json_path).on(json).to_a.map(&:to_s)
  if page.respond_to? :should
    results.should_not include(text)
  else
    assert !results.include?(text)
  end
end

Then /^the JSON response should have the following:/ do |table|
  json    = JSON.parse(page.driver.response.body)
  table.rows.each do |json_path, text|
    results = JsonPath.new(json_path).on(json).to_a.map(&:to_s)
    if page.respond_to? :should
      results.should include(text)
    else
      assert results.include?(text)
    end
  end
end

Then /^the JSON response should not have the following:/ do |table|
  json    = JSON.parse(page.driver.response.body)
  table.rows.each do |json_path, text|
    results = JsonPath.new(json_path).on(json).to_a.map(&:to_s)
    if page.respond_to? :should
      results.should_not include(text)
    else
      assert !results.include?(text)
    end
  end
end

Then /^the JSON response should have (\d+) "([^"]*)"$/ do |count, json_path|
  json    = JSON.parse(page.driver.response.body)
  results = JsonPath.new(json_path).on(json)
  results.first.size.should == count.to_i
end

Then /^the XML response should have "([^\"]*)" with the text "([^\"]*)"$/ do |xpath, text|
  parsed_response = Nokogiri::XML(response.body)
  elements = parsed_response.xpath(xpath)
  if page.respond_to? :should
    elements.should_not be_empty, "could not find #{xpath} in:\n#{response.body}"
    elements.find { |e| e.text == text }.should_not be_nil, "found elements but could not find #{text} in:\n#{elements.inspect}"
  else
    assert !elements.empty?, "could not find #{xpath} in:\n#{response.body}"
    assert elements.find { |e| e.text == text }, "found elements but could not find #{text} in:\n#{elements.inspect}"
  end   
end


users.feature




Feature: Users
  As an API client
  In order to do things with users
  I want to test CRUD for users
 
  Background:
    Given I send and accept JSON
 
  Scenario: List users when there are no users
    When I send a GET request for "/users"
    Then the response status should be "200"
    And the JSON response should have 0 "$.users.*"
 
  Scenario: Create a user
    When I send a POST request to "/users" with the following:
      """
      {
          "user": {
              "artist_gid": null,
              "id": 5885690,
              "is_guide": 1,
              "is_superuser": 0,
              "medium_synopsis": "Sequi quibusdam recusandae enim alias iste quisquam quia. In nam facilis minima iusto. Est soluta odio voluptas. Voluptas impedit aut quos molestiae provident officiis quia similique.Ab ipsum doloribus qui nesciunt illum minima quia magni. Sint qui dicta iste a non. Natus in ea ex. Aspernatur reiciendis molestiae iure cumque repudiandae aut itaque earum.Quo quo ut et eaque. Itaque aliquam fugit qui. Omnis dicta inventore odio distinctio odit autem.",
              "name": "Marquis Kertzmann",
              "short_synopsis": "Voluptatibus minus quia vel.",
              "status": 1,
              "username": "marquiskertzmann"
          }
      }
      """
    Then the response status should be "200"
    And show me the response
    And the JSON response should have the following:
      | jsonpath              | value                        |
      | $.user.username       | marquiskertzmann             |
      | $.user.name           | Marquis Kertzmann            |
      | $.user.short_synopsis | Voluptatibus minus quia vel. |
      | $.user.is_guide       | 1                            |
      | $.user.is_superuser   | 0                            |
    And the JSON response should have "$.user.artist_gid" as nil
    And the JSON response should have "$.user.featured_position" as nil
    And the JSON response should have "$.user.brand_pid" as nil
 
  Scenario: Create the same user twice
    Given a user exists
    When I send a POST request to "/users" with the following:
      """
      {
          "user": {
              "id": 5885690,
              "name": "Test User",
              "username": "testuser"
          }
      }
      """
      # Then the response status should be "403" - is this the correct status code?
      When I send a GET request for "/users"
      Then the response status should be "200"
      And the JSON response should have 1 "$.users.*"

Wednesday, 7 March 2012

JDK8 Warnings Cleanup Day on Dec 1st, 2011

JDK8 Warnings Cleanup Day on Dec 1st, 2011

In the previous blog I had posted the details about how to configure your virtual box for building Open JDK.

London Java Community had planned to participate on the global JDK8 Warnings Cleanup Day on Dec 1st, 2011. Michael Barker of the LJC had planned a session at Skills matter eXchange, 10 of the members had signed up for the event.

Michael had earlier advised the instructions, i tried to set the machine before I had gone for the event, :( unfortunately I was not able to setup my machine. Luckily, the next day Michael and Martijn  were able to provide us with full setup VM.

    I had paired with one another person Mani (he came without a laptop). We all were at skills matter by 6 30 PM, the machine set up took the most of the time.

    At about 7 30, we had the system up with the setting and had finished the build. We were advised by Michael that we will be dealing with java.util.* warnings, and once we start working on a fix to update the name of the class on the board.

   We had chosen to work on the fix for java.util.zip.ZipEntry.java, but the change was similar to the one in Apache Harmony implementation.

diff -r 43a630f11af6 src/share/classes/java/util/zip/ZipEntry.java
--- a/src/share/classes/java/util/zip/ZipEntry.java Wed Nov 30 13:11:16 2011 -0800
+++ b/src/share/classes/java/util/zip/ZipEntry.java Fri Dec 02 19:12:54 2011 +0000
@@ -24,7 +24,7 @@
  */
 
 package java.util.zip;
-
+import java.util.Calendar;
 import java.util.Date;
 
 /**
@@ -281,27 +281,33 @@
      * Converts DOS time to Java time (number of milliseconds since epoch).
      */
     private static long dosToJavaTime(long dtime) {
-        Date d = new Date((int)(((dtime >> 25) & 0x7f) + 80),
-                          (int)(((dtime >> 21) & 0x0f) - 1),
-                          (int)((dtime >> 16) & 0x1f),
-                          (int)((dtime >> 11) & 0x1f),
-                          (int)((dtime >> 5) & 0x3f),
-                          (int)((dtime << 1) & 0x3e));
-        return d.getTime();
+     Calendar cal = Calendar.getInstance();
+     cal.set(Calendar.YEAR, (int) ((dtime >> 25) & 0x7f) + 1980);
+     cal.set(Calendar.MONTH, (int) ((dtime >> 21) & 0x0f) - 1);
+     cal.set(Calendar.DATE, (int) (dtime >> 16) & 0x1f);
+     cal.set(Calendar.HOUR_OF_DAY, (int) (dtime >> 11) & 0x1f);
+     cal.set(Calendar.MINUTE, (int) (dtime >> 5) & 0x3f);
+     cal.set(Calendar.SECOND, (int) (dtime << 1) & 0x3e);
+     return cal.getTimeInMillis();
     }
 
     /*
      * Converts Java time to DOS time.
      */
     private static long javaToDosTime(long time) {
-        Date d = new Date(time);
-        int year = d.getYear() + 1900;
+        Calendar cal = Calendar.getInstance();
+        cal.setTimeInMillis(time);
+        int year = cal.get(Calendar.YEAR);
         if (year < 1980) {
             return (1 << 21) | (1 << 16);
         }
-        return (year - 1980) << 25 | (d.getMonth() + 1) << 21 |
-               d.getDate() << 16 | d.getHours() << 11 | d.getMinutes() << 5 |
-               d.getSeconds() >> 1;
+        int month = cal.get(Calendar.MONTH) + 1;
+        return (year - 1980) << 25
+                | month << 21
+                | cal.get(Calendar.DAY_OF_MONTH) << 16
+                | cal.get(Calendar.HOUR_OF_DAY) << 11
+                | cal.get(Calendar.MINUTE) << 5
+                | cal.get(Calendar.SECOND) >> 1;
     }
 
     /**
 
The Fix we provided started the question of performance and what sort of things we can fix in warnings clean up, a very good lesson learn t.
 
This was my first build in OpenJDK (facepalm)...
 
There were lots of things I had learned, 

You can run the following program to get the real performance 

public class JavaDosTime {

     public static void main(String[] args) throws IOException {

         long tt0 = System.currentTimeMillis();
         int ii = 0;
         for (ii = 0; ii < 1000000; ii++) {
             long t = 10000 + ii;
             t= javaToDosTime(t);
         }
         long tt1 = System.currentTimeMillis();
         System.out.println("j2dt  :" + (tt1 - tt0));


         tt0 = System.currentTimeMillis();
         ii = 0;
         for (ii = 0; ii < 1000000; ii++) {
             long t = 10000 + ii;
             t= javaToDosTime2(t);
         }
         tt1 = System.currentTimeMillis();
         System.out.println("j2dt2 :" + (tt1 - tt0));


         tt0 = System.currentTimeMillis();
         ii = 0;
         for (ii = 0; ii < 1000000; ii++) {
             long t = 10000 + ii;
             t= dosToJavaTime(t);
         }
         tt1 = System.currentTimeMillis();
         System.out.println("d2jt  :" + (tt1 - tt0));


         tt0 = System.currentTimeMillis();
         ii = 0;
         for (ii = 0; ii < 1000000; ii++) {
             long t = 10000 + ii;
             t= dosToJavaTime2(t);
         }
         tt1 = System.currentTimeMillis();
         System.out.println("d2jt2 :" + (tt1 - tt0));

     }

     private static long javaToDosTime(long time){
         Date d = new Date(time);
         int year = d.getYear() + 1900;
         if (year < 1980) {
             return (1 << 21) | (1 << 16);
         }
         return (year - 1980) << 25 | (d.getMonth() + 1) << 21 |
                d.getDate() << 16 | d.getHours() << 11 | d.getMinutes() 
<< 5 |
                d.getSeconds() >> 1;
     }

     private static long javaToDosTime2(long time){
         Calendar cal = Calendar.getInstance();
         cal.setTimeInMillis(time);
         int year = cal.get(Calendar.YEAR);
         if (year < 1980) {
             return (1 << 21) | (1 << 16);
         }
         int month = cal.get(Calendar.MONTH) + 1;
         return (year - 1980) << 25
                 | month << 21
                 | cal.get(Calendar.DAY_OF_MONTH) << 16
                 | cal.get(Calendar.HOUR_OF_DAY) << 11
                 | cal.get(Calendar.MINUTE) << 5
                 | cal.get(Calendar.SECOND) >> 1;
      }

      private static long dosToJavaTime(long dtime) {
         Date d = new Date((int)(((dtime >> 25) & 0x7f) + 80),
                           (int)(((dtime >> 21) & 0x0f) - 1),
                           (int)((dtime >> 16) & 0x1f),
                           (int)((dtime >> 11) & 0x1f),
                           (int)((dtime >> 5) & 0x3f),
                           (int)((dtime << 1) & 0x3e));
         return d.getTime();
      }

      private static long dosToJavaTime2(long dtime) {
      Calendar cal = Calendar.getInstance();
      cal.set(Calendar.YEAR, (int) ((dtime >> 25) & 0x7f) + 1980);
      cal.set(Calendar.MONTH, (int) ((dtime >> 21) & 0x0f) - 1);
      cal.set(Calendar.DATE, (int) (dtime >> 16) & 0x1f);
      cal.set(Calendar.HOUR_OF_DAY, (int) (dtime >> 11) & 0x1f);
      cal.set(Calendar.MINUTE, (int) (dtime >> 5) & 0x3f);
      cal.set(Calendar.SECOND, (int) (dtime << 1) & 0x3e);
          return cal.getTimeInMillis();
      }

} 
 
The Results were
 
t$ java -server JavaDosTime
j2dt  :386
j2dt2 :1282
d2jt  :424
d2jt2 :1296
 
$ java -client JavaDosTime
j2dt  :621
j2dt2 :1901
d2jt  :662
d2jt2 :2016 


This made me learn so many things on building OpenJDK and fixing some warning (which eventually made me fix more issues the next time).

Drawbacks

We had very little time for fixing just about 45 minutes we were able to look at the code for fixing.

Positives

We had learn t so many things out of this 1 hour of working time.





Oracle had posted me a t-shirt, I was expecting Oracle T-Shirt, but I was so happy the -Shirt HAD JAVA... Hurrah !!! A T-Shirt with JAVA and that also from JAVA. I was so proud. 
 
 I have to thank LJC, and skills matter for arranging such a day.

Friday, 17 February 2012

This is my First Blog On Java JDK.



JDK 8 Warnings Cleanup Day :: My First JDK 8 Warnings Fix

        MY First warnings fix for JDK 8 was on Dec 01 2011. I was very eager to look at contributing back to Java. I have to thank London Java Community (http://www.meetup.co/Londonjavacommunity/) for sponsoring the event at Skill Matters, 116-120 Goswell Road
London, EC1V 7DP.

       The event was hosted by Michael Barker, he on the day before the event on Nov 30th had posted the instructions (which i was not able to fully cover up)

Let me the drop the instructions here so that let the information get to more people.

1. Download Virtual Box.

First download Virtual Box (https://www.virtualbox.org/wiki/Downloads).


2. Download Ubuntu

Next download Ubuntu 10.04 LTS(http://www.ubuntu.com/download/server/download).  Don't download the latest version, you can download Ubuntu 10.04 Long Term Support.



3. Install Virtual Box

Install the virtual box, at this point of time don't worry about Ubuntu.

You can see the installation details on this page.
https://help.ubuntu.com/community/VirtualBox/FirstVM

4. Create a New Virtual Machine 

5. Start the Virtual Machine

You can get more information on the link below

https://help.ubuntu.com/community/VirtualBox/FirstVM

You will get the details for installing Ubuntu, which we had downloaded earlier in the virtual machine.

6. Install Mecurial

Log in virtual machine,

Open a terminal window and type in

$sudo add-apt-repository ppa:mercurial-ppa/releases
$sudo apt-get update
$sudo apt-get install mercurial


$hg  --version 

, to make sure mercurial is installed

7.  Clone jdk 8


$hg clone http://hg.openjdk.java.net/jdk8/tl/jdk




8. After this you can follow

 the http://java.net/projects/jugs/pages/CleanUpjavacwarnings



We have setup the machine to build JDK ... Hurrah ...