New value added to Java Enum not available during debug - java

I am having the following problem:
I have an Enum that was originally declared with 5 elements.
public enum GraphFormat {
DOT,
GML,
PUML,
JSON,
NEO4J,
TEXT {
#Override
public String getFileExtension() {
return ".txt";
}
};
Now I need to add an additional element to it (NEO4J). When I run my code or try to debug it I am getting an exception because the value can't be found in the enum.
I am using IntelliJ as my IDE, and have cleaned the cache, force a rebuild, etc.. and nothing happens. When I look at the .class file created on my target folder, it also has the new element.
Any ideas on what could be causing this issue ?

I found my problem and want to share here what was causing it. My code was actually for a Maven plug-in which I was pointing to another project of mine to run it as a goal. However the pom.xml of my target test project was pointing to the original version of the plug-in instead of the one I am working on, and that version of course is outdated and does not include the new value. Thank you.

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.

Eclipse flags (working) code as compilation error and will not run

I have some fairly complex code that uses Javaslang. If I compile it into a jar, it runs fine. However, when I try to step into it in Eclipse for debugging, Eclipse flags it as a compilation error and dies when it reaches that line. The particularly weird part is that this worked a week ago, and the code has not changed in the interim.
Things I have tried:
clean project (including unchecking 'build automatically')
delete project from Eclipse, delete .project and .settings, re-import
from scratch
delete project from Eclipse, delete .project, .classpath, .settings, do mvn eclipse:eclipse, reimport
Maven builds this without errors [both within Eclipse and from the command line]. I can run the project this depends on and have it access this code from the JAR, so I know it works. I just cannot have Eclipse access the code from the project, either in 'run' or 'debug' mode.
Seq<Tuple2<StateProbabilityVector, ScenData>> resultStateProbs =
futures.
flatMap(Future::get).
toList();
// Update the target counts.
// THIS ENTIRE STATEMENT IS THE ERROR
Seq<Tuple2<ScenState, Probability>> result =
resultStateProbs.flatMap(tuple -> tuple.apply((spv, baTargetCount) ->
{
return spv.getStateProbList().
peek(sp -> logger.debug("Checking if {} > {}: {}",
sp.getProbability(),
intermediateMinProb,
sp.getProbability().greaterThan(intermediateMinProb))).
filter(sp -> sp.getProbability().greaterThan(intermediateMinProb)).
map(sp -> updateScenarioData(sp, baTargetCount, dupStateInfo));
}));
// signature for updateScenarioData
protected abstract Tuple2<ScenState, Probability> updateScenarioData(StateProbability stateProb,
ScenData scenData,
DSI dupStateInfo);
// truncated def of StateProbabilityVector
#Getter #ToString #Builder
public class StateProbabilityVector {
#NonNull
private final Seq<StateProbability> stateProbList;
}
So the types are all correct, but Eclipse claims:
> Type mismatch: cannot convert from Object to Iterable<? extends
> Object>
> Type mismatch: cannot convert from Seq<Object> to
> Seq<Tuple2<ScenState,Probability>>
As Nándor comments, this is probably down to a difference between the Eclipse compiler and javac, and the problem can probably be solved with a type witness in the right place. To find the right place, I would start by breaking up the functional method chain and extracting some local variables:
Seq<Tuple2<ScenState, Probability>> result =
resultStateProbs.flatMap(tuple -> {
Seq<Tuple2<ScenState, Probability>> filteredAndUpdated =
tuple.apply((spv, baTargetCount) -> {
Seq<StateProbability> stateProbList = spv.getStateProbList();
stateProbList.peek(sp -> {
logger.debug("Checking if {} > {}: {}", sp.getProbability(), intermediateMinProb, sp.getProbability().greaterThan(intermediateMinProb));
});
Seq<StateProbability> filtered = stateProbList.filter(sp ->
sp.getProbability().greaterThan(intermediateMinProb));
Seq<Tuple2<ScenState, Probability>> updated = filtered.map(sp ->
updateScenarioData(sp, baTargetCount, dupStateInfo));
return updated;
});
return filteredAndUpdated;
});
If you use Eclipse's extract variable refactoring, that by itself may tell you where it's inferring the wrong types, and explicitly declaring the correct types of the local variables might be enough to fix the problem all by itself.
If not, it should at least narrow the error down, and show you exactly where in the call chain Eclipse is having trouble. You can then probably fix it with type witnesses or, if all else fails, explicit casts, and then (with that type information added) perhaps inline the variables again, although this code is dense enough that I might leave them in.
Side notes:
peek() will only only debug the first StateProbability -- is that your intent?
consider adding a greaterThan() method to StateProbability so you don't have to repeatedly call getProbability().greaterThan(). (If the answer to #1 is "no", this method would also be a good place to put the debug statement.)
consider adding a method on SceneState that would return a prefiltered list, like Seq<StateProbability> SceneState.allGreaterThan(Probability).

Eclipse RCP: InternalPlatform.getDefault().getUserLocation() doesen't return C:\Users\username\AppData\Roaming

I am currently migrating an Eclipse 3.0 application to 4.4. The user data was and still should be stored in the folder C:\Users\username\AppData\Roaming\applicationname
The application is using following code to read the directory:
public static String getUserDirectory()
{
String directory = InternalPlatform.getDefault().getUserLocation().getFile();
return directory;
}
I know the code is deprecated, but following code returns the same:
public static String getUserDirectory()
{
String directory = Platform.getUserLocation().getURL().getFile();
return directory;
}
They both return C:\Users\username\user but as I said the user data should be stored at C:\Users\username\AppData\Roaming\applicationname. Did the behaviour of those methods change?
How can I realize that I store my user data under C:\Users\username\AppData\Roaming\applicationname and my application can still find the directory?
I know this has to do something with environment-variables which I don't fully understand.
I don't have a 3.x target platform at hand to compare but C:\Users\username\user looks plain wrong.
If you are interested in the details, the constructor of EquinoxLocations computes the userLocation and adds the literal 'user' the the user's home directory if no default is specified.
Hence, if you start your application with -user #user.home or -Dosgi.user.area=#user.home, the user location will be set to C:\Users\username\. Still not what you are looking for, but at least a sane value.
I think this is a bug in Equinox and recommend to file a bugzilla. If it turns out that there is a good reason for this appraoch the bug entry will still serve as documentation/reasoning.
In the meanwhile you could obtain the home directory on Windows through System.getenv( "APPDATA" ). According to this post it will return the roaming home directory.
I solved the problem by adding three properties in the Configuration tab of my config.ini.product-file:
osgi.configuration.area =
#user.home/AppData/Roaming/ApplicationName/...
osgi.user.area =
#user.home/AppData/Roaming/ApplicationName/...
osgi.instance.area =
#user.home/AppData/Roaming/ApplicationName
Now my method as stated in my question reads the paths that are configured by those properties and the config.ini file which is generated looks exactly like the one of the old build with Eclipse 3.0.

Error debugging CGLIB FastClass on eclipse

I'm trying to debug an java eclipse project with some problem!
I'm starting using CGLIB to make faster reflection calls using the index metod.
example
FastClass fastClass = FastClass.create(getClass());
int index = fastClass.getIndex("methodName", new Class[] { Object.class });
fastClass.invoke(index, this, new Object[] { obj } );
now when i try to put a breakpoint into a class that is called by fastreflection method this is the eclipse output.
I try to change compiler option on generate line number with no results.
I also upload an eclipse project (built with Juno version) that replicates the problem!!
http://www.filefactory.com/file/4zryz3gjgbyh/n/FastDebug.rar
Thanks!
I "resolved"(understand) the problem, but it is not a problem with Eclipse. When you launch
the program this line: FastClass.create(ReflectionTarget.class); ends up
creating an entirely new version of the compiled class removing all
non-essential stuff from the classfile to make it "fast" - that includes all
the line number / debug infos, which means the breakpoint cannot be set in it.
http://cglib.sourceforge.net/xref/net/sf/cglib/core/package-summary.html
There's no javadoc and you need to read the source but now i understand this is not a
problem but a feature of this method to make fast reflection!

How does Java generate signatures for Methods?

I have an Java class with a static final method getAll:
public static final Vector<Category> getAll(Context context, ContentValues where) {
ArrayList<Integer> IDs = null;
if(where != null && where.containsKey(DatabaseAdapter.KEY_PRODUCT)) {
IDs = OvertureItem.getAll(context, DatabaseAdapter.TABLE_PRODUCT_CATEGORY, new String[] { DatabaseAdapter.KEY_CATEGORY }, where);
} else {
IDs = OvertureItem.getAll(context, DatabaseAdapter.TABLE_CATEGORIES, where);
}
Vector<Category> categories = new Vector<Category>();
for(Integer id: IDs) {
categories.add(Category.get(context, id));
}
return categories;
}
Now I want to hand in null as a value for the where statemant so that it will just be ignored later on in the code. Anyway in the testcase for this method I have:
Vector<Category> categories = Category.getAll(context, null);
Which then in turn gives me a NoSuchMethodError. I don't know exactly why it does that. The only thing I could imagine is that the null I hand in would not match the signature of the above method. But how can I overcome this? I already thought of overloading. But this would just end in rewriting most of the code. At least when I do it, how I think.
Any suggestions on that?
Phil
P.S. This is the stack trace I get:
java.lang.NoSuchMethodError: com.sap.catalogue.model.Category.getAll
at com.sap.overture.test.model.CategoryTest.testGetAll(CategoryTest.java:59)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:430)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)
If the method did not exist at compile-time, then the code would not compile.
If you get NoSuchMethodError at run-time, then this suggests that the version of the Category class you are running against is different than the version of the Category class you are compiling against.
What is your setup like - is this class in the same project? Are you copying in JARs from another project?
The real answer
So I now finally figured it out and it wasn't as obvious as I expected. I started wondering, when every new test case for any new method I wrote would give me the NoSuchMethodError. So I digged a little bit deeper and then, suddenly it came to my mind: "I changed the package name of the android application". I thought this would not make any difference to the test project as long as I kept the properties right in the AndroidManifest.xml but I was wrong!
In fact when your application package is named com.foo.bar.app, the package for your tests has to be named com.foo.bar.app.test! What happened was, that with my old configuration somehow the classes that sat in the bin/ folder were used. I thought, that they should have been deleted when I cleaned the project but they weren't. This way all of the older test cases would still pass and only the new ones would give me the NoSuchMethodError. After I deleted the bin/ folder manually I got a whole bunch of errors. I then renamed the package holding the test cases and did a full clean/ rebuild on the project et voilá everything is back to normal again.
Thanks for all the tips! I really appreciate your help that just kept me digging to the bottom of the problem. Hope this here will help anybody with the same problem in the future.
Phil

Categories