Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Class JavaLaunchHelper is implemented in both

I was getting the below error which compiling my code.

objc[3789]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home/bin/java (0x1095e64c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x1096724e0). One of the two will be used. Which one is undefined.

Solution.

Upgrade JDK to the latest version from http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

Details related are also discussed at https://stackoverflow.com/questions/18794573/class-javalaunchhelper-is-implemented-in-both-libinstrument-dylib-one-of-th

Java 8 framework and Tools support

 

Following post if the draft , i am going to update it on ongoing basis as part of my learnings.

Updated 26 March 2014

Development tools

Eclipse Kelper SR2 supports Java8

 

Application servers

Tomcat

People have been running Java 8 with Tomcat

http://tomcat.apache.org/whichversion.html

JBoss Wildfy

Comes with basic Java 8 support

http://www.wildfly.org/

Frameworks

Spring

Spring Framework 4.0 provides support for several Java 8 features. You can make use of lambda expressions and method references with Spring’s callback interfaces. There is first-class support for java.time (JSR-310), and several existing annotations have been retrofitted as @Repeatable. You can also use Java 8’s parameter name discovery (based on the -parameters compiler flag) as an alternative to compiling your code with debug information enabled.

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/new-in-4.0.html

Links

http://spring.io/blog/2014/03/21/java-8-in-enterprise-projects

Test SSL LDAPS connection

A useful code to check SSL LDAPS connection

http://java.ittoolbox.com/groups/technical-functional/java-l/ldap-test-connection-4747814

Debug SSL connection java


Examples
  • To view all debugging messages:
    java -Djavax.net.debug=all MyApp
  • To view the hexadecimal dumps of each handshake message, you can type the following, where the colons are optional:
    java -Djavax.net.debug=ssl:handshake:data MyApp
  • To view the hexadecimal dumps of each handshake message, and to print trust manager tracing, you can type the following, where the commas are optional:
    java -Djavax.net.debug=SSL,handshake,data,trustmanager MyApp


Compare contents of two jar files

Download jarcomp jar from below URL
 

Use the following command to compare


java -jar jarcomp_01.jar file1.jar file2.jar

Chain Mapper Example

Giving example of how to use Chain map class in hadoop to call code in sequence.
I am writing comments in between to explain
 
public class ChainDriver {
                public static Logger log = Logger.getLogger(ChainDriver.class);
                /**
                * @param args
                * @throws IOException
                * @throws ClassNotFoundException
                * @throws InterruptedException
                */
                public static void main(String[] args) throws IOException,
                                                InterruptedException, ClassNotFoundException {
                                // Start main Chain Job and declare its conf and job
                                Configuration chainConf = new Configuration();
                                Job chainJob = Job.getInstance(chainConf);
                                // Variable names kept like conf1 etc to make code less cluttered
                                // Start Mapper for MyMapperA 
                                Configuration conf1 = new Configuration(false);
                                // Example for Passing arguments to the mappers
                                conf1.set("myParameter", args[2]);
                                ChainMapper.addMapper(chainJob, MyMapperA.class,
                                                                LongWritable.class, Text.class, Text.class, Text.class, conf1);
                                // Start Mapper for Second replacement
                                Configuration conf2 = new Configuration(false);
                                // Dynamically take the class name from argument to make more Dynamic chain :)
                                // (MapperC OR MapperD)
                                ChainMapper.addMapper(chainJob,
                                                                (Class<? extends Mapper>) Class.forName(args[2]), Text.class,
                                                                Text.class, NullWritable.class, Text.class, conf2);
                                // Set the parameters for main Chain Job
                                chainJob.setJarByClass(ChainDriver.class);
                                FileInputFormat.addInputPath(chainJob, new Path(args[0]));
                                FileOutputFormat.setOutputPath(chainJob, new Path(args[1]));
                                System.exit(chainJob.waitForCompletion(true) ? 0 : 1);
                }
}
 
Now in details few important points
1)
Configuration conf1 = new Configuration(false);
The Sub mappers configuration objects are initiated with boolean false
http://hadoop.apache.org/docs/r2.0.3-alpha/api/src-html/org/apache/hadoop/conf/Configuration.html#line.518
Using constructor
public Configuration(boolean loadDefaults)


loadDefaults - specifies whether to load from the default files



2)

Passing arguments
  conf1.set("myParameter", args[2]);

You can use same code as we use in any Driver class

3)

ChainMapper.addMapper(chainJob, MyMapperA.class,
                                                                LongWritable.class, Text.class, Text.class, Text.class, conf1);

The method signature is like this

