java.lang.NoSuchFieldError exception while the field is defined - eclipse

I'm working on a web application for Apache Tomcat.
I'm using a class called Location in which i defined a field called ipAddresses. Here it is:
package com.maxmind.geoip;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
public class Location {
private final static double EARTH_DIAMETER = 2 * 6378.2;
private final static double PI = 3.14159265;
private final static double RAD_CONVERT = PI / 180;
public Set<String> ipAddresses;
public String countryCode;
public String countryName;
public String region;
public String city;
public String postalCode;
public float latitude;
public float longitude;
public int dma_code;
public int area_code;
public int metro_code;
public Location() {
ipAddresses = new HashSet<String>();
}
...
}
However, after deploying the webapp to the server (war file) and trying to run the servlet that is using this class in it, i'm getting the exception java.lang.NoSuchFieldError for ipAddresses.
Moreover, when trying to debug it (Eclipse), when i reach a place where Location loc = new Location() is called, two weird things happen:
The constructor i coded isn't called, the debugger won't step into it, instead the program counter arrow is shown on on of the imports of in the Location.java file.
After "returning" from the Location loc = new Location() call, when i'm viewing the object's content the field actually does not exist.
The source file that was deployed with the jar file does include this field.
I have tried many things:
cleaning and building the project and redeploying it.
cleaning the server's working directory, both manual and by using Eclipse.
changing the working directory of the server, in Eclipse.
re-installing the server in Eclipse.
re-installing Tomcat entirely, three times and to different locations!
I'm pretty stuck. What could it be?

The symptoms indicate that you have the com.maxmind.geoip.Location class in some JAR in the JRE/lib or JRE/lib/ext or any other Eclipse/Tomcat-independent classpath location which will always have precedence in classloading over the WAR's classes.
Examining the loc.getClass().getProtectionDomain().getCodeSource().getLocation() after you construct it should give insights about where it is actually been loaded from.

Are you using the field at all? Are there any references to it?. It is entirely possible that Eclipse is optimising it away.
In Windows->Preferences->Java->Compiler, there is a setting: Preserve unused (never read) local variables. Is this checked? If not, check it and try again.

Related

Eclipse RCP persistence framework integration

