Jmeter Java Request - jmeter

I have a java Request in Jmeter for which I wrote the code extending AbstractJavaSamplerClient and Implemented overridden method
I am hitting and could see the response in the log of remote machine
But I cannot see the response in view Results tree and save responses to file in jmeter
Below is the runtest code snippet,please let me know on how can I capture java request response in Jmeter
public SampleResult runTest(JavaSamplerContext context) {
System.out.println("run Test method actual method is called here..");
XCardService xcardService = null;
String urlString = context.getParameter( "rubyURL" );
SampleResult result = new SampleResult();
boolean success = true;
result.sampleStart();
//try with Junit
String[] rubyURL = new String[1];
rubyURL[0] = urlString;
try {
System.out.println("RubyUrl::"+rubyURL);
xcardService = XCardFactory.getService(rubyURL, 165, appPassword, 5000);
} catch (AuthenticationFailureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IncompatibleVersionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceInitFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XCardTimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DiagnosticContext dc = new ServerDiagnosticContext("Junit TestCase");
try {
System.out.println("xcardService::"+xcardService);
AccountInfo account = xcardService.getAccountInfo(dc, 1089765);
System.out.println("getAccount Info ::"+account.toString());
} catch (InvalidArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientNotAuthenticatedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XCardTimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XCardException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result.sampleEnd();
result.setSuccessful(success);
System.out.println("Response Message:::"+result.getResponseMessage());
return result;
}

A good example of an implementation of AbstractJavaSamplerClient is org.apache.jmeter.protocol.java.test.SleepTest.
http://www.javadocexamples.com/java_source/org/apache/jmeter/protocol/java/test/SleepTest.java.html
As a general rule i would put the result.sampleEnd(); in a finally block.

Related

Java CompletableFuture - main class not terminated

I am trying to implment CompletableFuture which invokes a dummy callback method when completed.
However, after adding CompletableFuture.get() method my main class doesn't terminate.
I tried replacing CompletableFuture.get() with Thread.sleep(5000) but it doesn't seem to be right approach.
Please suggest what is causing CompletableFuture.get() to keep blocking even if the thread is complete.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.IntStream;
public class CallableAsyncWithCallBack {
public static void main(String[] args) throws InterruptedException {
CompletableFuture<String> compFuture=new CompletableFuture<String>();
compFuture.supplyAsync(()->{
//Compute total
long count=IntStream.range(Integer.MIN_VALUE, Integer.MAX_VALUE).count();
return ""+count;
}).thenApply(retVal->{
try {
return new CallBackAsynchClass(retVal).toString();
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
);
System.out.println("Main Thread 1");
try {
compFuture.get();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("Lock cleared");
}
}
class CallBackAsynchClass
{
String returnVal="";
public CallBackAsynchClass(String ret) throws InterruptedException, ExecutionException {
System.out.println("Callback invoked:"+ret);
returnVal=ret;
}
#Override
public String toString() {
return "CallBackAsynchClass [returnVal=" + returnVal + "]";
}
}
I am expecting "Lock cleared" to be outputted but .get() seems to be holding up the lock.
.thenApply function returns a new instance of CompletableFuture, and it's this instance that you need to use, try using this way instead :
public class CallableAsyncWithCallBack {
public static void main(String[] args) throws InterruptedException {
CompletableFuture<String> compFuture = CompletableFuture.supplyAsync(() -> {
//Compute total
long count = IntStream.range(Integer.MIN_VALUE, Integer.MAX_VALUE).count();
return "" + count;
});
CompletableFuture<String> future = compFuture.thenApply(retVal -> {
try {
return new CallBackAsynchClass(retVal).toString();
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ""; });
System.out.println("Main Thread 1");
try {
future.get();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("Lock cleared");
}
}
Hope this helps

How to stop a Spring-boot batch job from command line?

I was able to successfully launch a springboot-batch job through command line using CommandLineRunner.
Code :
#Component
public class CommandLineAppStartupRunner implements CommandLineRunner {
#Autowired
ApplicationContext context;
#Override
public void run(String...args) throws Exception {
JobLauncher jobLauncher = context.getBean(JobLauncher.class);
Job myJob = context.getBean(args[0], Job.class);
JobParameters jobParameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis()).toJobParameters();
try {
jobLauncher.run(myJob, jobParameters);
} catch (JobExecutionAlreadyRunningException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JobRestartException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JobInstanceAlreadyCompleteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JobParametersInvalidException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Job is successfully started and running using this command
java -jar <jarName> <jobName>
So far so good, But is there any option to stop this batch using command line?
Spring batch by default supports option to stop the job via arg, check out the documentation below:
https://docs.spring.io/spring-batch/trunk/apidocs/org/springframework/batch/core/launch/support/CommandLineJobRunner.html
jobPath <options> jobIdentifier (jobParameters)*
The command line options are as follows
jobPath: the xml application context containing a Job
-stop: (optional) to stop a running execution
jobIdentifier: the name of the job or the id of a job execution (for -stop, -abandon or -restart).
jobParameters: 0 to many parameters that will be used to launch a job specified in the form of key=value pairs.
Both JobExplorer and JobOperator came in handy for me.
Finally got the desired working.
#Component
public class CommandLineAppStartupRunner implements CommandLineRunner {
#Autowired
ApplicationContext context;
#Autowired
JobExplorer jobExplorer;
#Autowired
JobOperator jobOperator;
#Override
public void run(String...args) throws Exception {
if (args!=null&&args.length<2){
System.out.println("################Jar requires two or more command line args.###########");
return;
}
//Stopping Job
if(args[0].equals("stop")){
Set<JobExecution> jobExecutionsSet= jobExplorer.findRunningJobExecutions(args[1]);
for (JobExecution jobExecution:jobExecutionsSet) {
System.out.println(jobExecution.getStatus()+"ID :"+jobExecution.getId());
if (jobExecution.getStatus()== BatchStatus.STARTED|| jobExecution.getStatus()== BatchStatus.STARTING){
jobOperator.stop(jobExecution.getId());
System.out.println("###########Stopped#########");
}
}
System.out.println("EXITING JOB");
return;
}
else if(args[0].equals("start")){
JobLauncher jobLauncher = context.getBean(JobLauncher.class);
Job establishmentJob = context.getBean(args[1], Job.class);
JobParameters jobParameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis()).toJobParameters();
try {
jobLauncher.run(establishmentJob, jobParameters);
} catch (JobExecutionAlreadyRunningException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JobRestartException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JobInstanceAlreadyCompleteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JobParametersInvalidException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
To start the job, use the command like this
java -jar <jarName> start <jobName>
And to stop
java -jar <jarName> stop <jobName>

get parameters in servlet always shows "null" when an ajax call is made .

enter code here
Javascript
$(document).ready(function(){
var link="http://feeds.feedburner.com/techcrunch/startups";
$.ajax({
type:"GET",
url: "/FeedAction",
data:"links="+link,
success:function(data){
alert(data);
},
error : function(errorData){
alert("Some error occurred while processing the request");
}
});
});
Below is the servlet where i'm trying to getparameters("links") which throws null all the time ,i'm trying to get the parameters from the "links" and set it in where clause to generate data from database .
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url=request.getParameter("links");
System.out.println(url);
List<DataVO> users=new ArrayList<DataVO>();
Connection connection = null;
ResultSet resultset = null;
PreparedStatement preparedstatement=null;
try {
connection=ConnectionManager.getConnection();
preparedstatement=connection.prepareStatement("select description,date,link from post where feedlink in('"+url+"')");
resultset=preparedstatement.executeQuery();
while(resultset.next()){
DataVO user=new DataVO();
user.setDescription(resultset.getString("description"));
user.setDate(resultset.getString("date"));
user.setLink(resultset.getString("link"));
users.add(user);
}
} catch (SQLException e) {
try {
connection.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
preparedstatement.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
resultset.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// TODO Auto-generated catch block
}
request.setAttribute("feed", users);
request.getRequestDispatcher("FeedAction.jsp").forward(request, response);

Locale.getDefault(Locale.Category.FORMAT) using reflection in java

*import java.util.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.*;
public class LocaleProgram {
public static void main(String[] args) {
try {
Class c = Class.forName("java.util.Locale");
Class c1 = Class.forName("java.util.Locale$Category");
Class[] paramTypes = { c1 };
try {
Method m = c.getMethod("getDefault", paramTypes);
try {
//Object o = m.invoke(c1);
Object o = m.invoke(c1,new Object[]{"FORMAT"});
System.out.println("Object:" + (Locale)o);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}*
Basically I want Locale.getDefault(Locale.Category.FORMAT) using reflection, so that I can run this code on other than Java version 7.But I am trouble with calling invoke method, it's giving me java.lang.IllegalArgumentException: argument type mismatch exception.
Many thanks in advance
Change this line
Object o = m.invoke(c1,new Object[]{"FORMAT"});
to
Object o = m.invoke(c1,new Object[]{Locale.Category.FORMAT});
However, this may not be what you want, as you want to create the used enum by using reflection?
This will not work under Java 1.6 as these enums didn't exist yet.
Some handy stuff to read: http://blog.ej-technologies.com/2011/12/default-locale-changes-in-java-7.html
As Timmos stated the IllegalArgumentException results from the fact that you pass a String instead of a Locale.Category enum constant. The correct way to get the Locale.Category.FORMAT is by using java.lang.reflect.Field class:
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Locale;
public class GetDefaultLocale {
public static void main(String[] args){
Locale locale = null;
try {
Class<?> LOCALE_CATEGORY_Class = Class.forName("java.util.Locale$Category");
Class<?> LOCALE_Class = Class.forName("java.util.Locale");
Class<?>[] paramTypes = { LOCALE_CATEGORY_Class };
Method m = LOCALE_Class.getMethod("getDefault", paramTypes);
Field FORMAT_Field = LOCALE_CATEGORY_Class.getField("FORMAT");
//we pass null because the FORMAT is an enumeration constant(the same applies for class variables)
Object FORMAT = FORMAT_Field.get(null);
locale = (Locale)m.invoke(LOCALE_CATEGORY_Class, new Object[]{FORMAT});
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//for jre 6
if(locale == null){
locale = Locale.getDefault();
}
}

Mac lion can't connect to Socket when use Android emulator

When I use Windows to run eclipse Android emulator to connect socket,it was successful.
However, when I use Mac os lion to run the "Same" code ,the emulator shows"unfortunately
client test was stop!!"please help me solve this.And I already add the permission to internet!
package com.example.testclientokok;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
Socket socket=new Socket(InetAddress.getLocalHost(), 8888);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
server part
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
public static void main(String[] args){
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(8888);
System.out.println("Listening :8888");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true){
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
dataOutputStream.writeUTF("Hello!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if( socket!= null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataInputStream!= null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataOutputStream!= null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
If I understand correctly, you are executing MyServer on your machine, where you also run the emulator. If the Activity running in the emulator wants to establish a connection with MyServer, then it should use the following IP address : 10.0.2.2 (and not localhost, which references the emualor loopback interface).
See http://developer.android.com/tools/devices/emulator.html#networkaddresses

Resources