Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Web Service REST Calls


REST Web Services APIs

There are several ways to make Yahoo! Web Services REST requests using Java.
HTTP GET Requests
An HTTP GET request is all you need to retrieve basic search results from the Yahoo! Search Web Service. GET requests are easy to debug because you can paste it in your web browser and quickly see if the query has been constructed properly. Some web services require requests via POST for tasks such as image uploading or the modification of HTTP headers to set cookies. We will cover both GET and POST requests in the following examples.
The first example is a request for the keyword “umbrella” that returns 10 results:
String request = "http://api.search.yahoo.com/WebSearchService/V1/webSearch?
appid=YahooDemo&query=umbrella&results=10";
We make a simple HTTP GET request to retrieve the results:
HttpClient client = new HttpClient();
GetMethod method = new GetMethod(request);
// Send GET request
int statusCode = client.executeMethod(method);
Next, we process the response from Yahoo! Web Services and print the XML response to the console:
InputStream rstream = null;
rstream = method.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
String line;
while ((line = br.readLine()) != null) 
System.out.println(line);
}
br.close();
A complete code example is shown below in the  YahooWebServiceGet.java
import java.io.*;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;

public class YahooWebServiceGet {

public static void main(String[] args) throws Exception {
String request = "http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=YahooDemo&
query=umbrella&results=10";

HttpClient client = new HttpClient();
GetMethod method = new GetMethod(request);

// Send GET request
int statusCode = client.executeMethod(method);

if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
InputStream rstream = null;

// Get the response body
rstream = method.getResponseBodyAsStream();

// Process the response from Yahoo! Web Services
BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}

}
HTTP POST Requests
POST requests are used by web browsers when submitting data from HTML forms. The content type “multipart/form-data” should be used for submitting forms that contain files, non-ASCII data, and binary data.
For POST requests, we construct the POST data separately from the request URL and parameters.
String request = "http://api.search.yahoo.com/WebSearchService/V1/webSearch";
HttpClient client = new HttpClient();

PostMethod method = new PostMethod(request);

// Add POST parameters

method.addParameter("appid","YahooDemo");

method.addParameter("query","umbrella");

method.addParameter("results","10");

// Send POST request

int statusCode = client.executeMethod(method);

InputStream rstream = null;

// Get the response body

rstream = method.getResponseBodyAsStream();
The response is the same as the first example and can be processed in the same way.
A complete code example is shown in  YahooWebServicePost.java
import java.io.*;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;

public class YahooWebServicePost {

public static void main(String[] args) throws Exception {
String request = "http://api.search.yahoo.com/WebSearchService/V1/webSearch";

HttpClient client = new HttpClient();
PostMethod method = new PostMethod(request);

method.addParameter("appid","YahooDemo");
method.addParameter("query","umbrella");
method.addParameter("results","10");

// Send POST request
int statusCode = client.executeMethod(method);

if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
InputStream rstream = null;

// Get the response body
rstream = method.getResponseBodyAsStream();

// Process the response from Yahoo! Web Services
BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}
POST Requests with Sockets
Here’s a POST example where we use sockets instead of the URL and URLConnection objects.
// Create POST data string

String postdata = "appid" + "=" + URLEncoder.encode("YahooDemo", "UTF-8");

postdata += "&" + "query" + "=" + URLEncoder.encode("umbrella", "UTF-8");

postdata += "&" + "results" + "=" + URLEncoder.encode("10", "UTF-8");
// Create a socket to the host

String hostname = "api.search.yahoo.com";

int port = 80;

InetAddress addr = InetAddress.getByName(hostname);

Socket socket = new Socket(addr, port);
// Send header

String path = "/WebSearchService/V1/webSearch";

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));

bw.write("POST " + path + " HTTP/1.0\r\n");

bw.write("Content-Length: " + postdata.length() + "\r\n");

bw.write("Content-Type: application/x-www-form-urlencoded\r\n");