I am developing an Eclipse application, using the latest version of Eclipse RCP and RAP 2022-12.
I have a target platform, a product file, a complete Maven/Tycho build system working with unit and integration test.
My need now is to persist to a DB (my preference here is MongoDB) a simple POJO class, for example:
/**
* The logged user.
*/
public class User implements IMASUser {
/**
* Developer user name
*/
public static final String DEVELOPER_USER_NAME = "developer"; //$NON-NLS-1$
private static final SimpleDateFormat DB_DATE_FORMAT = new SimpleDateFormat(CommonConstants.DB_DATE_FORMAT_PATTERN);
private int m_id;
private String m_username;
private String m_password;
private String m_name;
private String m_surname;
private String m_domainID;
private String m_office;
private String m_blockCode;
private String m_eMail;
private AccessLevel m_accessLevel;
private boolean m_isBeta; // Access to beta program
private boolean m_isActive; // Currently working (hired and actively developing)
private Date m_loginDate;
private Date m_lastLoginDate;
......
What is the most "common" and easy way to integrate a persistence framework into an Eclipse RCP application?
In a standard Java app I would try Hibernate or Spring Boot but here the integration in the OSGi environment is somehow problematic.
I tried to integrate:
Spring Boot JPA
Hibernate
Eclipselink
adding the dependencies to the target platform.
All of those have problems runtime discovering the needed service and classes.
For sure I'm missing some experience in Eclipse/RCP/OSGi.
Can you share some of your experience (if any), I can't find any up to date documentation.
Thank you!

'xxx' cannot be resolved (String, Scanner etc.) after importing files

I took a backup of my workspace. Meanwhile I created another workspace in my pc after formatting for temprory purposes. So now I've imported everything from my hard disk to my pc from File -> Import. However nothing seems to be 'resolved'. Heres an example of the code:
package com.sarthak.main;
import java.util.Scanner;
public class Myfirstgame {
public static void main(String[] args) {
System.out.println("Welcome to Momo Land, a place full of horror and utter momoness ");
System.out.println("Enter Your Name: ");
Scanner input = new Scanner(System.in);
String name=input.nextLine();
MyGame game=new MyGame(name);
game.run();
}
}
Things like System.out.println , input game.run etc. can't be resolved for some reason.
Check if your Java libraries are referenced in the properties of your project. In most cases, it is the referencing problem when importing projects.
Create a new project and then just copy the code inside the files..This may solve your problem.

GWT Bean validation does not return all constraint violations in compiled mode

I am experiencing different behavior for client side bean validation when running in gwt development mode than in compiled mode. I have been trying to debug and resolve this issue for hours (days actually) but, although further still did not find the root cause and am currently stuck. Hence my request for help.
In general I have been following the approach advocated here http://www.gwtproject.org/doc/latest/DevGuideValidation.html
and was further more inspired by various articles and questions on StackOverlow. So I have the user enter an object on the client. Than I validate it client side via a call to the validator that has been created by the validator factory.
The problem I am experiencing is that when more than one constraint is validated (i.e. the user enters 2 or more "mistakes") the validator does not (always) return all constraint violations when running in compiled mode, while it does return them all when running in gwt development mode.
The object I try to validate is of the class EnvyMonUser
#Entity
public class EnvyMonUser implements Serializable, Obj<EnvyMonUser> {
private static final long serialVersionUID = 3L;
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
#Id
private Long id;
#NotNull(message = "company must be selected")
#Index
private Key<Company> companyKey;
#Index
private String googleUserId;
#NotNull(message = "email address must be set")
#Pattern(regexp = EMAIL_PATTERN, message = "invalid email address")
#Index
private String email;
#NotNull(message = "name must be set")
#Size(min = 3, message = "must have a name of minimal 3 characters")
#Index
private String nickName;
#NotNull(message = "location must be selected")
#Index
private Key<SampleLocation> sampleLocationKey;
#NotNull(message = "result must be set")
#Index
private Long value;
...
Where Company and SampleLocation are two other classes. (The annotations #Entity, #Index, #Id and the class Key are of Objectify. I use the same entity class(es) client and server (gae) side. )
Once the user has entered an EnvyMonUser object I validate it via a validator, i.e.
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
...
EnvyMonUser obj = getView().getEditorDriver().flush();
Set<ConstraintViolation<O>> validate = validator.validate(obj);
where my validation factory is
public final class AppValidatorFactory extends AbstractGwtValidatorFactory {
#GwtValidation(value = { MonitorType.class, Measurement.class,
ProgramMeasurement.class, EnvyMonUser.class, Company.class,
SampleLocation.class })
public interface GwtValidator extends Validator {
}
#Override
public AbstractGwtValidator createValidator() {
return GWT.create(GwtValidator.class);
}
}
Am I doing something wrong?
Desperate as I was I tried removing and adding several fields but have not found any logical pattern. Depending on which fields I leave out and also on which of the fields are filled correctly by the user the (missing) constraint(s) in compiled mode change.
I have already tried multiple routes but no success so far. For example at some point I thought this was caused by using objectify. However when I remove sampleLocationKey member it works perfectly fine for companyKey member. I also tried removing the objectify attributes but this also doesn't seem to make a difference.
An interesting thing I did observe (by accident) is that when I remove (comment) some of the members from the hashCode and equals methods the behavior changes. Not sure why this is. Maybe it has something to do with how the validator generator is implemented.
Does anyone have any clue?
Also a pointer in the right direction is appreciated. Does someone for example know where I can find the validator that is generated. Or the sources of the validator generator?
Some versions of libraries I use:
gwt 2.6.0
hibernate-validator-4.1.0.Final.jar
hibernate-validator-4.1.0.Final-sources.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.6.1.jar
log4j-1.2.16.jar
objectify 4.0.1
Turns out the problem was not in my code but a bug in gwt sources for com.google.gwt.validation.client.impl.ConstraintViolationImpl . See https://groups.google.com/forum/#!topic/Google-Web-Toolkit/xRVGnMWfttc for a full description of the problem and solution.
I had the same issue. The validations were working fine on dev mode and all the error messages were showing up on the UI but in the prod mode we could see only one error message at one time. Late on when debugged and found that my DTO has implemented equals and hashcode method and that what causing this issue. The moment is removed these two implementations from my DTO every things worked fine after that.
I am using GWT 2.6.1.

Axis2 How to create a service instance for other services

My service will load a lot of data (from txt files) to memory every request.
But,I want to keep the data in memory.
Because it is read from same txt files.
public class pirTMain {
public String[] RUN_pirT(...){
...
//this object will read txt files to initialize
ELC elc = new ELC(elcFolder.getPath());
//use elc to initialize a graph
pirT.initGraph(userID, nodeFile.getPath(), userScore, elc, true, begin, target);
//Use graph to search paths
itinerary = pirT.search(userID, TopK, begin, beginWithTime, target, targetWithTime);
...
I had read Axis2 document.
It says I can change service scope to "application".
But I still don't know how to do it, because I use eclipse plugin to generate a web service *.arr.
Can anyone suggest me how to separate elc object to another service?
Then, my pirTMain class can use it.
pirTMain is 'request'.
elc is 'application'.
thanks a lot.
There are a lot of different ways to achieve this, the simplest one that comes in my mind is to create a static reference to the read lines so that it's shared among all threads in the same virtual machine:
#WebService
public MyServiceClass {
private static String[] readLines = null;
private static synchronized getLines(){
if (readLines == null)
readLines = ....;
return readLines;
}
public int getNumberOfLines(){
return MyServiceClass.getLines().length;
}
public String getLine(int position){
return MyServiceClass.getLines()[position];
}
...
}
Probably not the "cleanest" way, but it works and it's easy to do. You could also wrap the login in a more standard "singleton pattern" if you prefer. keep in mind that getLines should be synchronized to be thread safe but if you experience bottlenecks remove the synchronized keyword, you could get useless reads on first calls but it would be faster.

How do I create a custom content type as part of an Orchard module?

I would like to create a custom Package content type in Orchard 1.6. I already have a content part that represents the whole db record and UI for a Package, but now I'm wondering if I am going about this correctly.
It seems to me the next step is to use Orchard dashboard to create a new content type, and add my custom content part to the type. But, then the content type is internal to Orchard, with a dependency on my 'external' module that hosts the content part. How can I make it so that my content type is only available when my module is enabled?
For convenience, you could create the content type as part of one of the migrations in your module. This would only run when enabled. It would look something like this...
//Inside of your migration file...
public int UpdateFrom1(){
ContentDefinitionManager.AlterTypeDefinition("Package", cfg=> cfg
.Creatable()
.WithPart("YourCustomPart")
.WithPart("CommonPart")
.WithPart("Whatever other parts you want..."));
return 2;
}
Removing this content type when you disable your module would be the tricky part because it might be kind of unexpected by the user. Maybe "Package" is a type they still want to use with different parts attached. Also, if they manually delete your module without disabling, you can't really write code to respond to that event. The only reliable thing I know of is the IFeatureEventHandler. This would allow you to remove your content type if they disable the module in the admin...
public PackageRemover : IFeatureEventHandler {
private readonly IContentDefinitionManager _contentDefinitionManager;
public PackageRemover(IContentDefinitionManager contentDefinitionManager){
_contentDefinitionManager = contentDefinitionManager;
}
public void Installed(Feature feature){}
public void Enabling(Feature feature){}
public void Enabled(Feature feature){}
public void Disabling(Feature feature){
_contentDefinitionManager.DeleteTypeDefinition("Package");
}
public void Disabled(Feature feature){}
public void Uninstalling(Feature feature){}
public void Uninstalled(Feature feature){}
}