public static void addMapper(Job job,
Class<? extends Mapper> klass,
Class<?> inputKeyClass,
Class<?> inputValueClass,
Class<?> outputKeyClass,
Class<?> outputValueClass,
Configuration mapperConf)


The Job argument here is Job object of main Driver , chainJob
Then we tell which mapper to start and key value pairs as used by Mapper

Last argument is of Conf of Mapper being called

4)

You can call as many mappers , Reducers in chain but one thing to be kept in mind is that output of previous mapper ( or reducer) must be consumable directly by next in chain.
For example

Map 1
Map 2
are called in chain

If map 1 emits ,
Text as Key
Long as Value

Then

Map 2 should have

Text as Key Input
and Long and Value Input

The framework will not do any conversions for you.

5)
http://hadoop.apache.org/docs/r2.0.3-alpha/api/org/apache/hadoop/mapreduce/lib/chain/ChainMapper.html

The ChainMapper class allows to use multiple Mapper classes within a single Map task.

Quoting from Javadocs

The key functionality of this feature is that the Mappers in the chain do not need to be aware that they are executed in a chain. This enables having reusable specialized Mappers that can be combined to perform composite operations within a single task.
Special care has to be taken when creating chains that the key/values output by a Mapper are valid for the following Mapper in the chain. It is assumed all Mappers and the Reduce in the chain use matching output and input key and value classes as no conversion is done by the chaining code.
Using the ChainMapper and the ChainReducer classes is possible to compose Map/Reduce jobs that look like [MAP+ / REDUCE MAP*]. And immediate benefit of this pattern is a dramatic reduction in disk IO.

I found it pretty good tool while developing multiple processing pipelines. I just develop re usable classes of various tasks and call them in chain.

 

Update April 6

 

I would say based on experience using till now , chain mapper makes processing slow. So use it if and only if unless you really cannot avoid this.

 

Do you have some tips to improve performance of Chain mapper ? Please share below.

Happy Chaining :)

Api diagrams from source

ApiViz ia another magical tool which can be helpful in learning about the code

Lets see how it works

Download GraphViz

http://www.graphviz.org/Download..php

Set the environment variable

GRAPHVIZ_HOME=C:\Program Files\Graphviz 2.28\bin

ApiViz

http://code.google.com/p/apiviz/#Prerequisites

We can use maven to use it quickly

 

Edit maven pom.xml

 

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.9</version>

<configuration>
         <doclet>org.jboss.apiviz.APIviz</doclet>
         <docletArtifact>
           <groupId>org.jboss.apiviz</groupId>
           <artifactId>apiviz</artifactId>
           <version>1.3.2.GA</version>
         </docletArtifact>
         <useStandardDocletOptions>true</useStandardDocletOptions>
         <charset>UTF-8</charset>
         <encoding>UTF-8</encoding>
         <docencoding>UTF-8</docencoding>
         <breakiterator>true</breakiterator>
         <version>true</version>
         <author>true</author>
         <keywords>true</keywords>
         <additionalparam>
           -sourceclasspath ${project.build.outputDirectory}
         </additionalparam>
       </configuration>

 

        </plugin>
    </plugins>
</build>

 

Lets start magic

 

mvn compile javadoc:javadoc

Generate UML diagrams for Java from source

ywroks has very good docklet for generating automated UML diagrams from java source code

Here are steps to use it.

I am using maven based system , although you can use ant also. Read the documentation on yworks website. On linux based system you need x server running for uml generation.

Step 1

Download docklet jars

http://www.yworks.com/en/downloads.html#yDoc

Extract it to some location say

D:\Development\yworks-uml-doclet-3.0_01-jdk1.5

 

Step 2

Tell maven you want to use this docklet

Add following to your pom.xml

Add property for path

Add build details for javadoc

<project>…..

<properties>
        <yworks.uml.path>D:\Development\yworks-uml-doclet-3.0_01-jdk1.5</yworks.uml.path>
</properties>

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <!-- Doclet -->
                    <doclet>ydoc.doclets.YStandard</doclet>
                    <docletPath>${yworks.uml.path}/lib/ydoc.jar:${yworks.uml.path}/lib/ydoc.jar:${yworks.uml.path}/resources:${yworks.uml.path}/lib</docletPath>
                    <additionalparam>-umlautogen</additionalparam>
                    <!-- bootclasspath required by Sun's JVM -->
                    <bootclasspath>${sun.boot.class.path}</bootclasspath>
                    <!-- General Javadoc settings -->
                    <doctitle>${project.name} (${project.version})</doctitle>
                    <show>private</show>

                    <docfilessubdirs>true</docfilessubdirs>
                    <!-- Apple's JVM sometimes requires more memory -->
                    <additionalJOption>-J-Xmx1024m</additionalJOption>
                    <verbose>true</verbose>
                </configuration>
            </plugin>
        </plugins>
    </build>

 