bw.write("\r\n");
// Send POST data string

bw.write(postdata);

bw.flush();
A complete code example is shown in  YahooWebServicePostSocket.java
import java.net.*;
import java.io.*;

public class YahooWebServicePostSocket {

public static void main(String[] args) {
try {

// Create POST data string
String postdata = "appid" + "=" + URLEncoder.encode("YahooDemo", "UTF-8");
postdata += "&" + "query" + "=" + URLEncoder.encode("umbrella", "UTF-8");
postdata += "&" + "results" + "=" + URLEncoder.encode("10", "UTF-8");

// Create a socket to the host
String hostname = "api.search.yahoo.com";
int port = 80;
InetAddress addr = InetAddress.getByName(hostname);
Socket socket = new Socket(addr, port);

// Send header
String path = "/WebSearchService/V1/webSearch";
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
bw.write("POST " + path + " HTTP/1.0\r\n");
bw.write("Content-Length: " + postdata.length() + "\r\n");
bw.write("Content-Type: application/x-www-form-urlencoded\r\n");
bw.write("\r\n");

// Send POST data string
bw.write(postdata);
bw.flush();

// Process the response from Yahoo! Web Services
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
bw.close();
br.close();
} catch (Exception e) {
System.out.println("Web services request failed");
System.err.println(e.getMessage());
e.printStackTrace(System.err);
}

}

}

Java Thread Dump Analyser


understand thread dumps by looking at a thread dump

Java Thread Dump Analyser is a tool for quickly summarizing lengthy Java thread dumps.
This tool groups threads together which have the same stack trace and allows you to only show threads which are in particular states (e.g. RUNNABLE or BLOCKED).
This makes it a bit quicker to find the interesting threads amongst the tens or hundreds of JBoss threads which spend most of their time waiting for work at the same place in the code and therefore all have the same stack trace
A Java thread dump is a way of finding out what every thread in the JVM is doing at a particular point in time. This is especially useful if your Java application sometimes seems to hang when running under load, as an analysis of the dump will show where the threads are stuck.
You can generate a thread dump under Unix/Linux by running kill -QUIT <pid>, and under Windows by hitting Ctl + Break.
To make it easier to understand the contents of a Java thread dump you can use the Java Thread Dump Analyser. All you have to do is copy/paste your thread dump text into the input tab and press the Analyse button.

Threadanalyser

Here is an example of the output which is generated.
2011-08-19 17:46:25
Full thread dump Java HotSpot(TM) Client VM (20.0-b11 mixed mode, sharing):
As the name suggests thread dump is a dump of all the threads in a Java virtual machine. It contains the current execution state of both application and the JVM specific threads. The above thread dump snippet shows two application threads [Thread-0 and Thread-1] and JVM specific threads such as “Signal Dispatcher”, “Finalizer” etc. For the purpose of this article we will focus only on application threads.
Thread dumps are extremely useful in the following situations
  • To get a holistic view of what is happening in the application at that particular moment
  • To expose glaring issues such as
  • portions of code which seem to be invoked almost always
  • portions of code where the application seems to be hung
  • locking and thread synchronization issues in an application
  • Additionally they are invaluable in production environments where sophisticated profiling tools cannot be easily attached
