Tuesday, September 30, 2014

Tuning Process

Performance Principles
Common Performance Problems
Performance Methodology
Development and Performance
Monitoring Operating System Performance
Monitor CPU Usage
Monitor Network I/O
Monitor Disk I/O
Monitor Virtual Memory Usage
Monitor and Identify Lock Contention
Monitoring the JVM
HotSpot Generational Garbage Collector
Monitor the Garbage Collector with Command Line Tools
Monitor the Garbage Collector with VisualVM
Monitor the JIT Compiler
Throughput and Responsiveness
Performance Profiling
NetBeans Profiler, Oracle Solaris Studio, and jmap/jhat
Profile CPU Usage
Profile JVM Heap
Find Memory Leaks
Identify Lock Contention
Heap Profiling Anti-patters
Method Profiling Anti-patterns
Garbage Collection Schemes
Garbage Collection
Generational Garbage Collection
GC Performance Metrics
Garbage Collection Algorithms
Types of Garbage Collectors
JVM Ergonomics
Garbage Collection Tuning
Tune the Garbage Collection
Select the Garbage Collector
Interpret GC Output
Language Level Concerns and Garbage Collection
The best practices for Object Allocation
Invoking the Garbage Collector
Reference Types in Java
The use of Finalizers
Performance Tuning at the Language Level
String-efficient Java Applications
Collection Classes
Using Threads
Using I/O Efficiently


On the other hand, good object-oriented design actually encourages many small methods
and significant polymorphism in the method hierarchy

However, this technique cannot be applied Ofreilly - Java Performance Tuning
- 9 -
when it is too difficult to determine method calls at compile time, as is the case for many Java
methods.

A lot of time (in CPU cycles) passes while the user is reacting to the application interface. This time
can be used to anticipate what the user wants to do (using a background low priority thread), so that
precalculated results are ready to assist the user immediately. This makes an application appear
blazingly fast.

 Multiuser response times depending on the number of users (if applicable)
 Systemwide throughput (e.g., number of transactions per minute for the system as a whole,
or response times on a saturated network, again if applicable)
 The maximum number of users, data, files, file sizes, objects, etc., the application supports
 Any acceptable and expected degradation in performance between minimal, average, and
extreme values of supported resources

You must specify target times for each benchmark. You should specify ranges: for example, best
times, acceptable times, etc.

CPU time (the time allocated on the CPU for a particular procedure)
 The number of runnable processes waiting for the CPU (this gives you an idea of CPU
contention)
 Paging of processes
 Memory sizes
 Disk throughput
 Disk scanning times
 Network traffic, throughput, and latency
 Transaction rates
 Other system values


For distributed applications , you need to break down measurements into times spent on each
component, times spent preparing data for transfer and from transfer (e.g., marshalling and
unmarshalling objects and writing to and reading from a buffer), and times spent in network
transfer. Each separate machine used on the networked system needs to be monitored during the test
if any system parameters are to be included in the measurements. T



Any decoupling, indirection, abstraction, or extra layers in the design are highly likely to be
candidates for causing performance problems. You should include all these elements in your design
if they are called for. But you need to be careful to design using interfaces in such a way that the
concrete implementation allows any possible performance optimizations to be incorporated. Design
elements that block, copy, queue, or distribute also frequently cause performance problems. These
elements can be difficult to optimize, and the design should focus attention on them and ensure that
they can either be replaced or that their performance is targeted.
[7]
 Asynchronous and background
events can affect times unpredictably, and their effects need to be clearly identified by benchmark
testing.


The behavior and efficiency of the garbage collector used can heavily influence the performance and responsiveness of an application thatfs taking advantage of it


Clocks per CPU instruction, usually referred to as CPI, for an application is a ratio of the number of CPU clock ticks used per CPU instruction. CPI is a measure of the efficiency of generated code that is produced by a compiler. A change in the application, JVM, or operating system that reduces the CPI for an application will realize an improvement in its performance since it takes advantage of better and more optimized generated code.



1.using verbosege option with the VM to print out garbage collector staticstics,it gives idea how often garbage collector is running .
2.application partioning ,data compressing
3.Larger heap take longer to collect garbage
young generation,old generation,permanent generation --- see it
5.Most employ a gstop the worldh collection, meaning the running
application must stop processing while the GC is engaged.
? Therefore frequent or large amounts of collection affect the
performance of your application.There are four garbage collector
6.use most updated jdk
7Hints are added to the command line start up of an application, such as
g-XX:+UseAdaptiveGCBoundaryh to allow the Garbage Collector to
change the allotted space between Young and Old Generations.
8.gThe Garbage Collector runs too frequently / is too slow.h

 Try to reduce the number of temporary objects that are created.
 If all else fails, carefully consider using a different garbage collector.
 The Parallel Compactor (good for multiple CPUs where response
time isnft as important as overall throughput) can be selected with
the -XX:+UseParallelGC command line option.
 The Parallel Compacting Collector (good for multiple CPUs where
response time is more important) can be selected with the
XX:ParallelGCThreads=n command line option.
9.gThe Garbage Collector...h (cont.)

The Concurrent Mark-Sweep Collector (good for apps running on
machines with few CPUs that needs more frequent garbage
collection) can be selected with the -XX:+UseConcMarkSweepGC
command line option.