</project>

 

Step 3

Let the magic began

 

mvn:package javadoc:aggregate

or just

mvn javadoc:javadoc

 

Open the javadocs at

/target/site/apidocs/index.html

You can see magical pictures there :)

 

Credit : http://blog.keyboardplaying.org/2012/05/29/javadoc-uml-diagrams-maven/

 

Tip 1: If you want to generate uml for only specific packages use following additional configuration above

<sourcepath>${basedir}/src/main/java/com/MypakagePath</sourcepath>

 


Want to have more fun ?


Read here


http://code.google.com/p/apiviz/#Sample


http://www.umlgraph.org/download.html

Java Tutorials in Kindle , eReader , iPad

Do you know Oracle has started providing all the Java Tutorials which are present on its website in ePub and mobi format?

This has been pretty good surpsise for me.

You can download all of them at

http://www.oracle.com/technetwork/java/javase/downloads/java-se-7-tutorial-2012-02-28-1536013.html

Check for the latest version of above page.

The best way is to go to Tutorials first

http://docs.oracle.com/javase/tutorial/index.html

and then on right side

There is section of eBook Download

Click there

Happy Learning :)

Eclipse SVN configuration for JavaHL

Failed to load JavaHL Library.
These are the errors that were encountered:
no libsvnjavahl-1 in java.library.path
no svnjavahl-1 in java.library.path
no svnjavahl in java.library.path
java.library.path = /usr/lib/jvm/java-6-openjdk/jre/lib/i386/client:/usr/lib/jvm/java-6-openjdk/jre/lib/i386::/usr/java/packages/lib/i386:/usr/lib/jni:/lib:/usr/lib
 
You can download the same from
sudo  apt-get install libsvn-java

Exception handling Mindmap

Jasper Reports integration with Liferay

Liferay has one portlet which supports Jasper Reports , but that is not free. It is available only for EE edition people.

Luckily we have one portlet which is free and is based on Jasper reports

http://code.google.com/p/aperte-reports/

I have used it on Tomcat based liferay installation.

Some of the steps and things you need to do

* You need PostgreSQL database , it doenst not work with MySQL. The Postgre SQL based database if used to store internal details which are required for this portlet to work. So dont worry if your liferay install is MySQL or any other it can be used freely.

* Install Postgre and create one database which can be used by aperte-reports portlet

Configure JDBC datasource in tomcat

* In your tomcat context , (generally inside ROOT.xml ) add the following information

<Resource name="jdbc/aperte-reports" auth="Container"

    type="javax.sql.DataSource" driverClassName="org.postgresql.Driver" url="jdbc:postgresql://localhost:5432/aperteDb" username="postgres" password="root" maxActive="20" maxIdle="10" maxWait="-1"/>

aperteDb is database which i created in Postgre for this portlet

* Download the war file of aperte-reports portlet and deploy it

* Download extra jars from

http://jdbc.postgresql.org/download/postgresql-9.1-901.jdbc4.jar

to tomcat lib/ext folder

* Download Vaadin jar from its website

Also download 3 jars of

Vaadin add-ons:

  1. MaskedTextField v0.1.1
  2. ActiveLink v1.0
  3. CKEditor wrapper for Vaadin v1.0

Restart the tomcat and after your portlet deployment is done , you can go to Aperte Reports manager to import jmxml file of ireports into Liferay to create reports and charts

String split and NumberFormatException

Here is one interesting catch

I was trying to convert a string with spaces into various subparts

So i used split method and then tried to convert the individual values into int

While parsing int values i was getting NumberFormatException

That seems very strange at first instance but yes i got it.

After careful notice i found that

19 String[] input = line.split("\\s+");
20 System.out.println(input[0]);
21 int withdrawl = Integer.parseInt("input[0]");

Line 21 already had " " quotes inserted in array generated by the split method

So just


19 String[] input = line.split("\\s+");
20 System.out.println(input[0]);
21 int withdrawl = Integer.parseInt(input[0]);

without quotes was enough to parse the value

The javadoc for split method explains more

The string "boo:and:foo", for example, yields the following results with these expressions:

Regex Result
: { "boo", "and", "foo" }
o { "b", "", ":and:f" }

read the program input from text file

How to set and read the program input from text file instead of keyboard

Other day i was trying to take part in some online programming tests and generally we have to give our program which is compliant to certain guidelines.

One of them is that input has to be given from keyboard.

For testing locally i suggest that you can make one text file to give input all in one go

Some thing like

System.setIn(new FileInputStream(
"D:\\Development\\eclipse_workspace\\RandomInterview\\src\\1.txt"));