Format of thread dumps
The format of thread dump has been changing with JSE versions. Sun or any other vendors inform users that the format will change between versions. However one thing which hasn’t changed is the level of information contained in a thread dump. As mentioned above thread dumps is a snapshot of the JVM state listing all the application and system level threads and monitor states.
Full thread dump Java HotSpot(TM) Client VM (1.5.0_04-b05 mixed mode, sharing):
"Thread-1" prio=5 tid=0x00a995d0 nid=0x1300 in Object.wait() [0x02d0f000..0x02d0fb68]
at java.lang.Object.wait(Native Method)
- waiting on <0x22aaa8d0> (a org.tw.testyard.thread.Drop)
at java.lang.Object.wait(Unknown Source)
at org.tw.testyard.thread.Drop.take(Drop.java:14)
- locked <0x22aaa8d0> (a org.tw.testyard.thread.Drop)
at org.tw.testyard.thread.Consumer.run(Consumer.java:15)
at java.lang.Thread.run(Unknown Source)
"Thread-0" prio=5 tid=0x00a88440 nid=0x6a4 waiting on condition [0x02ccf000..0x02ccfbe8]
at java.lang.Thread.sleep(Native Method)
at org.tw.testyard.thread.Producer.run(Producer.java:24)
at java.lang.Thread.run(Unknown Source)
In the thread dump snippet above you can observe the following
  • The thread dump starts with “Full thread dump”, followed by a list of threads currently being executed.
  • There are 2 application threads called Thread-1 and Thread-0. These are the default names which the JVM handed over to the threads.
  • “Thread-1″ is waiting for a notification after it called Object.wait() on the Drop object.
  • Similarly, “Thread-0″ is sleeping on a condition after it called Thread.sleep
  • At this particular instant, there are no threads in the runnable state and hence the application isn’t doing any real work.
Although thread dumps also lists the state of the system threads we are not going to look deeper into system threads.
How to take thread dumps
Thread dumps can be generated by the users as well as the system in unusual situations. The users can generate thread dumps by explicitly sending a signal to the JVM or programatically by calling java.lang.Exception.printStackTrace(). Calling printStackTrace() method will only cause the stack trace of the current thread to be printed.
On windows environment thread dumps can only be generated when the process is running in the fore ground and is associated with a command line console. Thread dumps can be generated by hitting the key combination Ctrl + \ (Back slash). On unix / linux enviroments thread dumps can be generated by the command kill -QUIT <process id of jvm> or kill -3 <process id of jvm>. Thread dumps are generally logged to the stderr. Depending on your start up commands you may find the thread dumps in some other log files. Please consult your system administrator for details. Taking thread dumps by either of the 2 strategies doesnt cause the application to terminate, the JVM dumps the execution state and continues.
Although very rare the JVM can also generate a thread dump when a thread causes the JVM to crash. The amount of information which gets logged is again implementation specific. Typically you will find information about the thread which caused the JVM to crash.

J2EE application using Eclipse + Tomcat 6


J2EE application using Eclipse + Tomcat 6

Following is the steps to configure tomcat in Eclipse. Afterward reading this article you will be able to launch your J2EE Applications from eclipse and debug them.
Requirements :
Eclipse IDE for Java EE Developers
Tomcat 6.0.x
The steps to follow are:
  1. Download Java  7  SDK
  2. Download Eclipse IDE for Java EE Developers
  3. Download & Install Tomcat 6
  4. Configure Eclipse to use Java  7as the Runtime
  5. Configure Eclipse to use Tomcat 6
  6. Creating a WEB EE Dynamic Project
Download Java 7 SDK
You can downolad Java from here.
This will download an executable file. Execute it and follow the wizard steps.
Download Eclipse IDE for Java EE Developers
You can download Eclipse IDE for Java EE Developers (aka Helios) here.
This download is also an executable file. Run it and follow the wizard steps.
I would highly recommend to take a look at this page (Eclipse documentation) for those that never used this software before.


Download & Install Tomcat 6
You can download Tomcat 6 from here
In this case I recommend downloading the zip version of it. Once it is download what I do is to unzip the file to a directory in the main drive, for example: c:\Tomcat6


