guava-testlib future version JAR - java

Today, the current Guava version seems to be:
release is 13.0.1, August 3, 2012.
but I checked out the source off of:
git clone https://code.google.com/p/guava-libraries/
and got intrigued by what seems like an extremely useful testing tool to me:
http://code.google.com/p/guava-libraries/source/browse/guava-testlib/src/com/google/common/testing/NullPointerTester.java
I am trying to verify that all of my methods detest null just as much as Doug Lea ( http://gee.cs.oswego.edu/dl/html/vita.html ) seems to do, unless Joshua Bloch misquotes him ( http://www.youtube.com/watch?v=ZeO_J2OcHYM#t=26m35s ) in being "null-hostile".
Anyway, NullPointerTester.java seems to be just perfect so I am trying to build it into my project.
Following the dependencies (NullPointerTester -> Invokable<?, ?>, -> ... for example) is tedious as I run into classes that are #since 14.0, basically belong to a future version.
What's the best way to build a self-contained JAR of the next/future version of Guava, with all dependencies being taken care of for me? Note: the sources seem to be "all" on git...
You can stop reading here.
I can't wait to be doing stuff like this, which is really cool I think:
http://www.massapi.com/class/nu/NullPointerTester.html
Note: what's missing are "security checks", as in "if the constructor has been made private, check that I cannot reflect-invoke it anyway...
If I were a better coder I'd contribute, but this is all I can do and it's very poor, although the intent should be clear?
static boolean isDefaultConstructorDisabled(Class<?> type) {
boolean isDefaultConstructorDisabled = false;
Constructor<?>[] declaredConstructors = type.getDeclaredConstructors();
Constructor<?> defaultContructor = declaredConstructors[0];
defaultContructor.setAccessible(true);
try {
defaultContructor.newInstance();
} catch (InvocationTargetException invocationTargetException) {
Throwable cause = invocationTargetException.getCause();
if (cause instanceof UnsupportedOperationException
&& cause.getMessage().contains(
ErrorMessage.DefaultConstructor.DISABLED)) {
isDefaultConstructorDisabled = true;
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return isDefaultConstructorDisabled;
}

Did you try looking in Maven?
http://search.maven.org/#browse%7C-723200679
I think guava-testlib is what contains NullPointerTester. You could grab the 13.0.1 jar.
http://search.maven.org/#browse%7C1590928164

If you cloned the whole Guava repository, then the v13.0.1 tag will have guava-testlib, and specifically NullPointerTester, as of 13.0.1, which should work -- no?

Related

Google Guava getTopLevelClasses returns empty set

I've been searching around all over the internet to no avail. I am attempting to use Guava to get all the classes in a package of mine, but it is not behaving as intended. It always returns an empty set, making it impossible to do anything with the given results. Could there be a problem with System Variables, or some other road-block?
Here is some of my code.
String packageName = "me.travja.package";
ImmutableSet<ClassPath.ClassInfo> root = null;
try {
System.out.println(ClassPath.from(getClass().getClassLoader()));
root = ClassPath.from(getClass().getClassLoader()).getTopLevelClasses();//.getTopLevelClassesRecursive(packageName);
} catch (IOException e) {
e.printStackTrace();
}
for (ClassPath.ClassInfo info : root) {
System.out.println(info.getPackageName() + " -- " + info.getSimpleName());
}
It never hits the last sout because it's empty, but the one that prints the classpath prints 'com.google.common.reflect.ClassPath#33571c14' which isn't super useful. But to my knowledge, shouldn't that resemble more of my application's directory?
Thank you for your help with this. It's been bugging me for too long.
EDIT: I did some digging around. It seems that it works as intended if my file path doesn't contain a Space. I read a little that this used to be a problem with Guava in older versions, but I even tried using Maven and shading the latest version of Guava. Is there any way to fix this, or do I just have to be cautious that my file path never has a space in it?
After doing some more digging, one of the other dependencies that I was using had shaded an older version of Guava and that is what my code was using. As a result, it was broken. I used a decompiler so I could manually shade the ClassPath class from a newer Guava into my own code, and imported that. Works flawlessly now.

How to check if class exists somewhere in package?

I'm currently dealing with a particular issue with my paid application. Internally it contains a licensing check. The app is patched by hackers by modifying the app apk/jar. They are adding a new class which helps bypass the licensing check.
My goal is to somehow check for this particular patch. If I find it I know my app has been compromised.
Any tips on how to know that something has been modified on the package? Doing a hash over the app is not really an option in my case.
I thought maybe checking if this class exists would help, but what if they change the name of the class? Then, another idea is somehow check for unexpected includes added to the class.
Any of these possible? Any suggestions would help :)
Not sure about android but in standard JDK you would do something like this:
try {
Class.forName( "your.fqdn.class.name" );
} catch( ClassNotFoundException e ) {
//my class isn't there!
}
Here is what I used in Android - standard Java:
public boolean isClass(String className) {
try {
Class.forName(className);
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
Implementation example:
if (isClass("android.app.ActionBar")) {
Toast.makeText(getApplicationContext(), "YES", Toast.LENGTH_SHORT).show();
}
You can use
public static Class<?> forName (String className)
and check the ClassNotFoundException
http://developer.android.com/reference/java/lang/Class.html#forName%28java.lang.String%29
How does it get loaded if it's a random class in a random package?
That being said, see http://download.oracle.com/javase/6/docs/api/java/lang/System.html#getProperties%28%29 and java.class.path. For normal java apps, you have to walk the classpath and then search the entries (for jars) or directories (for .class files). But in a container-class-loader environment, this will fail to work (and I'm not sure how that applies to an android environment).

What happened to URIUtil.encodePath from commons-httpclient-3.1?

I want to do what's described in question 724043, namely encode the path components of a URI. The class recommended to do that is URIUtil from Commons HttpClient 3.1. Unfortunately, that class seems to have disappeared from the most recent version of HttpClient. A similarly named class from HttpClient 4.1, URIUtils, doesn't provide the same functionality. Has this class/method been moved to some other library that I'm not aware of or is it just gone? Am I best off just copying the class from the 3.1 release into my code or is there a simpler way?
The maintainers of the module have decreed that you should use the standard JDK URI class instead:
The reason URI and URIUtils got replaced with the standard Java URI was
very simple: there was no one willing to maintain those classes.
There is a number of utility methods that help work around various
issues with the java.net.URI implementation but otherwise the standard
JRE classes should be sufficient, should not they?
So, the easiest is to look at the source of encodePath from the 3.1 release and duplicate what it does in your own code (or just copy the method/class into your codebase).
Or you could go with the accepted answer on the question you referred to (but it seems you have to break the URL into parts first):
new URI(
"http",
"search.barnesandnoble.com",
"/booksearch/first book.pdf",
null).toString();
This can be achieved using org.apache.http.client.utils.URIBuilder utility in httpclient-4.X () as follows.
public static String encodePath(final String path) {
if(path.length() == 0)
return "";
else
return new URIBuilder().setPath(path).toString();
}
You can use Standard JDK functions, e.g.
public static String encodeURLPathComponent(String path) {
try {
return new URI(null, null, path, null).toASCIIString();
} catch (URISyntaxException e) {
// do some error handling
}
return "";
}

Testing if Quicktime and Java are installed?

In Javascript how can I test if the user has the quicktime plugin and java plugins installed?
For Java, you can use navigator.javaEnabled(). Or you can look here: http://www.pinlady.net/PluginDetect/JavaDetect.htm
For QuickTime, you can do:
var QtPlugin = navigator.plugins["Quicktime"];
if (QtPlugin) {//QuickTime is installed}
See here: http://javascript.internet.com/miscellaneous/check-plugins.html
This of course does not work in IE. The only way to check plugins in IE is using VB script, and it is very strange and messy. You can only test for specific plugin versions, for example, "quicktime" won't cut it. You have to specify the version, which is not published for versions older than 5, and I can't find a reference for version 7
The above examples haven't got the answer to the QuickTime part of your question, so here's what I'm writing right now even though the question has been closed and is a little old.
var p = navigator.plugins;
var qtcheck = 0;
for (i=0;i<p.length;i++) {
if (p[i].name.match(/QuickTime/) != null) {
qtcheck++
}
}
if (qtcheck > 0) { // do nothing, QuickTime is intalled }
else {
videos = document.querySelectorAll('object[type="video/quicktime"]')
// use .getElementById instead if there are multiple videos
// replace them with document.createElement('img')
For a more comprehensive and foolproof method i.e. without worry of a plug-in being renamed for whatever reason, you can check within the array of MimeTypes for type="video/quicktime" which is the ultimate answer of whether the object will be supported (or if you're not using the QT video, whatever else you're using it for instead).
This means creating a loop inside the loop through the plugins instead, but is a more firm verification than just a string match:
function checkQT() {
var p = navigator.plugins;
var QT = false; // assume you don't have it
for (i=0;i<p.length;i++) {
for (j=0;j<p[i].length;j++) {
if (p[i][j].type == "video/quicktime") {
QT = true;
return true;
}
else continue;
return false;
}
}
}
I searched around online and found a bunch of great IE fallback scripts here (not sure if this paste service code is going to persist so I gisted it for posterity), from which I took the QuickTime one:
function IEhasQT() {
if (!window.ActiveXObject) return false;
try { if(new ActiveXObject("QuickTime.QuickTime")) return true; }
catch (e) {}
try { if (new ActiveXObject('QuickTimeCheckObject.QuickTimeCheck')) return true; }
catch (e) {}
return false;
}
I tested some others and they just didn't work - catching the exceptions is important.
If you're doing what I'm doing (QuickTime fallback to a gif animation) you might want to take the attributes of the video to provide to the image (or whatever else you're using). The downside to this is that you have to couple it to an onscroll as well as onload (or use Jquery) as the browser is liable to try and find the element before the DOM has loaded no matter how you try and avoid it.
If anyone else reading this is looking for a similar answer, the code to do so is
function noQTfallback() {
var vid1 = document.getElementById("<insert your object id>");
var vid1gif = document.createElement('img');
vid1gif.setAttribute("src","<insert your URL source>");
vid1gif.setAttribute("style",vid1.getAttribute("style"));
document.getElementById("<...>").replaceChild(vid1gif, vid1);
}
function IEhasQT() {
// as above
}
function checkQT() {
// as above
}
function QTbackup(){
if (!checkQT() && !IEhasQT()) {
noQTfallback();
}
}
window.document.body.onload = QTbackup;
window.onscroll = QTbackup;
Oddly, you can have multiple versions of QuickTime installed, my Chrome browser on Windows has 7 copies... Luckily I have a Chromebook which doesn't have QT plug-in either installed or available, so I'm checking and seeing what works to distinguish it, this is the best I've come up with.
I never understood why testing was so important until looking at everyone's awful code on this online, incredible. I know no one cares about IE but basic things like || instead of && are just bad to leave lying around for other developers to reuse.
I've checked this on Windows, Linux and Android (IE and Chrome). The onscroll gives a bit of a jump but without Jquery or some other framework it's unavoidable I guess (and beats "plug-in not supported" !

What is the best way to detect whether an application is launched by Webstart

As it was made clear in my recent question, Swing applications need to explicitly call System.exit() when they are ran using the Sun Webstart launcher (at least as of Java SE 6).
I want to restrict this hack as much as possible and I am looking for a reliable way to detect whether the application is running under Webstart. Right now I am checking that the value of the system property "webstart.version" is not null, but I couldn't find any guarantees in the documentation that this property should be set by future versions/alternative implementations.
Are there any better ways (preferably ones that do not ceate a dependency on the the webstart API?)
When your code is launched via javaws, javaws.jar is loaded and the JNLP API classes that you don't want to depend on are available. Instead of testing for a system property that is not guaranteed to exist, you could instead see if a JNLP API class exists:
private boolean isRunningJavaWebStart() {
boolean hasJNLP = false;
try {
Class.forName("javax.jnlp.ServiceManager");
hasJNLP = true;
} catch (ClassNotFoundException ex) {
hasJNLP = false;
}
return hasJNLP;
}
This also avoids needing to include javaws.jar on your class path when compiling.
Alternatively you could switch to compiling with javaws.jar and catching NoClassDefFoundError instead:
private boolean isRunningJavaWebStart() {
try {
ServiceManager.getServiceNames();
return ds != null;
} catch (NoClassDefFoundError e) {
return false;
}
}
Using ServiceManager.lookup(String) and UnavailableServiceException is trouble because both are part of the JNLP API. The ServiceManager.getServiceNames() is not documented to throw. We are specifically calling this code to check for a NoClassDefFoundError.
Use the javax.jnlp.ServiceManager to retrieve a webstart service.
If it is availabe, you are running under Webstart.
See http://download.java.net/jdk7/docs/jre/api/javaws/jnlp/index.html
As you mentioned, checking the System property as follows is probably the cleanest way:
private boolean isRunningJavaWebStart() {
return System.getProperty("javawebstart.version", null) != null;
}
In a production system I have used the above technique for years.
You can also try to check to see if there are any properties that start with "jnlpx." but none of those are really "guaranteed" to be there either as far as I know.
An alternative could be to attempt to instantiate the DownloadService us suggested by Tom:
private boolean isRunningJavaWebStart() {
try {
DownloadService ds = (DownloadService) ServiceManager.lookup("javax.jnlp.DownloadService");
return ds != null;
} catch (UnavailableServiceException e) {
return false;
}
}
Of course that does have the downside of coupling your code to that API.
I have no real experience with Java web start other than looking at it a few years back.
How about start your application with a parameter that you define than you set when the app is started via Java web start.
If you want to pass in arguments to your app, you have to add them to the start-up file (aka JNLP descriptor) using or elements.
Then check to see if these properties are set.
Again this is a suggestion I have not coded for JWS and it may not be this easy.
You can check whether the current classloader is an instance of com.sun.jnlp.JNLPClassLoader (Java plugin 1) or sun.plugin2.applet.JNLP2ClassLoader (Java plugin 2). Despite the "applet" package, an applet using JNLP with the Java plugin 2 uses another classloader, sun.plugin2.applet.Applet2ClassLoader. It works with OpenJDK too.

Categories