9.Monitor and identify lock contention
10.Select the Garbage Collector
11.Invoking the Garbage Collector
12.Interpret GC Output
13.Garbage Collection Algorithms
Types of Garbage Collectors
14.Tune garbage collectors
15.Tune Just in Time (JIT) compilers
16.Examine and tune 64 bit JVMs
? Optimize the JVM for Multi-core platforms
17.Tune 64 bit JVM for different application requirements
o Tune a 64 bit JVM for a specific application
18.Optimize the JVM for Multi-core platforms
19.Select collector that best fits application characteristics and
requirements
20.Measure frequency and duration of collections

21.The algorithms and parameters used by GC can have dramatic effects on performance

22.Demonstrates that an application that spends 10% of its time in garbage collection can lose 75% of its throughput when scaled out to 32 processors
23.permanent generation
holds all the reflective data of the virtual machine itself, such as class and method objects
24.Young generation ? all new objects are created here. Majority of GC activity takes place here and is usually fast (Minor GC).
Old generation ? long lived objects are promoted (or tenured) to the old generation. Fewer GCfs occur here, but when they do, it can be lengthy (Major GC).
25.The permanent generation holds objects that the JVM finds convenient to have the garbage collector manage, such as objects describing classes and methods, as well as the classes and methods themselves.
26.Yound generation collector

Serial Copying Collector
All J2SEs (1.4.x default)
Stop-the-world
Single threaded
Parallel Copying Collector
-XX:+UseParNewGC
JS2E 1.4.1+ (1.5.x default)
Stop-the-world
Multi-threaded
Parallel Scavenge Collector
-XX:UseParallelGC
JS2E 1.4.1+
Like Parallel Copying Collector
Tuned for very large heaps (over 10GB) w/ multiple CPUs
Must use Mark-Compact Collector in Old Generation


Old generation collector :

Mark-Compact Collector
All J2SEs (1.4.x default)
Stop-the-world
Single threaded
Train (or Incremental) Collector
-Xincgc
About 10% performance overhead
All J2SEs
To be replaced by CMS Collector
Concurrent Mark-Sweep (CMS) Collector
-XX:+UseConcMarkSweepGC
J2SE 1.4.1+ (1.5.x default (-Xincgc))
Mostly concurrent
Single threaded


28.Lots of cast
29.Replace multiple objects by sinlge object or few

30 String test=new String("test");
String test=new String("test");
two objects if used
String test="test";
String test1="test";
two points to same objects
vector is synchronized
hashtable  is synchronized  and hashmap is not

Important to understand

the internal representation of a Java object and an internal representation of a Java class are very similar. From this point on let me just call them Java objects and Java classes and you'll understand that I'm referring to their internal representation. The Java objects and Java classes are similar to the extent that during a garbage collection both are viewed just as objects and are collected in exactly the same way. So why store the Java objects in a separate permanent generation? Why not just store the Java classes in the heap along with the Java objects?

Classes also have classes that describe their content.


important
//he permanent generation holds objects that the JVM finds convenient to have the garbage collector manage, such as objects describing classes and methods, as well as the classes and methods themselves.

//dynamic binding is slower than static binding,

//Minimize Subclasses and Method Overriding

How spring transaction API is designed and works with multi threading

Every thread have common value of operation like what type of operation to go Or standard protocol when to commit ,when to rollback,how many transaction object to create so it is set once and use by all threads

Whether every thread share same object,Or for every thread the object is different.If they share it will be singleton and need synchronization .

Creating a common scenario of data for db operation for all thread by setting as singleton

there are lost of set method in a class in DataSourceTransactionManager.So,first make sure what is common protocol  for all threads

MultiThreading Data Select

package org.apache.tomcat.jdbc.pool.jmx;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

public class MockCommonDao extends SqlMapClientDaoSupport {

ArrayList<ArrayList> listOlists = new ArrayList<ArrayList>();

public List selectByExample(List<Object> example)
   {
List<Future<Object>> listOlists = null;
ExecutorService executor = Executors.newFixedThreadPool(example.size());
List<TransactionImpl> callingList = new ArrayList<MockCommonDao.TransactionImpl>();
for (int i = 0; i < example.size(); i++) {
             TransactionImpl localImpl = new TransactionImpl(example.get(i));
             callingList.add(localImpl);
         }
try {
           
listOlists = executor.invokeAll(callingList);

         } catch (InterruptedException e) {
           
         }
         return listOlists;
       

               
   
     
   }
private String getClassNameFromExample(Object example)
   {
       String tableName = example.getClass().getName();
       int cnt = tableName.indexOf("Example");
       int last = tableName.lastIndexOf('.');
       tableName = tableName.substring(last + 1, cnt);
       return tableName.toUpperCase();
   }
 private class TransactionImpl implements Callable<Object>{
 private Object example;


 TransactionImpl(Object Criteria) {
           this.example = Criteria;

       }


@Override
public Object call() throws Exception {

            List list = getSqlMapClientTemplate().queryForList((new StringBuilder(String.valueOf(getClassNameFromExample(example)))).append(".ibatorgenerated_selectByExample").toString(), example);
            listOlists.add((ArrayList) list);
            return listOlists;
 }
 }}





Best Approaches for transaction control

Approach one
Catch the exception.Do not apply transaction to any method.If exception is thrown catch it and set  checkforcommit=false.If false pro-grammatically rollback the transaction using spring provided classes . Other wise programmatically commit the transaction

MultiThreading and Exception