Configure Eclipse to use Java 7
Once Eclipse is running (you should now how to start eclipse by now) we go to the Menu and select:
Window — Preferences, then you-ll see the following screen:
Then browse in the left panel: Java — Installed JREs and then click on the right button “Add…”
You’ll be prompted with a screen to select the type of JRE you want to add. In that screen select “Standard VM” and click Next. Then you’ll get to another screen where you will have add the information related to your JRE environment (the one you just downloaded on step 1):
JRE Home: directory depends on where you installed your Java JDK in step 1.
JRE Name: any valid name.
Click on finish and you are done, now you can use this JRE in your Java projects within this Eclipse setup.
Configure Eclipse to use Tomcat 6
Within Eclipse go to the Menu and select:
Window — Preferences, then in the window preferences browse: Server — Runtime Environments.  Then click on the right button “Add…”
In the followin screen you can choose and configure the Tomcat Application Server you just installed in step 3:
Click on Next to continue with the Server Configuration:
Name: Give it a name to identify your server within Eclipse
Tomcat Installation Directory: Location where you unzipped your tomcat on Step 3 (c:\Tomcat6)
JRE: Choose the JRE we just configured in the previous step (4)
Click on Finish and you are ready to create your first J2EE Dynamic Project in Eclise.
Creating a WEB J2EE Dynamic Project – Eclipse
Create a new Project in Eclipse within the project Explorer View in the Left panel by right-clicking on the panel and select New — Project…:
After selecting the “Dynamic Web Project” and clicking next, we need to fill in some information:
Step 1:
Step 2:
Step 3:
Then we click on “Finish” and our project will be ready.


Note: as you can see in the second step, there is a Configuration section where you need to select the Application Server you want to use. In this example I will be using Tomcat 6 configured previously in this post.
Your project is ready:
The name “Jaime’s Ideas – CWA”  has an explanation. I am using this project to explain something else related to SDL Tridion CWA Framework.
Next thing will be to create a JSP page and run your Project/J2EE application. Right-click over the WebContent folder select New — JSP File  and give it a name, for example index.jsp. Then write “HELLOW WORLD” within the body content of your file.
Now you can run your JSP by right-clicking over it (index.jsp) and selecting Run As — Run on Server. Now you will see the Server configured before, in the available servers for running:


Click on “Finish” and you will be running your JSP:

Now you are able to start working on  J2EE application using Eclipse + Tomcat 6  + Java 7.

major differences and similarity in java and ruby?

Ruby over Java?


Ruby is a scripting language and it is interpreted at the run time by the Ruby interpreter , The Ruby code is interpreted and converted to machine level language i.e Assembly code . Talking about the platform Independence you can run ruby code in any of the the platform like Linux ,Windows or Mac if you have platform dependent Ruby Interpreter installed.Ruby is slower  than Java to run but faster to write, or read whereas Java takes too long to develop
Where as in Java , it is Compiled and converted to an intermediate byte class and this byte class is interpreted by platform dependent JVM (Java Virtual Machine ) .
In that way you can think you Ruby source file as byte class which can be run on any platform ,with one difference byte class is already compiled but ruby source file will be compiled at the Run time .
The Object Oriented feature in Ruby is actually very different compared to Java. In Ruby, everything is an object, including a primitive type (in Java) like integer. In Ruby, new is like a property instead of a keyword. So to instantiate an object you would do this in Ruby:
animal = Animal.new
Ruby is strong typing but also dynamic.Ruby enables you to do duck typing.Ruby’s answer to multiple inheritance is mixin (which is a language feature), where in Java you would implement many interfaces.Ruby has got block, where you would use anonymous class to achieve the same thing in Java. But IMHO Ruby block is more powerful.
Similarities
As with Java, in Ruby,…
Memory is managed for you via a garbage collector.
Objects are strongly typed.
There are public, private, and protected methods.
There are embedded doc tools (Ruby’s is called RDoc). The docs generated by rdoc look very similar to those generated by javadoc.
Differences
Unlike Java, in Ruby,…
You don’t need to compile your code. You just run it directly.
There are several different popular third-party GUI toolkits. Ruby users can try WxRuby, FXRuby, Ruby-GNOME2, or the bundled-in Ruby Tk for example.
You use the end keyword after defining things like classes, instead of having to put braces around blocks of code.
You have require instead of import.
All member variables are private. From the outside, you access everything via methods.
Parentheses in method calls are usually optional and often omitted.
Everything is an object, including numbers like 2 and 3.14159.
There’s no static type checking.
Variable names are just labels. They don’t have a type associated with them.
There are no type declarations. You just assign to new variable names as-needed and they just “spring up” (i.e. a = [1,2,3] rather than int[] a = {1,2,3};).
There’s no casting. Just call the methods. Your unit tests should tell you before you even run the code if you’re going to see an exception.
It’s foo = Foo.new( “hi”) instead of Foo foo = new Foo( “hi” ).
The constructor is always named “initialize” instead of the name of the class.
You have “mixin’s” instead of interfaces.
YAML tends to be favored over XML.
It’s nil instead of null.
== and equals() are handled differently in Ruby. Use == when you want to test equivalence in Ruby (equals() is Java). Use equal?() when you want to know if two objects are the same (== in Java).
simple data structure in Java
class MySimpleStructure{
int data1;
int data2;
MyOtherDataStructure m1;
}

