What is causing this Java "Cannot find symbol" error? - java

I'm modifying inherited code and keep getting a weird "cannot find symbol" error which is throwing me off.
//======= Error =========
Compiling 1 source file to /Users/Inprimus/Projects/Workspace/Soft/build/web/WEB-INF/classes
/Users/Inprimus/Projects/Workspace/Soft/WebContent/WEB-INF/classes/fr/service/CarPeer.java:49: cannot find symbol
symbol : method addCarToCompany(java.lang.Long,fr.model.company.Car)
location: class fr.dao.CompanyDAO
cmpDAO.addCarToCompany(idCompany,car);
^
1 error
Car peer:
package fr.service;
import fr.model.company.Car;
import fr.dao.CompanyDAO;
import fr.dao.CarDao;
public class CarPeer {
private static CarDao carDAO= new CarDao();
private static CompanyDAO cmpDAO = new CompanyDAO();
public static void storeCar(Long idCompany, Car car) throws UserServiceException, Exception {
try {
cmpDAO.addCarToCompany(idCompany,car);
System.out.println("Car stored : "+car.toString()+" in "+idCompany);
carDAO.storeCar(car);
} catch(DAOException ex) {
throw new UserServiceException(ex.getMessage(), ex);
}
}
}
CompanyDao:
package fr.dao;
import fr.model.accounting.Cost;
import fr.model.company.Car;
public class CompanyDAO extends GenericDAO<Company> {
private enum ChildType {
COST{
public void addChildToCompany(Company company, Object child) {
company.addCost((Cost)child);
}
},
CAR{
public void addChildToCompany(Company company, Object child) {
company.addCar((Car)child);
}
};
public abstract void addChildToCompany(Company company, Object child);
}
private void addChildToCompany(Long idCompany, Object child, ChildType type) throws NotFoundDAOException, AlreadyExistDAOException, Exception {
try {
// Begin unit of work
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Company company = (Company) session.load(Company.class, idCompany);
type.addChildToCompany(company, child);
session.flush();
// End unit of work
session.getTransaction().commit();
} catch (ObjectNotFoundException ex) {
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
throw new NotFoundDAOException("Identified object " + idCompany
+ " doesn't exist in database", ex);
} catch (ConstraintViolationException ex) {
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
throw new AlreadyExistDAOException("The new identity already exsits in database", ex);
} catch (Exception ex) {
ex.printStackTrace();
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
throw new Exception(ex);
}
}
public CompanyDAO() {
super(Company.class);
}
public void addCarToCompany(Long idCompany, Car car) throws NotFoundDAOException, AlreadyExistDAOException, Exception {
addChildToCompany(idCompany, car, ChildType.CAR);
}
}
I have triple checked but can't find anything wrong with the code thus far. I am building it in Netbeans 7.0.1.I should mention that I get this error when I build, but I can run the web app with no issues whatsoever (yet). But I am worried this may come back to bite in the behind.
I just noticed in the file tree that above the CompanyDAO classes are similarly named files bearing the format: CompanyDAO$ChildType#.class (# corresponds to a number) I'm guessing it hasn't re-compiled the class to generate the extra child Type I added. How can I effect this?

Most likely you're using a previously compiled class file ( which didn't have the method ) in your classpath and the system is trying to use that instead of your current source code.
Otherwise, clean up your workspace, do not depend on existing compilations and try again. This has happened to me in the past.

I keep having the same problem (though I don't know whether it's for the same reason). For me, the only thing that works (apart from ditching this "robust" IDE) is to delete the cache. On windows, it's located in %UserProfile%\.netbeans\7.0\var\cache. I suppose on *nix, it could be under ~/.netbeans/7.0/var/cache. You have to exit NetBeans first, delete the cache, then start NetBeans again.

Is CompanyDao being compiled and available on the classpath before CarPeer?

Clean and build your project. If that doesn't work, then restart Netbeans. Sometimes Netbeans gives weird errors and a full restart of Netbeans and/or computer just seems to fix these unexplainable issues.

