Jmock with reflection - java

I have a requirement where i need to mock the com.sun.deploy.security.DeployManifestChecker and return null when accessing printWarningsIfRequired in that class. Since Deploy.jar is not in my build path, i couldnt directly mock it up. I'm looking at a way to implement it using Java reflection API. but i'm not sure how to invoke the mock method with the Class argument.
method.invoke(null, new Class[]{claz1}); is failing with NP exception.
Here is the code
Mockery context ;
final Class<?> claz1;
try {
Class mclaz = Class.forName("org.jmock.Mockery");
context = (Mockery) mclaz.newInstance();
claz1 = Class.forName("com.sun.deploy.security.DeployManifestChecker");
final Method method = mclaz.getDeclaredMethod("mock",
new Class[]{Class.class} );
method.invoke(null, new Class[]{claz1});
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException 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 (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Your stated goal in to use reflection but if I had to do this i'd just create a test-only jar that includes an interface that mimics the com.sun.deploy.security.DeployManifestChecker class. Then use jmock to mock the stand-in.
I've taken this approach before when I couldn't include the actual class in my testing setup like you and it works like a champ. Just be sure that your stand-in doesn't make it to the runtime classpath and remains in test scope only.

Related

get user groups members using Google Directory API

I'm using the Google Directory API, here is the code that I'm using and I get the user info. But I need to get also the groups that the user is member.
My question is how can I do that when I have the user. I have another code to get the members, from a group but this impractical, because if I do that. I'll will need to get all the members for all the groups.
public static void get_user(String correo) {
Users us;
try {
service = getDirectoryService("admin#domain.mx");
try {
us = service.users().list().setCustomer("my_customer").setQuery("email:"+correo).execute();
System.out.println("us:"+us);
List<User> lu = us.getUsers();
System.out.println("lu:"+lu);
if (lu!=null) {
System.out.println("reses:"+lu.size());
for (int i=0;i<lu.size();i++) {
User u = lu.get(i);
String id = u.getId();
String pemail = u.getPrimaryEmail();
UserName username = u.getName();
System.out.println("xxxx.................");
System.out.println(i+":"+id);
System.out.println("username:"+username.getFullName());
System.out.println("full:"+username.getGivenName());
System.out.println("email:"+pemail);
System.out.println("organization unit:"+u.getOrgUnitPath());
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (GeneralSecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}

Why sendText calls throw timeout exception when using websockets?

I am new to websocket, and trying out with few examples. The application I created works fine for sometime say 10 - 15 mins, and from then on, it throws the timeout exception when sendText method is called on websocket session. I changed the value for "org.apache.tomcat.websocket.BLOCKING_SEND_TIMEOUT" to -1 and now it hangs.
could you please help me to resolve this issue.
The code I have written to send the data to websocket is as below:
public void update() {
Dashboard dashboardData = tunnelDataService.getDashboardData();
ObjectWriter ow = new ObjectMapper().writer();
String json = null;
try {
json = ow.writeValueAsString(dashboardData);
} catch (JsonGenerationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JsonMappingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
synchronized (lock) {
if (session.isOpen()) {
session.getBasicRemote().sendText(json);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am deploying this application on JBoss EAP 6.3.

Default Java exception handling code generated by Eclipse

The default exception handling code generated by Eclipse looks as follows:
try {
methodThrowsACheckedException();
} catch (SomeCheckedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Would it not be better if Eclipse generated the following code instead?
try {
methodThrowsACheckedException();
} catch (SomeCheckedException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
You can configure eclipse to do that its your choice. Check Code Template-> Catch Block Body in Preferences->Java->Code style

Program won't run because variables "may be uninitialized"?

I'm trying to make a new thread for parsing xml from an rss feed. When I click run it says there are errors please correct them etc. I have 2 classes in my project. The other class has no errors and this class below has only warnings that a lot of the things in the try/catch statements may be uninitialized. I understand that and figured I should still be able to run the program anyways, I expect them to be initialized and if they're not that's fine I want to know about it. Is this really what's going on or am I missing something? I thought it would compile if something may be uninitialized but its not certainly uninitialized.
public class RssParse extends Thread {
Thread th=new Thread() {
public void run(){
System.out.println("1");
URL iotd;
try {
iotd = new URL("http://www.nasa.gov/rss/image_of_the_day.rss");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("2");
BufferedReader in;
try {
in = new BufferedReader(new InputStreamReader(iotd.openStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("3");
XmlPullParserFactory factory;
try {
factory = XmlPullParserFactory.newInstance();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
factory.setNamespaceAware(true);
System.out.println("4");
XmlPullParser xpp;
try {
xpp = factory.newPullParser();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("5");
try {
xpp.setInput(in);
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("6");
int eventType;
try {
eventType = xpp.getEventType();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(eventType+"!!!!!!!!!!!!!!!!");
while(eventType!=XmlPullParser.END_DOCUMENT){
if(eventType==XmlPullParser.START_DOCUMENT){
System.out.println("start");
}
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//method
};//thread
}//class
Look at this try/catch block for example :
URL iotd;
try {
iotd = new URL("http://www.nasa.gov/rss/image_of_the_day.rss");
} catch (MalformedURLException e) {
e.printStackTrace();
}
If iotd = new URL("...") fails, iotd will remain uninitialized.
There are two ways to deal with this :
Assign a default value to iotd, like : URL iotd = null; However, it's bad here because if you use iotd later its value may be null and can throw a NullPointerException.
Stop the execution of your function if something failed instead of just printing the stack trace. For example you can add a return statement in the catch block :
URL iotd;
try {
iotd = new URL("http://www.nasa.gov/rss/image_of_the_day.rss");
} catch (MalformedURLException e) {
e.printStackTrace();
return;
}
All the warnings you are getting are because all your catch blocks are not dealing with the exception at all (just printing the stacktrace to standard out).
Let's see it through an example:
URL iotd;
try {
iotd = new URL("http://www.nasa.gov/rss/image_of_the_day.rss");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
at that snipped you are declaring a iotd variable as a URL but without initializing it (not assigning any value), you do it inside the try block - which isn't wrong by the way. However if for any reason the statement inside the try block throws an exception program flow will go to the catch block leaving the iotd variable with its initial value (unassigned).
So, in that case, execution of the program will continue and when reaching this statement:
in = new BufferedReader(new InputStreamReader(iotd.openStream()));
it will find no value assigned to the iotd variable.
To remove the warning regarding the uninitialized value you can either assign a null value to the variable when declaring it or rethrow another exception inside the catch block, stopping the program flow.
In the other hand, the snippet you posted here is not just one class, it's actually two as you are extending the Thread class and then creating an anonymous one inside its body. Using threads is easier than that in Java, just implement the Runnable interface and then instantiate a new thread from that interface:
public class MyRunnable implements Runnable {
public void run() {
// do stuff
}
}
and then:
new Thread(new MyRunnable()).start();
cheers
you need to initialize the variables above the try catch block, or give them a value in catch or finally block
find updated code here
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
public class RssParse extends Thread {
Thread th=new Thread() {
public void run(){
System.out.println("1");
URL iotd=null;
try {
iotd = new URL("http://www.nasa.gov/rss/image_of_the_day.rss");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("2");
BufferedReader in=null;
try {
in = new BufferedReader(new InputStreamReader(iotd.openStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("3");
XmlPullParserFactory factory=null;
try {
factory = XmlPullParserFactory.newInstance();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
factory.setNamespaceAware(true);
System.out.println("4");
XmlPullParser xpp=null;
try {
xpp = factory.newPullParser();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("5");
try {
xpp.setInput(in);
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("6");
int eventType=-1; // set to a default value of your choice
try {
eventType = xpp.getEventType();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(eventType+"!!!!!!!!!!!!!!!!");
while(eventType!=XmlPullParser.END_DOCUMENT){
if(eventType==XmlPullParser.START_DOCUMENT){
System.out.println("start");
}
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//method
};//thread
}//class

Is there a way to invoke reflected method of the class not having object of the class?

I'm trying to get access to sendRawPdu method of SMSDispatcher.
I'm able to get method, but I can't invoke it because I have to have instance of SMSDispatcher to call mSendRawPdu.invoke( /* ??? */ , pdus.encodedScAddress, pdus.encodedMessage, null, null );
Invoking the method from SmsManager works great, because I can get an object like this SmsManager sm = SmsManager.getDefault(); and pass it to .invoke
try {
#SuppressWarnings("rawtypes")
Class c = Class.forName("com.android.internal.telephony.SMSDispatcher");
Method[] ms = c.getDeclaredMethods();
// List all methods
for (int i = 0; i < ms.length; i++) {
Log.d("ListMethos",ms[i].toString());
}
// Get method "sendRawPdu"
byte[] bb = new byte[1];
Method mSendRawPdu = c.getDeclaredMethod("sendRawPdu",bb.getClass(),bb.getClass(), PendingIntent.class, PendingIntent.class);
Log.d("success","success getting sendRawPdu");
mSendRawPdu.setAccessible(true);
// How to invoke the method not having object of type SMSDispatcher?
mSendRawPdu.invoke( /* ??? */ , pdus.encodedScAddress, pdus.encodedMessage, null, null );
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException 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();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Does this task has a possible solution?
See the doc for Method#invoke(java.lang.Object, java.lang.Object...)
If the underlying method is an instance method, it is invoked using dynamic method lookup as documented in The Java Language Specification, Second Edition, section 15.12.4.4; in particular, overriding based on the runtime type of the target object will occur.
Throws:
NullPointerException - if the specified object is null and the method is an instance method.
So, basically if you pass a null to invoke an instance method then you receive a NPE. Which means it's not possible to invoke an instance method without an object. Which makes sense because why would you want to invoke an instance-method without an instance.
e.g.
class MyClass {
public void myMethod() {
System.out.println("Hello Java Reflection!!!");
}
}
Method theMethod = MyClass.class.getDeclaredMethod("myMethod");
System.out.println(theMethod);
theMethod.setAccessible(true);
theMethod.invoke(null);
It throws a NPE, but prints "Hello Java Reflection!!!" if I make the method static.
SMSDispatcher is an abstract class, so you can't get an instance of it.
public abstract class SMSDispatcher extends Handler {...}
Try to use others.

Categories