Class ThreadException {

TestKl0t1Example example = new TestKl0t1Example();
TestKl0t1Example.Criteria criteria = example.createCriteria();
criteria.andT1trnoEqualTo(new BigDecimal(dto.getTranNo()))

List<Object> dbResult = getCommonDao()
.selectByExampleDltmOff(example);


t1 = (TestKl0t1) dbResult.get(0);
List<TestKl0t1> results = new ArrayList<TestKl0t1>();
for (int i = 0; i < dbResult.size(); i++) {
results.add((TestKl0t1) dbResult.get(i));
}
ExecutorService executor = Executors.newFixedThreadPool(dbResult
.size());
List<Transactiompl> callingList = new ArrayList<ThreadException.Transactiompl>();
for (int i = 0; i < dbResult.size(); i++) {
Transactiompl localImpl = new Transactiompl(dbResult.get(i));
callingList.add(localImpl);
}
List<Future<TestKl0t1>> results1 = null;

try {

results1 = executor.invokeAll(callingList);

// executor.shutdown();
// while (!executor.isTerminated()) {
// executor=null;
// }

} catch (Exception e) {
executor = null;

}
executor = null;

}
Class Transactiompl extends RequestContextAwareCallable{
Transactiompl(Object readTestKl0t1) {
this.t1 = (TestKl0t1) readTestKl0t1;

}



public TestKl0t1 onCall() throws InterruptedException {
beginTransaction();





public abstract class RequestContextAwareCallable<V> implements Callable<V> {

private final RequestAttributes requestAttributes;
private Thread thread;

public RequestContextAwareCallable() {
this.requestAttributes = RequestContextHolder
.getRequestAttributes();
this.thread = Thread.currentThread();
}

public V call() throws Exception {
try {
RequestContextHolder.setRequestAttributes(requestAttributes);
return onCall();
} catch (Exception e) {
System.out.println("Oh boy, something broke!");
e.printStackTrace();
rollbackTransaction();
checkforcommit=false;
throw e;


}

finally {
if (Thread.currentThread() != thread) {
RequestContextHolder.resetRequestAttributes();
}

thread = null;
}
}

public abstract V onCall() throws Exception;
public void beginTransaction() {

DefaultTransactionDefition txDef = new DefaultTransactionDefition();
txDef.setPropagationBehavior(0);
txStatus = txManager.getTransaction(txDef);
}

public void commitTransaction() {
if (txStatus != null) {
if (!txStatus.isCompleted())
txManager.commit(txStatus);
} else {
System.out.println("error");
}
}

public void rollbackTransaction() {
if (txStatus != null) {
if (!txStatus.isCompleted())
txManager.rollback(txStatus);
} else {
System.out.println("rollbackcalled");
}
}
}

@Override
public void resetGlobalVariables() {
// TODO Auto-generated method stub

}

private PlatformTransactionManager txManager;

public void setTxManager(PlatformTransactionManager txManager) {
this.txManager = txManager;
}

public PlatformTransactionManager getTxManager() {
return txManager;
}

Example 5

<aop:config>
<aop:aspect id="ResetGlobalVariablesInterceptor" ref="resetGlobalVariablesAspect">
<aop:pointcut id="resetGlobalVariablesPointcut" expression="execution(* *..*BServiceImpl.executeRealBatch(..)) " />
<aop:pointcut id="resetGlobalVariablesPointcut1" expression="execution(* com.utility.occasionalbatch.server.service.impl.*ServiceImpl.execute(..))" />
<aop:pointcut id="resetGlobalVariablesPointcut12" expression="execution(public * *..*EServiceImpl.*(..)) or execution(public * *..*QServiceImpl.*(..)) or execution(public * *..*LServiceImpl.*(..)) or execution(* *..KKC*ServiceImpl.*(..))
and not execution(* com.sample..*(..)) and not execution(* com.extend..*(..)) and not execution(* com.utility.occasionalbatch..*(..))" />
<aop:before pointcut-ref="resetGlobalVariablesPointcut12" method="resetGlobalVariablesMaster" />
<aop:before pointcut-ref="resetGlobalVariablesPointcut" method="resetGlobalVariables" />
<aop:before pointcut-ref="resetGlobalVariablesPointcut1" method="resetGlobalVariables1" />
</aop:aspect>
</aop:config>

<bean id="resetGlobalVariablesAspect" class="com.extend.aop.ResetGlobalVariablesInterceptor">
<property name="order" value="125" />
</bean>

Example 3

<aop:config>
<aop:aspect id="InterceptorForComponentCall" ref="interceptorForComponentCall">
<aop:pointcut id="pointCutForComponentCall" expression="execution(* *..MMC*ServiceImpl.*(..)) or execution(* *..MMC0010BServiceImpl.*(..))" />
<aop:before pointcut-ref="pointCutForComponentCall" method="setPGMID" />
</aop:aspect>
</aop:config>
<bean id="interceptorForComponentCall" class="com.extend.aop.InterceptorForComponentCall">
<property name="order" value="135" />
</bean>

Example 2

<aop:config>
<aop:aspect id="PGMIDIntercepter" ref="pgmIDAspect">
<aop:pointcut id="pgmIDPointcut" expression="execution(* *..BBC*ServiceImpl.*(..)) or execution(* *..BBC0010BServiceImpl.*(..))" />
<aop:before pointcut-ref="pgmIDPointcut" method="setPGMIDBefore" />
</aop:aspect>
</aop:config>
<bean id="pgmIDAspect" class="com.extend.aop.PGMIDInterceptor">
<property name="order" value="90" />
</bean>

  <aop:config>
<aop:aspect id="InterceptorForComponentCall" ref="interceptorForComponentCall">
<aop:pointcut id="pointCutForComponentCall" expression="execution(* *..BBC*ServiceImpl.*(..)) or execution(* *..BBC0010BServiceImpl.*(..))" />
<aop:before pointcut-ref="pointCutForComponentCall" method="setPGMID" />
</aop:aspect>
</aop:config>

Example 1

<bean id="whitespaceAspect" class="com.extend.aop.TrimInterceptor" />
  <aop:config>
    <aop:aspect ref="TrimwhitespaceAspect">
      <aop:pointcut id="trimWhitespacePointCut"
        expression="execution(* com.base.dao.CommonDAO.selec*(..)) )" />
      <aop:after-returng pointcut-ref="trimWhitespacePointCut"
        method="trimWhitespaces" returng="returnedData" />
    </aop:aspect>
  </aop:config>

Monday, September 29, 2014

Providing ability to software to add feature dynamically

 provide common functions of batch processing
 provide the ability to manage an application exception.
 provide the ability to manage the application log.
And provide the ability to create Excel.
And provide the ability to create PDF.
Intercept (service calls, Dao call) the various processes, and to provide the ability to realize the call of common functions.

 provide the ability to record access, login logout to each function.
provide the function according to the preferred language of the user, controls the display language of the screen fields.
To provide the ability to control the display of dialog language message according to the preferred language of the user
 provide the ability to hold the common information of the authentication information
Among the information stored in the preconditioned master, provide a function of holding the information to be cached in the entire system.

Providing ability for database access control

Ways ho hold data of the client on server

Adding ability to software for features

Features controlled by DB data .According to setting performed on DB master ,features behaves in polymorphic way according to data present on precondition and post condition master modules

Ways for enabling and disabling feature

Internationalization and Localization.
Custom tag with different attributes .The value of attributes controlled from configuration files .Like db ,xml or other

Preloading and Lazy loading Beans

Employee emp = (Employee) factory.getBean("employeeBean"); // 2
Even though "beans.xml" configuration file is loaded with BeanFactory container in line number 1, none of the beans will be instantiated. Instantiation takes place only at line number 2, where bean called "employeeBean" is requested from container. Since the class is instantiated at getBean() method call, time spend to return this method will vary depending on the instantiated object.


ApplicationContext context =
            new ClassPathXmlApplicationContext("beans.xml"); // 1
Employee emp = (Employee) context.getBean("employeeBean"); // 2
As all singleton beans are instantiated by container at line number 1, this line will take some considerable time to complete. However line number 2 will return the bean instance immediately since instances are already available inside the container.


destroy-method="close">

The init-methodattribute specifies a
method that is to be called on the beanimmediately upon instantiation. Similarly,
destroy-method specifies a method that is called just before a bean is removed from
the container.In our case



When some Web Application Shut downs Spring's web-based ApplicationContext handles shutting down gracefully but for a non web application if you want the container to shutdown gracefully and call the relevant destroy callbacks on your singleton beans, you will need to register a shutdown hook with the JVM.

So for registering a shutdown hook that enables the graceful shutdown for the relevant Spring IoC container, we simply need to call the registerShutdownHook () method that is declared on the AbstractApplicationContext class.

public final class Test {

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

AbstractApplicationContext ctx= new ClassPathXmlApplicationContext(new String []{"test.xml"});
ctx.registerShutdownHook();
// app runs here...
// main method exits, hook is called prior to the app shutting down...
}
}

when container is shut down it is destroyed .But in our case the bean is never destroyed and application context is also not shutdown unless tomcat is restarted .context.close()destroyed.and at that time the destroy method that is defined in bean definition file is called for example in our case it is close which is called
'

destroy-methodspecifies a method that is called just before a bean is removed from
the container.

Web Service Testing Example



package testingWS;

import groovyx.net.http.ContentType;

import org.junit.Before;
import org.junit.Test;

import com.jayway.restassured.RestAssured;
import com.jayway.restassured.path.json.JsonPath;
import com.jayway.restassured.response.Response;

import static com.jayway.restassured.RestAssured.expect;
import static com.jayway.restassured.RestAssured.get;
import static com.jayway.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.*;


public class TestingUsingRestAssured {

 @Before
   public void setUp(){
    //  do something
   }



@Test
public void testUserFetchesSuccess() {
expect().
body("id", equalTo(12)).
body("firstName", equalTo("Tim")).
body("lastName", equalTo("Tester")).
when().
get("/abc/users/id/12");
}


@Test
   public void testGetProducts(){
       expect().statusCode(200).contentType(ContentType.JSON)
       .when().get("/abc/users/id/1");
   }



// testing a simple response containing some JSON data
@Test
public void testGetSingleUser() {
 expect().
   statusCode(200).
   body(
     "firstName", equalTo("Tim"),
     "lastName", equalTo("Testerman"),
     "id", equalTo(1)).
   when().
   get("/abc/users/single-user");
}

@Test
public void testGetSingleUse1r() {
given().
pathParam("id",1).
expect().
statusCode(200).
body("id", equalTo(1),
"firstName", equalTo("Tim")).

when().
get("/abc/users/id");
}




//we’re using JsonPath to programatically test the returned JSON structure we’re
//using JsonPath to programatically test the returned JSON structure
@Test
public void testGetSingleUserProgrammatic() {

  Response res = get("/abc/users/single-user");

  assertEquals(200, res.getStatusCode());

  String json = res.asString();
  JsonPath jp = new JsonPath(json);

  assertEquals("Tim", jp.get("firstName"));
  assertEquals("Testerman", jp.get("lastName"));
  assertEquals(1, jp.get("id"));
}







// handling basic authentication
// Response Status: 401 Unauthorized/ 200 Status Ok (when logged in with username=admin and password=admin)
/* @Test
public void testAuthenticationWorking() {
  // we're not authenticated, service returns "401 Unauthorized"
  expect().
    statusCode(401).
  when().
  get("/abc/users/secure/person");
  // with authentication it is working
  expect().
    statusCode(200).
  when().
    with().
      authentication().basic("admin", "admin").
  get("/abc/users/secure/person");
}*/


/* @Test
public void testCreateuser() {
  final String firstName = "Tim";
  final String lastName = "Tester";

  given().
    parameters(
      "firstName", firstName,
      "lastName", lastName).
  expect().
    body("firstName", equalTo(firstName)).
    body("lastName", equalTo(lastName)).
  when().
  get("/abc/users/create");
}*/

}

Example 10



package testingWS;

import static org.junit.Assert.assertEquals;


import org.junit.Test;

import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.test.framework.AppDescriptor;
import com.sun.jersey.test.framework.JerseyTest;
import com.sun.jersey.test.framework.WebAppDescriptor;
//jettison reads and writes json
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;


public class TestingUsingJerseyTestFrameWork extends JerseyTest {

@Override
protected AppDescriptor configure() {
// traffic logging
// enable(TestProperties.LOG_TRAFFIC);
//If set to true the property enables basic logging of the request and response flow on both - client and server
return new WebAppDescriptor.Builder().build();
}

 @Test
public void testUser() throws JSONException{
 WebResource webResource = client().resource("http://localhost:8080/");
 JSONObject json =webResource.path("/abc/users/id/12") .get(JSONObject.class);

// String jsonStringObj = json.toString();
 //String jsonStringObj = json.toString();
//  Gson gson = new Gson();
/*  User obj = gson.fromJson(jsonStringObj, User.class);*/

 assertEquals(12,json.get("id"));
 assertEquals("Tim", json.get("firstName"));
 assertEquals("Tester", json.get("lastName"));

 }

 @Test
 public void testTrack() throws JSONException{
 WebResource webResource = client().resource("http://localhost:8080/");
 JSONObject json =webResource.path("/abc/users/get").get(JSONObject.class);
 //String jsonStringObj = json.toString();
/*  Gson gson = new Gson();
 User obj = gson.fromJson(jsonStringObj, User.class);*/

 assertEquals("Mr. Big",json.get("singer"));
 assertEquals("Wild World", json.get("title"));
 }


}

Example



 package testingWS;

 import org.junit.Test;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class TestingUsingJerseyClient {

@Test
public void testgetUsingJerseyClient(){
Client client = Client.create();
WebResource webResource = client
  .resource("http://localhost:8080/abcrAuthorization/api/authz");
ClientResponse response = webResource.accept("application/json")
                   .get(ClientResponse.class);


if (response.getStatus() != 200) {
  throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}

String output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println("Output from Server .... \n"+output);
}

@Test
public void testpostUsingJerseyClient(){
Client client = Client.create();
WebResource webResource = client
  .resource("http://localhost:8080/abc/users/post");
String input = "{\"singer\":\"Mr. Big\",\"title\":\"Wild World\"}";
ClientResponse response = webResource.type("application/json")
  .post(ClientResponse.class, input);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
    + response.getStatus());
}
String output = response.getEntity(String.class);

}

}