MySimpleStructure s1 = new MySimpleStructure();
s1.data1 = 19;
s1.m1 = new MyOtherDataStructure();
Equivalent implementation in Ruby.
class MySimpleStructure
attr_accessor :data1, :data2, m1
end

s1 = MySimpleStructure.new
s1.data1 = 19
s1.m1 = MyOtherDataStructure.new

Webservices and API

Webservices and — Javamazon:

Webservices and API

An API is an Application Programming Interface, it's the means by which third parties can write code that interfaces with other code. A Web Service is a type of API, almost always one that operates over HTTP (Though some, like SOAP, can use alternate transports, like SMTP). The Official W3C Definition mentions that Web Services don't necessarily use HTTP, but this is almost always the case and is usually assumed unless otherwise mentioned.

For examples of web services specifically see SOAP, REST, and XML-RPC.

As an example of another type of API, one written in C for use on a local machine, see the Linux Kernel API
As far as protocol goes, a Webservice API almost always uses HTTP (hence the Web part), and definitely involves communication over a network. APIs in general can use any means of communication they wish. The Linux kernel API for example uses Interrupts to invoke the system calls that comprise its API for calls from userspace.
Webservice is a method of communication between two machines while an API is an exposed layer allowing you to program against something.

You could very well have an API and the main method of interacting with that API is via a webservice. API is code based integration while web service is message based integration with interoperable standards having a contract such as WSDL.

The technical definitions (courtesy of Wikipedia) are:

 API
An application programming interface (API) is a set of routines, data structures, object classes and/or protocols provided by libraries and/or operating system services in order to support the building of applications.

 Webservice
 A Web service (also Web Service) is defined by the W3C as "a software system designed to support interoperable machine-to-machine interaction over a network"

Example 1 :
API's are a published interface which defines how component A communicates with component B.

For example, Doubleclick have a published Java API which allows users to interrogate the database tables to get information about their online advertising campaign.

e.g. call GetNumberClicks (user name)

To implement the API, you have to add the Doubleclick .jar file to your class path. The call is local.

A web service is a form of API where the interface is defined by means of a WSDL. This allows remote calling of an interface over HTTP.

If Doubleclick implemented their interface as a web service, they would use something like Axis2 running inside Tomcat.The remote user would call the web service

e.g. call GetNumberClicksWebService (user name)

and the GetNumberClicksWebService service would call GetNumberClicks locally.

Example 2:

API(Application Programming Interface), the full form itself suggests that its an Interface which allows you to program for your application with the help or support of some other Application's Interface which exposes some sort of functionality which is useful to your application.

E.g showing updated currency exchange rates on your website would need some third party Interface to program against unless you plan to have your own database with currency rates and regular updates to the same. This set of functionality is when already available with some one else and when they want to share it with others they have to have an endpoint to communicate with the others who are interested in such interactions so they deploy it on web by the means of web-services. This end point is nothing but interface of their application which you can program against hence API.

