I am using eclipse and have to develop a jsp application that connects to a derby db.
After I setup the database I went into my project and added derbyclient.jar as well as derbyclient.jar as reference.
However each time I try to get the jdbc class I am getting a ClassNotFoundException.
Class.forName("org.apache.derby.jdbc.ClientDriver");
jakarta.servlet.ServletException: java.lang.ClassNotFoundException: org.apache.derby.jdbc.ClientDriver
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:674)
org.apache.jsp.index_jsp._jspService(index_jsp.java:179)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:71)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:770)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:467)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:379)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:327)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:770)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
I have also tried it with a mysql database and got the same result so I thought maybe I did something wrong with the way I reference.
I intend to use a business java class which then will be used in jsp because I don't want to have the db access code in the jsp code.
The current "BusinessManager.java" class looks like this (only mocking stuff which needs to be replaced with database code).
package com.forum.shared;
import java.sql.*;
import java.time.Instant;
import java.util.*;
public class BusinessManager {
public List<ForumEntity> LoadFromDatabase() throws ClassNotFoundException, SQLException
{
//Class.forName("com.mysql.jdbc.Driver");
//Class.forName("org.apache.derby.jdbc.ClientDriver");
//java.sql.Connection connect = null;
//String dbName = "D:/Apache/test/forum";
//String connectionURL="jdbc:derby://localhost:1527/" + dbName + ";create=true";
//connect = DriverManager.getConnection(connectionURL);
List<ForumEntity> result = new ArrayList<ForumEntity>();
ForumEntity mockData = new ForumEntity();
mockData.setID(1);
mockData.setAntwortId(0);
mockData.setAntwort(false);
mockData.setInhalt("Willkommen im Forum!");
mockData.setTitle("Willkommen");
mockData.setName("Admin");
mockData.setMail("admin#hszg.de");
mockData.setZeit(java.util.Date.from(Instant.now()));
ForumEntity answerData = new ForumEntity();
answerData.setID(2);
answerData.setAntwortId(1);
answerData.setName("Max Mustermann");
answerData.setMail("max_mustermann#gmx.com");
answerData.setInhalt("Das ist eine Antwort");
answerData.setZeit(java.util.Date.from(Instant.now()));
mockData.addAnswer(answerData);
result.add(mockData);
return result;
}
public ForumEntity LoadFromDatabaseById(int id)
{
ForumEntity result = new ForumEntity();
result.setID(1);
result.setAntwortId(0);
result.setAntwort(false);
result.setInhalt("Willkommen im Forum!");
result.setTitle("Willkommen");
result.setName("Admin");
result.setMail("admin#hszg.de");
result.setZeit(java.util.Date.from(Instant.now()));
ForumEntity answerData = new ForumEntity();
answerData.setID(2);
answerData.setAntwortId(1);
answerData.setName("Max Mustermann");
answerData.setMail("max_mustermann#gmx.com");
answerData.setInhalt("Das ist eine Antwort");
answerData.setZeit(java.util.Date.from(Instant.now()));
result.addAnswer(answerData);
return result;
}
public boolean CreateAndSafeForumEntity(int antwordId, boolean antwort, String titel, String inhalt, String name, String mail)
{
boolean result = false;
return result;
}
}
I am out of ideas. I have added the jar files for both dbms and non can be loaded. Any ideas?
Edit: I used this eclipse project template
Edit: Update
Now it gets intersting. I decided to try a different approach. I kept the libs as reference but decided to try load them during runtime.
public List<ForumEntity> LoadFromDatabase() throws ClassNotFoundException, SQLException
{
List<File> jars = Arrays.asList(new File("D:\\Apache\\db-derby-10.15.2.0-bin\\lib").listFiles());
URL[] urls = new URL[jars.size()];
for (int i = 0; i < jars.size(); i++) {
try {
urls[i] = jars.get(i).toURI().toURL();
} catch (Exception e) {
e.printStackTrace();
}
}
URLClassLoader childClassLoader = new URLClassLoader(urls, ClassLoader.getSystemClassLoader());
Class.forName("org.apache.derby.jdbc.ClientDriver", true , childClassLoader);
//Class.forName("com.mysql.jdbc.Driver");
//Class.forName("org.apache.derby.jdbc.ClientDriver");
//java.sql.Connection connect = null;
//String dbName = "D:/Apache/test/forum";
//String connectionURL="jdbc:derby://localhost:1527/" + dbName + ";create=true";
//connect = DriverManager.getConnection(connectionURL);
List<ForumEntity> result = new ArrayList<ForumEntity>();
ForumEntity mockData = new ForumEntity();
mockData.setID(1);
mockData.setAntwortId(0);
mockData.setAntwort(false);
mockData.setInhalt("Willkommen im Forum!");
mockData.setTitle("Willkommen");
mockData.setName("Admin");
mockData.setMail("admin#hszg.de");
mockData.setZeit(java.util.Date.from(Instant.now()));
ForumEntity answerData = new ForumEntity();
answerData.setID(2);
answerData.setAntwortId(1);
answerData.setName("Max Mustermann");
answerData.setMail("max_mustermann#gmx.com");
answerData.setInhalt("Das ist eine Antwort");
answerData.setZeit(java.util.Date.from(Instant.now()));
mockData.addAnswer(answerData);
result.add(mockData);
return result;
}
Guess what when I previously reached Class.forName("org.apache.derby.jdbc.ClientDriver") he allways threw the ClassNotFoundException. Now with the runtime library loading code above I don't get the ClassNotFoundException anymore when I execute Class.forName("org.apache.derby.jdbc.ClientDriver"). Very weird. I must have done something wrong while I set the references.
I am trying to run a MapReduce code to calculate average satisfaction level per department. Below is the sample data. The file has headers and in order to remove the headers I placed these in another txt file and used it to check if the row values are not equal to headers.
Sample Data
satisfaction_level,last_evaluation,number_project,average_montly_hours,time_spend_company,Work_accident,left,promotion_last_5years,sales,salary
0.38,0.53,2,157,3,0,1,0,sales,low
0.8,0.86,5,262,6,0,1,0,sales,medium
0.11,0.88,7,272,4,0,1,0,sales,medium
0.72,0.87,5,223,5,0,1,0,sales,low
0.37,0.52,2,159,3,0,1,0,sales,low
0.41,0.5,2,153,3,0,1,0,sales,low
0.1,0.77,6,247,4,0,1,0,sales,low
0.92,0.85,5,259,5,0,1,0,sales,low
0.89,1,5,224,5,0,1,0,sales,low
Below is my mapper code.
public class SatisfactionLevelMapper extends Mapper<LongWritable, Text, Text, FloatWritable>
{
String header;
#Override
protected void setup(Mapper.Context context) throws IOException, InterruptedException
/* Headers are placed in a separate header.txt file for which the location is specified in the driver */
{
BufferedReader bufferedReader = new BufferedReader(new FileReader("header.txt"));
header = bufferedReader.readLine();
}
public void map(LongWritable key, Text text, Context context) throws IOException, InterruptedException
{
String row = text.toString();
String [] values = row.trim().split(","); //dataset is a CSV file with 10 columns
float satisfaction = 0.0f;
String dept = null;
try
{
if(values.length == 9 && header != row)
{
satisfaction = Float.parseFloat(values[0]); }
}
catch (Exception e)
{
e.printStackTrace();
}
context.write(new Text(dept), new FloatWritable(satisfaction));
}
}
I am getting a NullPointerException Error as below.
Error: java.lang.NullPointerException
at org.apache.hadoop.io.Text.encode(Text.java:450)
at org.apache.hadoop.io.Text.set(Text.java:198)
at org.apache.hadoop.io.Text.<init>(Text.java:88)
at com.df.hra.SatisfactionLevelMapper.map SatisfactionLevelMapper.java:62)
at com.df.hra.SatisfactionLevelMapper.map(SatisfactionLevelMapper.java:1)
at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:145)
at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:784)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:168)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:422)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1642)
at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:163)
Is there a way to figure out which part of my code has the issue?
I am new to Java and trying to figure out a way to debug MapReduce codes. Any help would be appreciated. Thanks!
You cannot initialize a Text value with null, as you're doing here (with dept). Consider using an empty String ("") instead.
We just upgraded to DB2 10.5 from 9.5, this process was working fine until the upgrade was performed on the server. When i run the jar file from a linux server, I get the following error however when i run the exact same code from eclipse on my windows computer, it works just fine! I am also getting a similar error if I calll this sp from DB2 control center. I am looking to know what is causing this and how can i fix this error?
SQL4306N Java stored procedure or user-defined function "ESADBM.GETNEXTID",
specific name "WHDBRMM_UTILS" could not call Java method "GetNextID",
signature "(Ljava/lang/String;[I)V". SQLSTATE=42724
Explanation:
The Java method given by the EXTERNAL NAME clause of a CREATE PROCEDURE
or CREATE FUNCTION statement could not be found. Its declared argument
list may not match what the database expects, or it may not be a
"public" instance method.
User response:
Ensure that a Java instance method exists with the "public" flag and the
expected argument list for this call.
sqlcode: -4306
sqlstate: 42724.
Here is the code:
package pkgUtil_v4_0_0_0;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.hibernate.exception.JDBCConnectionException;
public class DBSequence {
public static final String SEQ_CONTACTID = "ContactIDSeq";
public static final String SEQ_PROJECTID = "ProjectIDSeq";
public static final String SEQ_LOCATIONID = "LocationIDSeq";
public static final String SEQ_SOURCEID = "SourceIDSeq";
public static final String SEQ_SURVEYID = "SurveyIDSeq";
public static final String SEQ_LOGICALSURVEYID = "WageAreaIDSeq";
public static final String SEQ_WAGEDETAILID = "WageDetailIDSeq";
public static final String SEQ_ORGID = "OrgIDSeq";
public static final String SEQ_OFFICEID = "RegionNumberSeq";
public static final String SEQ_LETTERID = "LetterIDSeq";
public static final String SEQ_DODGEID = "DodgeIDSeq";
public static final String SEQ_CRAFTID = "CraftIDSeq";
public static final String SEQ_CRAFTTITLEID = "CraftTitleIDSeq";
public static final String SEQ_ANALYSTID = "AnalystIDSeq";
public static final String SEQ_LETTERTEMPLATEID = "LetterTemplateIDSeq";
public static final String SEQ_RECRATESID = "RecRatesIDSeq";
public static final String SEQ_BRIDGESCDID = "BridgeSCDIDSeq";
public static String drvr = "";
public static Connection con = null;
// utility function
public static int getNextId(Connection lcon, String sequence) throws SQLException {
Boolean bFlag;
PreparedStatement stmt = null;
int id = 0;
String sql = "select next value for esadbm." +
sequence + " from SYSIBM.sysdummy1";
// System.out.println("String = "+sequence);
stmt = lcon.prepareStatement(sql);
ResultSet resultSet = stmt.executeQuery();
if (resultSet.next()) {
id = resultSet.getInt(1);
}
resultSet.close();
stmt.close();
return id;
}
// Stored Procedure Entry Point
public static void getNextId(String sequence, int[] seq) throws SQLException, Exception {
System.out.println("String = "+sequence);
System.out.println("Array = "+seq);
if (drvr.length() == 0) {
drvr = "jdbc:default:connection";
con = DriverManager.getConnection(drvr);
}
drvr = "";
seq[0] = getNextId(con, sequence);
con.close();
}
// test procedure
public static void main(String args[])throws SQLException, Exception {
try {
System.out.println("Connecting to DB " + args[0]);
Class.forName("com.ibm.db2.jcc.DB2Driver");
drvr = "jdbc:db2:" + args[0];
// System.out.println(drvr+args[1] + args[2]);
con = DriverManager.getConnection("jdbc:db2:" + args[0], args[1],args[2]);
// System.out.println(con);
System.out.println("DB Connection Successful");
con = DriverManager.getConnection(drvr, args[1], args[2]);
Statement st = con.createStatement();
String query = "set schema = 'ESADBM'";
st.execute(query);
System.out.println("Getting ID");
int id = getNextId(con, SEQ_SOURCEID);
System.out.println("Returned : " + Integer.toString(id));
}
catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
catch (SQLException sqle) {
sqle.printStackTrace();
}
catch (JDBCConnectionException e) {
System.out.println("Unable to connect to database");
e.printStackTrace();
}
}
}
Here is the stored procedure:
CREATE PROCEDURE "ESADBM "."GETNEXTID"
(
IN SEQUENCE CHARACTER(40),
OUT ID INTEGER
)
DYNAMIC RESULT SETS 0
SPECIFIC WHDBRA_UTILS
EXTERNAL NAME 'pkgUtil_v4_0_0_0.DBSequence!getNextId()'
LANGUAGE JAVA
PARAMETER STYLE JAVA
NOT DETERMINISTIC
FENCED THREADSAFE
MODIFIES SQL DATA
NO DBINFO;
Libraries for external routines, including Java classes and JAR files for Java routines, must be present in a certain location in the DB2 instance directory. When you upgrade your DB2 version, a new instance is created, but those libraries are not copied automatically (which, by the way, makes sense as there is a good chance that they need to be rebuilt).
The error message indicates that the instance cannot find the Java class file that implements GETNEXTID -- that would be DBSequence.class. The class needs to be copied to the sqllib/function directory in the DB2 10.5 instance home on the database server, as explained in the manual. You will probably need also to create pkgUtil_v4_0_0_0 under sqllib/function for the correct package structure. Make sure you compile the Java source using the same JDK version as the one used by the DB2 instance to run the program.
Once you do that, execute CALL SQLJ.REFRESH_CLASSES() in the DB2 client of your choice to make sure DB2 reloads the most current version. After that your stored procedure should work correctly.
Having said that, I don't really understand why you use such a convoluted way of retrieving a SQL sequence value.
I'm using the Object API with OrientDB, and I need to change one of my fields. I currently have something like:
class Book { String author }
But I want to change it to:
class Book { List<String> authors }
My question is: how do I persist this list of Strings in OrientDB? Do I have to declare the list as #Embedded? Do I have to define the Schema as LINKLIST?
I tried the latter, which resulted in:
Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to com.orientechnologies.orient.core.db.record.OIdentifiable
And, if I make the type in the database an Embbed, then it results in the error:
Caused by: java.lang.IllegalArgumentException: Type EMBEDDED must be a multi value type (collection or map)
Which doesn't provide to much information unfortunately.
So, how can I best fix this?
Start point:
I created a new db from the Java API, and I saved a list of authors.
CLASS BOOK
public class Book {
private List<String> authors;
public void setAuthors (List<String> pAuthors){
this.authors = pAuthors;
}
public List<String> getAuthors(){
return this.authors;
}
}
CLASS MAIN
public class DatabaseTipoObject {
private static String remote="remote:localhost/";
public static void main(String[] args) {
String nomeDb="Object";
String path=remote+nomeDb;
try {
OServerAdmin serverAdmin = new OServerAdmin(path).connect("root", "root");
if(serverAdmin.existsDatabase()){
System.out.println("Database '"+nomeDb +"' exist..");
}
else{
serverAdmin.createDatabase(nomeDb, "object", "plocal");
System.out.println(" Database '"+nomeDb +"' created!..");
}
OObjectDatabaseTx db = new OObjectDatabaseTx (path);
db.open("root","root");
db.getEntityManager().registerEntityClass(Book.class);
Book book = db.newInstance(Book.class);
List<String> myAuthors = new ArrayList();
myAuthors.add("Archimede");
myAuthors.add("Pitagora");
book.setAuthors(myAuthors);
db.save(book);
System.out.println("Data inserted!" );
//get info by query
for (Book book_retrive : db.browseClass(Book.class)) {
System.out.println("#: " +book_retrive.getAuthors().get(0) );
System.out.println("#: " +book_retrive.getAuthors().get(1) );
}
db.close();
serverAdmin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
From Studio:
the object 'Book' was created, and it has the field 'authors' as embeddedlist. (Created automatically)
This is a little Program. The Method should set Icons on buttons to a predefined set of icons. But when I start the Program I get a NullPointerException.
The Method
public void SetIcon(boolean isActive) {
ImageIcon IconBold, IconClipboard, IconKursiv, IconUnderline;
Ressources Temp;
if (isActive) {
Temp = new RessourcesAlternate();
} else {
Temp = new RessourcesStandard();
}
IconBold = new ImageIcon(Temp.getBold());
IconClipboard = new ImageIcon(Temp.getClipboard());
IconKursiv = new ImageIcon(Temp.getKursiv());
IconUnderline = new ImageIcon(Temp.getUnderline());
this.btnBold.setText("");
this.btnBold.setIcon(IconBold);
this.btnClipboard.setText("");
this.btnClipboard.setIcon(IconClipboard);
this.btnKursiv.setText("");
this.btnKursiv.setIcon(IconKursiv);
this.btnUnderline.setText("");
this.btnUnderline.setIcon(IconUnderline);
}
The Interface
public interface Ressources {
public URL getBold ();;
public URL getClipboard ();
public URL getUnderline ();
public URL getKursiv ();
}
Class Standard
public final class RessourcesStandard implements Ressources{
final URL CLIPBOARD = Main.class.getResource("Icons/standard/clipboard-icon.png");
final URL BOLD = Main.class.getResource("Icons/standard/bold-icon.png");
final URL UNDERLINE = Main.class.getResource("Icons/standard/underline-icon.png");
final URL KURSIV = Main.class.getResource("Icons/standard/italic-icon.png");
#Override
public URL getBold() {
return BOLD;
}
#Override
public URL getClipboard() {
return CLIPBOARD;
}
#Override
public URL getUnderline() {
return UNDERLINE;
}
#Override
public URL getKursiv() {
return KURSIV;
}
}
Class Alternate
public final class RessourcesAlternate implements Ressources{
final URL CLIPBOARD = Main.class.getResource("Icons/alternate/clipboard-icon.png");
final URL BOLD = Main.class.getResource("Icons/alternate/bold-icon.png");
final URL UNDERLINE = Main.class.getResource("Icons/alternate/underline-icon.png");
final URL KURSIV = Main.class.getResource("Icons/alternate/italic-icon.png");
#Override
public URL getBold() {
return BOLD;
}
#Override
public URL getClipboard() {
return CLIPBOARD;
}
#Override
public URL getUnderline() {
return UNDERLINE;
}
#Override
public URL getKursiv() {
return KURSIV;
}
}
Error Message:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at de.test.Editor.GUI_Tapped.SetIcon(GUI_Tapped.java:262)
at de.test.Editor.GUI.<init>(GUI.java:79)
at de.test.Editor.Main.main(Main.java:23)
GUI is my Main Frame
GUI_Tapped is on possible Open Tab
Okay,
There was some Problem with the URL Objects. They returned Null.
I edited the whole Thing and uses Strings instead of URLs. Now its working.
Thanks
If your NullPointerException occurs on the line where you call setIcon(...) on your JButtons, then your JButtons are likely null. Check the object whose method is being called on the line throwing the NPE and you'll see.
More importantly, you need to learn the general concepts of how to debug a NPE (NullPointerException). You should inspect the line carefully that throws it, find out which variable is null, and then trace back into your code to see why. You will run into these again and again, trust me.
For example, your stack trace has a key line:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at de.test.Editor.GUI_Tapped.SetIcon(GUI_Tapped.java:262) // ***** here *****
at de.test.Editor.GUI.<init>(GUI.java:79)
at de.test.Editor.Main.main(Main.java:23)
This line is the first line of the stacktrace that references one of your classes, and so that is the line that is likely causing the NPE to be thrown. Please check it carefully, please trace back to where your variables should be initialized, and you'll likely solve your problem.