Sample 8



package testingWS;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import First.Track;
import First.User;
import First.UserWebService;
import Service.TrackService;
import Service.UserService;


public class TestingDuringDevelopment {

@Mock
private UserService userService;

@Mock TrackService trackService;

@InjectMocks
private UserWebService userWebServiceMock=new UserWebService();


@Before
public void testBefore() {
MockitoAnnotations.initMocks(this);
User user = new User();
user.setId(12);
user.setFirstName("Tim");
user.setLastName("Tester");
when(userService.getUser(12)).thenReturn(user);

Track track = new Track();
track.setTitle("AWMAWY");
track.setSinger("Joe Satriani");
when(trackService.getTrack()).thenReturn(track);
}

@Test
public void testTrack(){
Track track= userWebServiceMock.getTrackInJSON();
Track newTrack=new Track();
newTrack.setSinger("Joe Satriani");
newTrack.setTitle("AWMAWY");
assertEquals(track.getSinger(), newTrack.getSinger());
assertEquals(track.getTitle(), newTrack.getTitle());
verify(trackService);

}


}

Sample 7

package FrameworkWrapper;


import javax.net.ssl.HttpsURLConnection;
import java.net.HttpURLConnection;
import java.net.URLConnection;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Scanner;

public class SimpleRestClient {