This will set the System.in to the text file specified and you can see the output in console.

Happy Programming

Useful link

http://stackoverflow.com/questions/188547/eclipse-reading-stdin-system-in-from-a-file

Use BufferedReader to read line by line

InputStreamReader in = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(in);

String line ;
while ((line = br.readLine()) != null){
System.out.println(line);
}

Earlier i was doing one mistake

invoking readLine() both for checking null and for printing so as a effect the values were skipped and alternate values were being printed. This is due to fact that readLine was called two times and one value was being skipped

Useful resource

http://www.java2s.com/Code/Java/File-Input-Output/UseBufferedReadertoreadlinebyline.htm

Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )


Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )

This error comes when we give path

D:\Development\eclipse_workspace\

instead of

D:\\Development\\eclipse_workspace\\

We should escape the backslash with \

New line character / OS dependence

The new line character depends on your OS \n for Unix, \r\n for Windows and \r for old Macs

Always use

System.getProperty("line.separator")

To find out OS specific line separator instead of judging yourself and hard coding it.

This error can lead to many bugs in system

Hadoop development environment in eclipse

The sample steps are

Create a Java Project
In Build path add the hadoop jar files , which come by default when you download hadoop binary from apache website.
It is also suggested that you link javadoc and source files for the above jars also

Now create one sample program based on famous WordCount example of hadoop

The example present on the official documentation for version 0.20.203 is based on old API , if you want to see the latest example you can see the link below

http://shuyo.wordpress.com/2011/03/08/hadoop-development-environment-with-eclipse

The example also shows detailed steps to setup eclipse

Sample code which you can use , just create one folder named input within your project workspace folder
Click Run

package com.hadoop;

import java.io.IOException;
import java.util.*;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Job;

import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.Mapper.Context;

import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import org.apache.hadoop.util.GenericOptionsParser;

public class WordCount1 {

public static class SimpleMapper extends Mapper {

private Text word = new Text();
private static final IntWritable one = new IntWritable(1);

public void map(Object key, Text value, Context context)
throws IOException {

StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
try {
context.write(word, one);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}
}

public static class SampleReducer extends Reducer {

private IntWritable result = new IntWritable();

protected void reduce(Text key, Iterator values,
Context context) throws IOException, InterruptedException {
// TODO Auto-generated method stub

int sum = 0;
while (values.hasNext()) {
sum += values.next().get();
}
context.write(key, new IntWritable(sum));

}

}

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

Configuration conf = new Configuration();
GenericOptionsParser g = new GenericOptionsParser(conf, args);
String[] otherArgs = g.getRemainingArgs();
Job job = new Job(conf, "Example Hadoop 0.20.1 WordCount");
job.setJarByClass(WordCount1.class);
job.setMapperClass(SimpleMapper.class);
job.setReducerClass(SampleReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path("input"));
FileOutputFormat.setOutputPath(job, new Path("output"));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}

How to install Java and JDK in Linux (Ubuntu)

We can install Java either using packages or manually. This post explains how to do it manually.

If you want jdk to be available only for particular user , then do it in his home directory. Otherwise if you want to make it available for all the users its better to do it in /usr directory.

Steps

1) Login to shell and go to folder where you want to install jdk . In this example i am doing it in folder in /usr . The shell commands are shown by # statements , it can be $ for you. It doesn’t matter. If the user with which you are logged in is not root. Then you need to prefix commands with sudo.

# cd /usr

# sudo mkdir java

# cd java

Download the latest version of jdk from oracle website. You can also isntall Open jdk . The steps would be more of less same. Just change would be file name and from where to get it.

Go to Oracle website and open the Java downloads page. Click JDK and you will be presented with various files which you can download depending upon your platform. If your machine is 32 bit you would download x86 setup . If its 64 bit then you will download x64 setup.

My machine is 32 bit so i am downloading setup accordingly.

# sudo wget http://download.oracle.com/otn-pub/java/jdk/6u26-b03/jdk-6u26-linux-i586.bin

The above command will downlad the jdk binary to java directory.

Next step is to change the permissions for the file to execute and start the install process

# chmod o+x jdk-6u26-linux-i586.bin

# ./ jdk-6u26-linux-i586.bin

This will complete the install process and will create one folder named jdk1.6.0_26 in the java directory. This is your java home and you are done.

Setting up Java environment and path variables.

To setup the environment variables

# export JAVA_HOME=/usr/java/jdk1.6.0_26

Setting the Java path use the following command

# export PATH = $PATH:$JAVA_HOME/bin

This will setup your JAVA_HOME , we can test our java installation with following command

# java –version

It will show the Java version installed.