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

*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();
}
}

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

mouseClicked doesn't work while mouseMoved work

So I have a new project I work which I move in a room (panoramic picture). Now I want to open something on mouseClick. But when I try even to print something to the console in the mouseClick event it doesn't work.
package noam;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class room extends JPanel{
ImageIcon img;
int locationX=0,locationY=0;
int cp=0,cr=0,c=0;//cp clickpresed cr clickreleased c clicked
public room()
{
addMouseMotionListener(new MML());
//addMouseMotionListener(new ML());
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
img =new ImageIcon("VRpano.jpg");
Image s=img.getImage();
g.drawImage(s, locationX,locationY,img.getIconWidth(),img.getIconHeight(), null);
}
class MML extends MouseAdapter{
/*public void mousePressed(MouseEvent e) {
}*/
public void mouseMoved(MouseEvent e) {
if(e.getX()>1100){
if(locationX>-6350)
locationX-=20;
if(locationX<=-6350)
locationX=0;
repaint();
try {
Thread.sleep(20);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(e.getX()<200){
if(locationX<0)
locationX+=20;
if(locationX>=0)
locationX=-6300;
repaint();
try {
Thread.sleep(20);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
//System.out.println("x="+e.getX()+" y="+e.getY());
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseClicked(e);
System.out.println("click!");
c++;
System.out.println(c);
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
super.mousePressed(e);
System.out.println("Pressed!");
cp++;
System.out.println(cp);
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseReleased(e);
System.out.println("Released!");
cr++;
System.out.println(cr);
}
}
/*public class ML extends MouseAdapter{
public void MOUSE_ENTERED(MouseEvent me){
System.out.println("click!");
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}*/
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame f=new JFrame("Asteroids MS Ver 1 (c) 2014");
room bp=new room();
f.add(bp);
f.setSize(1650,1080);
f.setExtendedState(JFrame.MAXIMIZED_BOTH);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.setVisible(true);
}
}

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);

Jmeter Java Request

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.

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