    public Response doGetRequest(URL url, HashMap<String,String> headers, HashMap<String,String> params, boolean debug) {
        GET get = new GET(url, headers, params);
        return sendRequest(get, debug);
    }

    public Response doPostRequest(URL url, HashMap<String,String> headers, String body, boolean debug) {
        POST post = new POST(url, headers, body);
        return sendRequest(post, debug);
    }

    private Response sendRequest(Request request, boolean debug) {
        HttpURLConnection conn = null;
        Response response = null;
        long time = 0;

        try {
            conn = (HttpURLConnection) request.getUrl().openConnection();

            if (request.headers != null) {
                for (String header : request.headers.keySet()) {
                    conn.addRequestProperty(header, request.headers.get(header));
                }
            }

            time = System.currentTimeMillis();          

            if (request instanceof POST) {
                byte[] payload = ((POST)request).body.getBytes();

                conn.setDoOutput(true);
                conn.setFixedLengthStreamingMode(payload.length);
                conn.getOutputStream().write(payload);
            }

            int status = conn.getResponseCode();

            if(status != HttpURLConnection.HTTP_OK)
                response = new Response(status, conn.getResponseMessage());
            else
                response = new Response(status, readInputStream(conn.getInputStream()));

            response.time = System.currentTimeMillis() - time;
            if(debug) dumpRequest(request, response);

        } catch (IOException e) {
            e.printStackTrace(System.err);

        } finally {
            if (conn != null)
                conn.disconnect();
        }

        return response;
    }