This could be the issue because the current netbeans instance that you are running is making use of the previously build up cache during its initialization. So, in order to clear the netbeans cache you can perform any of these two steps mentioned below.
APPROACH 1
1. right click on your project name in netbeans in the projects tab.
2. click on the clean and build option.
3. The cache has been cleared.
APPROACH 2
1. Click "windows key + R" and type "%UserProfile%/appdata/local/netbeans".
2. Navigate to the cache folder and then to the folder with name specifying the netbeans version.
3. Close the Netbeans and Delete all the files present in the folder.
4. Restart the netbeans and now you will be able to see the class name.
If any of these methods did not work then it might be the case that your classpath is not correct.

When using Netbeans 7.2+ do the following:
Close all tabs and exit Netbeans;
Remove cache directory: ~/.cache/netbeans/VERSION. Where VERSION is the Netbeans version, i.e. 7.3.1
Restart Netbeans and "Clean & Build"
Also see How to clear the cache in NetBeans
UPDATE (jan 2021)
Still works # Netbeans 12.2.
When Netbeans is installed with snap, the directory to delete / clean is: ~/snap/netbeans/common/cache

Related

Missing class from package within Netbeans when using Spire.Doc.jar for docx files

I downloaded and installed the free Spire.Doc.jar file to work with .docx files. When I run it within Netbeans the functionality works fine however when I attempt to build the program I am getting the following error:
warning: Supported source version 'RELEASE_6' from annotation processor 'org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor' less than -source '1.8'
Note: Creating static metadata factory ...
error: com.sun.tools.javac.code.Symbol$CompletionFailure: class file for com.spire.doc.packages.spryOb$1
not found
An annotation processor threw an uncaught exception.
Consult the following stack trace for details.
java.lang.RuntimeException: com.sun.tools.javac.code.Symbol$CompletionFailure: class file for com.spire.doc.packages.spryOb$1 not found
I have added the .jar file to my class path however there appears to be a class file missing from the com.spire.packages location.
Does anyone know if this is a Netbeans issue or does it look like there is an issue with the .jar file? I find it strange that it works when I run it within Netbeans but the above error occurs when I attempt to build the project.
I managed to get my application to build. What I had to do was remove the following code from my class and then it worked:
document.getMailMerge().MergeImageField = new MergeImageFieldEventHandler()
{
#Override
public void invoke(Object sender, MergeImageFieldEventArgs args)
{
mailMerge_MergeImageField(sender, args);
}
};
private static void mailMerge_MergeImageField(Object sender, MergeImageFieldEventArgs field)
{
String filePath = field.getImageFileName();
if (filePath != null && !"".equals(filePath))
{
try
{
field.setImage(filePath);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
I'm not sure why it didn't work with this included however I got this code from the following website:
https://www.c-sharpcorner.com/article/how-to-perform-mail-merge-in-word-document-in-java/
therefore I will inform them in case this happens to someone else in the future.

java rmi simple project classNotFoundException binding registry

Ok, I'm sure this should be pretty easy, but I'm fairly new to Java (I'm more a .NET boy :P) and after following every single recommendation I found here to no success, I think it's time to step back and ask.
I'm trying to start a simple rmi project with a client, a server and a common project where common interfaces are defined. I've just implemented my server code, and when I try to run it to check if everything is fine, I get struck on a java.lang.ClassNotFoundException.
After following several answers on similar issues, I'm fair sure that my problem comes from rmiregistry running on a different location than my project.
I use following code to set registry codebase:
public class Utils {
public static final String CODEBASE = "java.rmi.server.codebase";
public static void setCodeBase(Class<?> c) {
String ruta = c.getProtectionDomain().getCodeSource().getLocation().toString();
String path = System.getProperty(CODEBASE);
if (path != null && !path.isEmpty()) {
ruta = path + " " + ruta;
}
System.setProperty(CODEBASE, ruta);
}
}
Then, I try to start my server code with this main class:
public class MainRegulador {
public static void main(String[] args) throws AccessException, RemoteException, NotBoundException {
Utils.setCodeBase(IRegulador.class);
Registry registro = null;
Remote proxy = null;
try {
Regulador myReg = new Regulador();
proxy = UnicastRemoteObject.exportObject(myReg, 36510);
registro = LocateRegistry.getRegistry();
registro.rebind("Distribuidor", proxy); //this is the line where exception is thrown
System.out.println("El Regulador está corriendo. Pulse ENTER para finalizar el proceso.");
System.in.read();
} catch(Exception ex) {
System.out.println("No se ha logrado inicializar el Registrador");
System.out.println(ex.getMessage());
} finally {
if (registro != null && proxy != null) {
registro.unbind("Distribuidor");
UnicastRemoteObject.unexportObject(proxy, true);
}
}
}
}
But when I run it, always get a java.lang.ClassNotFoundException at IRegulador interface.
Now the fun part:
I've printed to console java.rmi.server.codebase value, and it's pointing to bin folder of project where IRegulador interface is defined. (file:/F:/Practicas%20y%20dem%c3%a1s/Sistemas%20Distribuidos/common/bin/)
Obviously, that project is also set in the classpath of server project
(Regulador)
Workspace and rmiregistry are on different disks
Despite all, it doesn't seem a global classpath problem, as Utils class is on the same project as IRegulador interface, and it runs before the exception is thrown (as java.rmi.server.codebase is correctly set).
I've tried to set the classpath of rmiregistry before calling it (although it is directly discouraged on some answers), but nothing changed.
I've also tried to start rmiregistry.exe from Regulador project bin folder, but also seemed to don't change anything.
Coming from a .NET background, I've always found these classpath issues confusing, and this one is starting to consume much more time than I suspect it deserves. I'm in desperate need of help.
UPDATE: I'm starting to think that the problem is within the url it's passed to the codebase from IRegulador.class. If I paste it into windows explorer, the SO is unable to locate it, so I supose that it's being built with some structure problem that prevents the registry to reach the route:
file:/F:/Practicas%20y%20dem%c3%a1s/Sistemas%20Distribuidos/common/bin/
UPDATE2: I thought path route could be too complex, so I decided to simplify it and strip it from any non-straight character. Now codebase value is
file:/F:/Practicas/SD/common/bin/
However the problem persists, I don't know why rmiregistry is unable to reach that folder.
Then I decided to move the whole project to the same disk where rmiregistry is executed, and see if it changes anything. But nothing changed, same problem.
Ok, finally I got it working...
I've just copied rmiregistry.exe into the common/bin folder and launch it directly from there (previously just had called from there).
This seems to fix the problem with the routes (actually it makes the route available to the registry as it's on the same folder, probably all my codebase writting code is superflous now).

Could not load JIntellitype.dll from local file system or from inside JAR

I am trying to use JIntellitype to listen to global hotkeys but I get this error:
Exception in thread "main"
com.melloware.jintellitype.JIntellitypeException: Could not load
JIntellitype.dll from local file system or from inside JAR at
com.melloware.jintellitype.JIntellitype.(JIntellitype.java:114)
at
com.melloware.jintellitype.JIntellitype.getInstance(JIntellitype.java:177)
at utils.HotKey.(HotKey.java:19) at
ui.Main.Catch_Hotkeys(Main.java:78) at ui.Main.(Main.java:20)
at ui.Main.main(Main.java:15) Caused by: java.io.IOException:
FromJarToFileSystem could not load DLL:
com/melloware/jintellitype/JIntellitype.dll at
com.melloware.jintellitype.JIntellitype.fromJarToFs(JIntellitype.java:150)
at
com.melloware.jintellitype.JIntellitype.(JIntellitype.java:105)
... 5 more Caused by: java.lang.NullPointerException at
com.melloware.jintellitype.JIntellitype.fromJarToFs(JIntellitype.java:146)
... 6 more
I have loaded the jar file and I also pointed to the folder where the dlls are located through Referenced Libraries.
Here is the code I am trying to run:
import com.melloware.jintellitype.HotkeyListener;
import com.melloware.jintellitype.IntellitypeListener;
import com.melloware.jintellitype.JIntellitype;
public class HotKey extends Thread implements HotkeyListener, IntellitypeListener {
private final int CTRL_C_SHIFT = 10;
public HotKey()
{
JIntellitype.getInstance().unregisterHotKey(CTRL_C_SHIFT);
JIntellitype.getInstance().registerHotKey(CTRL_C_SHIFT, JIntellitype.MOD_CONTROL + (int)'C', JIntellitype.MOD_SHIFT);
if (!JIntellitype.isJIntellitypeSupported())
{
System.exit(1);
}
}
#Override
public void onIntellitype(int arg0)
{
}
#Override
public void onHotKey(int key)
{
if (key == CTRL_C_SHIFT)
{
System.out.println("smg");
}
}
}
Any idea how to fix this?
Your problem will occur because of a version problem between that OS version and the JRE version.
You should check:
Whether an appropriate dll file is installed in your OS system folder.
JIntellitype package has two dll files, one is for 32bit OSs and the other is for 64bit OSs, they have different names.
Check your Java Platform version in the properties of the projects.
You can try to change the Java Platform, if there are more than one types of JDKs.
Make sure about which one is for 64bit or 32bit version.
Have good luck!
I recommend you do something like this:
try
{
JIntellitype.getInstance().unregisterHotKey(CTRL_C_SHIFT);
MyHotKeyListener hotKeyListener = new MyHotKeyListener();
hotKeyListener.addObserver(new MyEventListener());
JIntellitype.getInstance().addHotKeyListener(hotKeyListener);
JIntellitype.getInstance().registerHotKey(CTRL_C_SHIFT, JIntellitype.MOD_CONTROL + (int)'C', JIntellitype.MOD_SHIFT);
}
catch (JIntellitypeException je)
{
logger.warn("JIntellitype initialization failed.");
// DO WHATEVER (NOTIFY USERS?)
}
I can point to other threads, including one where the creator of this library himself denies problems with the library. However, many users such as myself encounter these sort of problems from time to time where JIntellitype fails to initialize and the only solution is to reboot the computer. Because of this, you should catch the JIntellitype exception (the only exception thrown by the library) and warn users (via dialog window) that the hotkey failed to register. You should give them the option to continue without them, or to reboot the computer and trying again.
Trust me.... unless this is a constant problem (which means you configured it incorrectly), it is your best alternative. This WILL happen from time to time at random.

Using CHelper plugin in IntelliJ for a coding contest

I quite recently discovered a coding site, with coding contests : CodinGame, and in order to solve the problems, we have to hand them over only one file with a main (in the following example, the class Player), and if other classes are needed, we include them in this file.
For this purpose (and seen to be working for another coding site), I have downloaded intelliJ and the plugin CHelper in order to put all the source files into one java file (it is supposed to be the purpose of the CHelper plugin). The problem is: I don't understand how to use/setup this plugin for my coding site. I know it should work because another user of this site has already used the plugin for this purpose.
What I want
For a more detailed example of what I want, here is the class with a main:
// Class Player in file Player.java
public class Player {
public static void main(String[] args) {
System.out.println(new Cell(1,2).toString());
}
}
And this class Cell is in another java file :
// Class Cell in file Cell.java
public class Cell {
int x,y;
public Cell(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return "["+x+","+y+"]";
}
}
And I would like the plugin to merge the two (or more) java files in order to have this :
// Generated : 2 files merged into one file: Player.java
public class Player {
public static void main(String[] args) {
System.out.println(new Cell(1,2).toString());
}
// Class Cell merged in this file
public class Cell {
int x,y;
public Cell(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return "["+x+","+y+"]";
}
}
}
What I achieved
I installed IntelliJ correctly, and downloaded the CHelper plugin.
I installed the toolbar menu buttons linked to TopCoder (the site that this plugin is expressly made for), but the Launch TopCoder button throws a RuntimeException : cannot run program .../javaws no such file.
With some tasks downloaded from TopCoder, I succeeded in merging 2 files into one : TaskA.java into Main.java (with templates downloaded)
What would be ideal
If an Eclipse plugin could work like what I want, I would be very happy to know of it. In fact, that was what I was looking for at the beginning of my search, and I only found some plugin for the IntelliJ IDE.
So I finally found a way to do what I wanted: the guy who had done it shared me a link to the help I needed.
I am going to sum it up specifically for CodinGame here.
I- Toolbar buttons
The important buttons to add to the menu toolbar are
create new task
modify task
delete task
Edit project settings
Now, we have some buttons in the red rectangle :
II- Edit settings
Then we have to edit project settings :
set the default directory to your default package
output directory is for the generated source file
III- Create task
Next thing, we have to create a new task (green "+" button) and set it up using the advanced option. We add the tests input and known output with the button Edit tests. We say we want the generated file to be called Solution.java, and the class where we are going to write is going to be called CGXFormatter.java
We now have two files which have appeared in our package .../puzzle :
CGXFormatter.java with a method solve, which is where we are going to read the input and give our answer in the output
CGXFormatter.task, which contains the info on the test cases, etc. in order for the plugin to generate the source file
IV- Write your solution
For example, we are just going to print "This is the result" in our CGXFormatter class (but we could have created another class file and called it, it would have worked by copying the definition of the class in the generated solution class). Like this :
package com......puzzle;
import java.util.Scanner;
import java.io.PrintWriter;
public class CGXFormatter {
public void solve(int testNumber, Scanner in, PrintWriter out) {
out.println("This is the result");
}
}
V- Generate the solution
Last step: click on run. Then we have the directory generated which is created, and in it, we have the Solution.java file newly generated. We can read this :
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* #author XXX
*/
public class Solution {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CGXFormatter solver = new CGXFormatter();
try {
int testNumber = 1;
while (true)
solver.solve(testNumber++, in, out);
} catch (UnknownError e) {
out.close();
}
}
static class CGXFormatter {
public void solve(int testNumber, Scanner in, PrintWriter out) {
out.println("This is the result");
}
}
}
VI- Last step
Okay, there still remains a little problem: in CodinGame, the solution class should not have public in front of it, so just put class Solution instead of public class Solution and you're done.
If you want, you can also put it in a script to do it automatically with a multirun (plugin to install in IDEA, also).
That's it, you're done.
VII- Edit Octobre 2019
If the plugin complains about not finding a net.egork.... class, you can add these steps that I found here
Update Intellij IDEA to the latest version. Secondly, you go to File
-> Settings... -> Plugins and search for the chelper plugin. It is required to run the task run configurations, and it supplies you with
the buttons on the toolbar, too. After you have done that, you should
be getting the error about impossibility to find and load class from
net.egork... Now you go to the jetbrains plugin site, search for
chelper plugin there, and download the latest zip archive. After
unzipping it, go to File -> Project Structure... -> Libraries -> + ->
Java, select recursively the folder you just unzipped until you get to
a bunch of jars that contain that missing class in the error. After
you have added those jars to your classpath, along with JDK, it should
be enough
As a side note, I remarked that the out.println didn't work as I intended (I don't know why), so I replaced it by System.out.println instead of using the proposed out object in the solve method.

NetBeans is not debugging correctly after I copy sources

Dunno why this happens... Ok here is the situation: I have a nb project on my laptop. I have the same project on my desktop. I copy the sources (not the entire project) on the desktop, overwriting the desktop sources. Everything cleans and builds ok. Then I start the debugger. On the main class I can debug step by step. If it goes into an internal method here is what happens:
Listening on 37574
User program running
LineBreakpoint test.java : 45 successfully submitted.
Breakpoint hit at line 45 in class test by thread main.
Thread main stopped at test.java:45.
User program running
Not able to submit breakpoint LineBreakpoint baseControllerManager.java : 41, reason: No executable location available at line 41 in class baseClasses.JNW.baseControllerManager.
Invalid LineBreakpoint baseControllerManager.java : 41
Debugger stopped on uncompilable source code.
User program finished
As you can see until I'm in static method main it works (line 45) as I jump inside a non static method (that is an override) it comes out with that... I tried to:
clean and build = no effect
manually delete build and dist = no effect
What do you suggest?
For the sake of completeness I'm attaching the sources of the main class:
import baseClasses.JNW.baseAction;
import baseClasses.JNW.baseContResult;
import baseClasses.JNW.baseController;
import baseClasses.JNW.baseControllerManager;
public class test {
public static class starter extends baseController {
public static final String ACTION_START = "ACTION_START";
#Override
public baseContResult doAction(baseAction action) {
if (ACTION_START.equals(action.action)) {
manager.log("action start...");
return new baseContResult(RESULT_OK, baseContResult.resultType.RESULT_OK);
}
return super.doAction(action);
}
#Override
public void init() {
super.init();
}
}
public void startMe() {
baseControllerManager manager;
try {
manager = new baseControllerManager();
} catch (Exception e) {
e.printStackTrace();
return;
}
starter st = new starter();
manager.setMainController(st);
manager.doAction(new baseAction(starter.ACTION_START));
}
public static void main(String args[]) {
test te = new test();
te.startMe();
}
}
Look in the file nbproject/project.properties for the property javac.debug and make sure that it's "true". If it is, grep for that property elsewhere in the nbproject directory and any local ant settings.
On a semi-related note: when I'm creating a project in NetBeans, even if the sources already exist elsewhere, I always create a new "Java Application", and let it populate the project directory as it wants. Then I can move in my sources and update the project, and NetBeans stays happy.
Edit after you tried setting javac.debug:
Looking at your question again, I see that you were able to set a breakpoint on test.java, but not able to set one on baseControllerManager.java. That indicates to me that you're getting the latter class from a JAR somewhere, not from your project directory.
So the first step is to make sure that you haven't defined a CLASSPATH environment variable. This is never a good thing to do, regardless of whether you're using an IDE or a manual build.
Next step is to look at the libraries that you've specified for the NetBeans project. You can use grep on a JARfile; the file directory is in plaintext. It should be sufficient to look for the unqualified classname.
And the final thing is to verify that you are indeed compiling the class, by looking for it in the build directory.
Generally, an uncompilable error means a symbol could not be resolved.
If you have dependencies on other projects, libraries, or jars, make sure they have built successfully / are present.
Checking "Build Projects on Classpath" (in project properties > Build > Compiling) will often fix this. If you don't have this checked, you are responsible for ensuring dependencies are already built.
The property was not present in project.properties. So I added it (at a point where there where many javac.* properties...). Then I grepped like this:
dario#dario-desktop:~/Scrivania/JNW$ grep -r javac.debug *
nbproject/project.properties:javac.debug=true
nbproject/build-impl.xml: <property name="javac.debug" value="true"/>
nbproject/build-impl.xml: <attribute default="${javac.debug}" name="debug"/>
nbproject/build-impl.xml: <javac debug="#{debug}" deprecation="${javac.deprecation}" destdir="#{destdir}" encoding="${source.encoding}" excludes="#{excludes}" fork="${javac.fork}" includeantruntime="false" includes="#{includes}" source="${javac.source}" sourcepath="#{sourcepath}" srcdir="#{srcdir}" target="${javac.target}" tempdir="${java.io.tmpdir}">
nbproject/private/private.properties:javac.debug=true
nbproject/project.properties~:javac.debug=true
In fact it sees my addition on the last line.
I cleaned and rebuilt the project. The debugger is not working again........... I think I'll kick my boss ass until he agrees to use eclipse or he fires me. I'll be unemployed but happy. Apart from joking, #kdgrgory, do you have any more ideas???
I had the same problem and found that if I run clean from project tab it solves the problem.

Categories