another example: google map api vs google direction api web service, while the former serves (delivers) javascript file to the site (which can then be used as an api to make new functions) , the later is a Rest web service delivering data (in json or xml format), which can be processed (but not used in an api sense).

Google halts new orders for 16GB Nexus 7


Review on Nexus 7

First – a note on the hardware. Despite the price, it feels like a solid, well-made, quality product. Both the screen and casing feel and look good.The software – pretty simple, robust and performant. I suspected it might be a poor cousin to the iPad’s iOS but in UI and responsiveness terms it’s at least the equal of iOS.
We all know that Android 4.2 aka Jelly Bean brings -this device is quite noticeably heavier than an Amazon Kindle – and that is one area where the specification of the iPad mini looks to be a winner.Google speech search is great fun to use and pretty accurate. The GPS on this device made travel abroad fun, especially with location features on.Unit size and weight is just right, easy one handed use for long periods. Web pages display well on this device, often loading the mobile/smart phone site, but easily switched to the full sites. Movies look great. Fantastic range of game apps.
android 4.2,nexus 4, nexus 7, nexus 10,jelly bean android 4.2
According to the Guardian :
The Guardian understands that Google’s planners had thought that buyers on the Google Play store, more than from physical or online retailers, would be more committed to the company’s “cloud” concept, and so would have more of their content stored online, rather than wanting to keep it on the device.
The Nexus 7  appears to have been a huge hit, although Google has not yet released any figures for sales. Its principal competitors for sales in physical stores such as Currys and PC World in the UK are Apple’s iPad and Amazon’s Kindle Touch. A spokesperson for Dixons Retail, which sells all three, said sales of the Nexus 7 have been “extremely brisk” but declined to say where it ranked against the other two.
In the UK, Tesco is understood to have turned down a number of orders made online for the 16GB version after overwhelming demand. It is not selling the 8GB version.Google has seen huge demand for the Nexus 7 since announcing it on 27 June and offering online ordering directly from the Google Play online store, followed a few days later by the announcement that a number of physical retailers would be selling it.

permanent generation of objects in the VM

jvm,,permgen — Javamazon:


If you see java.lang.OutOfMemoryError: PermGen space errors, you need to increase the permanent generation space available to Eclipse.increase permgen size in Eclipse
PermGen is the permanent generation of objects in the VM (Class names, internalized strings, objects that will never get garbage-collected). An easy, if somewhat memory-hungry fix is to enlarge the maximum space for these objects by adding.
-XX:MaxPermSize=128M
as an argument to the JVM when starting Eclipse. The recommended way to do this is via your eclipse.ini file.
Alternatively, you can invoke the Eclipse executable with command-line arguments directly, as in
1
eclipse [normal arguments] -vmargs -XX:PermSize=64M -XX:MaxPermSize=128M
The arguments after -vmargs are directly passed to the VM. Run java -X for the list of options your VM accepts. Options starting with -X are implementation-specific and may not be applicable to all JVMs.

OpenShift Platform as a Service (PaaS)

OpenShift Platform as a Service (PaaS) — Javamazon:

Platform as a Service (PaaS):

OpenShift is Red Hat’s Cloud Computing Platform as a Service (PaaS) offering. OpenShift is an application platform in the cloud where application developers and teams can build, test, deploy, and run their applications.
overview-paas

How do I use OpenShift?

For a Developer to use OpenShift to take advantage of the power and elasticity of the Cloud, they need only do the following:
  • Create an “Application” in OpenShift (With the command-line or via their IDE)
  • Code the application (in Vi, TextMate, Eclipse, Visual Studio, or whatever)
  • Push the application code to OpenShift (again, with the command-line or from their IDE)
Go on and read more on Red Hat Network and get a free trail of PaaS , in Short this all requires is your application .jar file which could be deployed to cloud and get off /start accessing your application.
More on RED HAT