    private static String readInputStream(InputStream is) throws IOException {
        Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }

    /**
     * Convenience method to output everything about the request
     */
    public void dumpRequest(Request req, Response resp)
            throws MalformedURLException {
        StringBuilder sb = new StringBuilder();
        sb.append("=> Dumping request information:");
        sb.append("\n").append("======================= REQUEST ==========================");
        sb.append("\n==> ").append("URL: ").append(req.getUrl());
        sb.append("\n==> ").append("Method: ").append((req instanceof POST ? "POST" : "GET"));

        if(req.headers != null) {
            for(String header : req.headers.keySet())
                sb.append("\n===> ").append("Header: ").append(header).append(": ").append(req.headers.get(header));
        }

        if(req instanceof GET && ((GET)req).params != null){
            for(String param : ((GET)req).params.keySet())
                sb.append("\n===> ").append("Param: ").append(param).append("=").append(((GET)req).params.get(param));
        }

        if(req instanceof POST)
            sb.append("\n==> ").append("Request body: ").append(((POST)req).body);

        sb.append("\n").append("======================= RESPONSE =========================");

        sb.append("\n==> ").append("Round trip time: ").append(resp.time).append(" ms");
        sb.append("\n==> ").append("Response status: ").append(resp.status);      
        sb.append("\n==> ").append("Response body:\n").append(resp.body);      

        sb.append("\n==========================================================");

        System.out.println(sb.toString());
    }


    private class Request {
        public URL baseUrl;
        public HashMap<String,String> headers;

        public Request(URL baseUrl, HashMap<String,String> headers) {
            this.baseUrl = baseUrl;
            this.headers = headers;
        }

        public URL getUrl() throws MalformedURLException{
            return baseUrl;
        }
    }

    private class POST extends Request {
        public String body;

        public POST(URL baseUrl, HashMap<String,String> headers, String body){
            super(baseUrl, headers);
            this.body = body;
        }
    }

    private class GET extends Request {
        public HashMap<String,String> params;

        public GET(URL baseUrl, HashMap<String,String> headers, HashMap<String,String> params){
            super(baseUrl, headers);
            this.params = params;
        }

        @Override
        public URL getUrl() throws MalformedURLException {
            StringBuilder sb = new StringBuilder(baseUrl.toString());
            if(params != null && params.size() > 0)
                sb.append(createParamString());

            return new URL(sb.toString());
        }

        private String createParamString() {
            StringBuilder sb = new StringBuilder();
            if(params != null && params.size() > 0) {
                sb.append("?");
                //TODO: Need to encode the paramater values
                for (String param : params.keySet()) {
                    sb.append(param).append("=").append(params.get(param)).append("&");
                }
                sb.deleteCharAt(sb.length()-1);          
            }
            return sb.toString();
        }
    }

    public class Response {
        public int status;
        public String body;
        public long time;

        protected Response(int status, String body) {
            this.status = status;
            this.body = body;
        }
    }
}

Sample 6

package FrameworkWrapper;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ServletResponse extends HttpServlet
{

   public void doGet (HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
   {

      Enumeration keys;
      String key;
      String myName = "";
      keys = request.getParameterNames();
      while (keys.hasMoreElements())
      {
         key = (String) keys.nextElement();
         if (key.equalsIgnoreCase("myName")) myName = request.getParameter(key);
      }
      System.out.println("Name = ");
      if (myName == "") myName = "Hello";

      response.setContentType("text/html");
      response.setHeader("Pragma", "No-cache");
      response.setDateHeader("Expires", 0);
      response.setHeader("Cache-Control", "no-cache");

      PrintWriter out = response.getWriter();
      out.println("json object");
   
      out.flush();
     
   // ---------------- Note:One approach--------------------------
      //response.setContentType("application/json");
   // Get the printwriter object from response to write the required json object to the output stream    
  // PrintWriter out = response.getWriter();
   // Assuming your json object is **jsonObject**, perform the following, it will return your json object
   //out.print(jsonObject);
   //out.flush();
     
      // ---------------- Note:One approach--------------------------
     
//      JSONObject json      = new JSONObject();
//      JSONArray  addresses = new JSONArray();
//      JSONObject address;
//      try
//      {
//         int count = 15;
//
//         for (int i=0 ; i<count ; i++)
//         {
//             address = new JSONObject();
//             address.put("CustomerName"     , "Decepticons" + i);
//             address.put("AccountId"        , "1999" + i);
//             address.put("SiteId"           , "1888" + i);
//             address.put("Number"            , "7" + i);
//             address.put("Building"          , "StarScream Skyscraper" + i);
//             address.put("Street"            , "Devestator Avenue" + i);
//             address.put("City"              , "Megatron City" + i);
//             address.put("ZipCode"          , "ZZ00 XX1" + i);
//             address.put("Country"           , "CyberTron" + i);
//             addresses.add(address);
//         }
//         json.put("Addresses", addresses);
//      }
//      catch (JSONException jse)
//      {
//
//      }
//      response.setContentType("application/json");
//      response.getWriter().write(json.toString());
     
      // ---------------- Note:One approach--------------------------
     
//      /**
//       * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
//       */
//      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//
//          request.setCharacterEncoding("utf8");
//          response.setCharacterEncoding("utf8");
//          response.setContentType("application/json");
//          PrintWriter out = response.getWriter();
//          JSONObject jsonObj = (JSONObject) JSONValue.parse(request.getParameter("para"));
//          System.out.println(jsonObj.get("message"));        
//          JSONObject obj = new JSONObject();
//          obj.put("message", "hello from server");
//          out.print(obj);
//
//      }

   

   }
}

Sample 5

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import com.howtodoinjava.model.User;

public class PureJavaClient
{
    public static void main(String[] args)
    {
        try
        {
            URL url = new URL("http://localhost:8080/RESTfulDemoApplication/user-management/users/10");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/xml");

            if (conn.getResponseCode() != 200)
            {
                throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
            String apiOutput = br.readLine();
            System.out.println(apiOutput);
            conn.disconnect();
 // this part need to be repalce with json parser
            JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            User user = (User) jaxbUnmarshaller.unmarshal(new StringReader(apiOutput));

            System.out.println(user.getId());
            System.out.println(user.getFirstName());
            System.out.println(user.getLastName());
           
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

Sample 4

package FrameworkWrapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class NetClientPost {

// http://localhost:8080/RESTfulExample/json/product/post
public static void main(String[] args) {

 try {

URL url = new URL("http://localhost:8080/RESTfulExample/json/product/post");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");

String input = "{\"qty\":100,\"name\":\"iPad 4\"}";

OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();

if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}

BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));

String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}

conn.disconnect();

 } catch (MalformedURLException e) {

e.printStackTrace();

 } catch (IOException e) {

e.printStackTrace();

}

}

}

Sample 3

package FrameworkWrapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class NetClientGet {

// http://localhost:8080/RESTfulExample/json/product/get
public static void main(String[] args) {

 try {

URL url = new URL("http://localhost:8080/RESTfulExample/json/product/get");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");

if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}

BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));

String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}

conn.disconnect();

 } catch (MalformedURLException e) {

e.printStackTrace();

 } catch (IOException e) {

e.printStackTrace();

 }

}

}

Sample 2

package FrameworkWrapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class JavaNetURLRESTFulClientPost {

private static final String targetURL = "http://localhost:8080/JerseyJSONExample/rest/jsonServices/send";

public static void main(String[] args) {

try {

URL targetUrl = new URL(targetURL);

HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Content-Type", "application/json");

String input = "{\"id\":1,\"firstName\":\"Liam\",\"age\":22,\"lastName\":\"Marco\"}";

OutputStream outputStream = httpConnection.getOutputStream();
outputStream.write(input.getBytes());
outputStream.flush();

if (httpConnection.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ httpConnection.getResponseCode());
}

BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
(httpConnection.getInputStream())));

String output;
System.out.println("Output from Server:\n");
while ((output = responseBuffer.readLine()) != null) {
System.out.println(output);
}

httpConnection.disconnect();

 } catch (MalformedURLException e) {

e.printStackTrace();

 } catch (IOException e) {

e.printStackTrace();

}

}
}

Sample 1

package FrameworkWrapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class JavaNetURLRESTFulClientGet {

private static final String targetURL = "http://localhost:8080/JerseyJSONExample/rest/jsonServices/print";

public static void main(String[] args) {

 try {

URL restServiceURL = new URL(targetURL);

HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Accept", "application/json");

if (httpConnection.getResponseCode() != 200) {
throw new RuntimeException("HTTP GET Request Failed with Error code : "
+ httpConnection.getResponseCode());
}

BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
(httpConnection.getInputStream())));

String output;
System.out.println("Output from Server:  \n");

while ((output = responseBuffer.readLine()) != null) {
System.out.println(output);
}

httpConnection.disconnect();

 } catch (MalformedURLException e) {

e.printStackTrace();

 } catch (IOException e) {

e.printStackTrace();

 }

}
}

Tuning

Change one parameter at a time
Measure and reconfigure by levels: For the same reasons that you should only change one parameter at a time, tune one level of your system at a time. You can use the following list of levels within a system as a guide:

Hardware
Operating System
Application Server and Requester
Database Manager
SQL and XQuery Statements
Application Programs

Understand the problem before you upgrade your hardware: Even if it seems that additional storage or processor power could immediately improve performance, take the time to understand where your bottlenecks are.



For how one affects the other, let's assume that you have a slow CPU but lots of RAM. That means that you can store quite a few of those numbers in memory - about half a billion of them on a typical 32 bit machine. But processing/computation/etc on those numbers will be slower.

On the other hand if you have a fast CPU but a small amount of RAM, processing of the numbers will be fast, but from time to time the machine will need to drag them from disk (and put them back again to make room for more), which is many times slower than taking them from RAM.

A basic example might be an image editing program. I load up my 20MB jpeg, the program reads the entire image, and the OS keeps that in RAM for you (all working memory looks the same to the program, the OS decides if it goes to the page/swap file on disk or RAM). So the image is in RAM waiting to be processed, but I go for coffee before telling the program to apply so silly filter, so the CPU isn't doing anything. I come back, apply the filter to add some bubbles to the image, and the CPU goes to 100% and even more memory gets used because it keeps the preprocessed image in memory,


More RAM = you can run more apps concurrently

More CPU = you can run more complex calculations/operations


It's the same relationship as your brain have with a book. The faster brain = the faster your read, the bigger the book = the more pages it can contain.


No relationship. Think of it in terms of doing some heavy-duty number-crunching. RAM is how many of those numbers can be stored for faster retrieval, whereas CPU is how fast those numbers can have mathematical operations performed on them.

For how one affects the other, let's assume that you have a slow CPU but lots of RAM. That means that you can store quite a few of those numbers in memory - about half a billion of them on a typical 32 bit machine. But processing/computation/etc on those numbers will be slower.

On the other hand if you have a fast CPU but a small amount of RAM, processing of the numbers will be fast, but from time to time the machine will need to drag them from disk (and put them back again to make room for more), which is many times slower than taking them from RAM.

So really, each affects the other, and for best performance you need both to be good. However, this totally depends on what each application is actually doing, and there are other factors (such as disk speed, processor caches, etc) which we needn't go into too much detail about for now, but which you should be aware will complicate things.



If the program is disk-intensive, speed is proportional to the disk.
If the program is oriented towards calculations : speed is (mostly) proportional to the CPU, since the memory cache nowadays is pretty intelligent and fast.
Else speed is (mostly) proportional to memory.


The relationship between RAM and processor and why programs run faster is simply because with more RAM, more data to be processed can get to the processor faster.


I believe you are referring to IO operations for processing purposes, and I'll attempt to give a simplified layman answer.

Assume the processor is a meat-grinder in a factory, and assume RAM, hard disk are like the conveyor belt system feeding unprocessed meat to the grinder to be ground.

Assume the conveyor belt has two parts -> the slow-but-wide part, and the fast-but-narrow part. The former alludes to the hard disk big storage but slow speed, and the latter is referring to memory's small storage but high speed characteristics.

So...

HARD DISK CONVEYOR (WIDE BUT SLOW) -> RAM CONVEYOR (NARROW BUT FAST) -> GRINDER (PROCESSOR)

When your increase your RAM, it is like widening the RAM conveyor, thus the grinder can potentially receive much more at one go for processing.

If your RAM is low, it means that while the RAM conveyor is fast, it is extremely narrow, thus the volume of meat pouring into the grinder is little. At the same time, meat might potentially choke at the hard disk conveyor points (in short meat that is supposed to be on the RAM conveyor in a well-optimized system is actually still on the hard disk conveyor - a.k.a paging/swap file).

To sum an answer all up in a hopefully easy to understand sentence :

The relationship between RAM and processor and why programs run faster is simply because with more RAM, more data to be processed can get to the processor faster.

If the size of the system memory is equivalent to how wide the RAM conveyor is, then the Frontside Bus (FSB) is equivalent to how fast the RAM conveyor goes.

Whew! Hope this answers your question!


Split single application in several processes with non-shared memory (not a threads; but processes). First process can run DB and second can run other part of the project. You can use RMI or shared memory or sockets to communicate between processes.




\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
it sounds like your talking about having different methods within a single application run under different JVMs. This is not possible.

If you want to use different JVMs for different applications, you'll have to manually specify the path to the particular JRE when you start an app. Example:

$PATH_TO_FIRST_JVM/bin/java -jar application1.jar
$PATH_TO_DIFFERNT_JVM/bin/java -jar application2.jar


There are several insightful answers here, but something that interests me the driving requirement for running multiple JVMs. Why do you believe you need to do this? If you are looking for parallel processing, you might want to consider a multi-threaded application as opposed to running multiple JVMs. Since each JVM could very likely require significant resources and you'd like to have communication between paths of execution, this may very likely be a better solution for your needs.



Tuning Java virtual machines
jvm maximum size for 32 bit and 64 bit
Determine the type of JVM on which your application server is running.
Need help regarding multiple JVM in a single server///////////////////////////////////////////////////////


http://www.cacheonix.com/articles/How_to_Distribute_Java_Application_on_Multiple_JVMs.htm
http://stackoverflow.com/questions/8098158/re-architect-application-to-run-on-multiple-serversjvms-to-enhance-performance

http://hadoop.apache.org/////////////////////////////////for cluster one solution
http://stackoverflow.com/questions/8098158/re-architect-application-to-run-on-multiple-serversjvms-to-enhance-performance// same problem
http://www.coderanch.com/t/580009/Performance/java/multiple-JVM-single-server// same problem

// http://maintainj.com/userGuide.jsp?param=runtime//// important concept



http://www.ramkitech.com/2012/10/tomcat-clustering-series-simple-load.html

http://www.coderanch.com/t/234337/threads/java/performance-improves-multithreading///multithreading
http://scalibq.wordpress.com/2012/06/01/multi-core-and-multi-threading//////multithreading


Event Publishing captures changed-data events and publishes them as WebSphereR MQ messages that can be used by other applications to drive subsequent processing.
WebSphere
R
MQ message queues to target systems.

Coding to interface provides reusability and polymorphism.As far as class implements interface,the interface or abstract class can be passed to parameter instead of class that implements the interface.
public class Polymorphism{
void run();
Void Bark();
Energy getEnergy(Polymorphism test);
Public abstract class EnergySynthesis implements Polymorphism{
abstract void Energy();
Void Bark(){
 getEnergy(){

}
void run(){
getEnergy();

}public EnegyGeneartion extends EnergySynthesis  {
Energy getEnergy(Polymorphism test){
return new Energy( test);
}
MainClass{

EnegyGeneartion test=new EnegyGeneartion ();
test.getEnergy(test);
test.Bark()
.
.
.
.
.
//here in Energy getEnergy(Polymorphism test) any class can be passed as parameter that implemets interface (Polymorphism .


}