I have the following code and I am trying to create a connection to a database.
I get an error "Could not find or load main class onjava" when I run the command: java -cp . onjava
I am able to run the javac -classpath "C:\CATALINA_HOME\lib*" onjava.java command
Both of my .class and .java files are in the same directory WEB-INF\classes\com\onjava
onjava.java
package com.onjava;
import java.sql.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.*;
import javax.naming.Context;
public class onjava extends HttpServlet {
private DataSource datasource;
public void init(ServletConfig config) throws ServletException {
try {
// Look up the JNDI data source only once at init time
Context envCtx = (Context) new InitialContext().lookup("java:comp/env");
datasource = (DataSource) ((InitialContext) envCtx).lookup("jdbc/testdb");
}
catch (NamingException e) {
e.printStackTrace();
}
}
private Connection getConnection() throws SQLException {
return datasource.getConnection();
}
public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException {
Connection connection=null;
try {
connection = getConnection();
//..<do JDBC work>..
if (connection != null) {
String message = "You are connected!";
System.out.println(message);
} else {
System.out.println("Failed to make connection!");
}
}
catch (SQLException sqlException) {
sqlException.printStackTrace();
}
finally {
if (connection != null)
try {connection.close();} catch (SQLException e) {}
}
}
}
EDIT:
I changed my code and I added the public class. But I am facing the same error when I run it!
package src;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Wrapper;
import java.util.Hashtable;
import java.util.Properties;
import java.io.*;
import javax.activation.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import oracle.jdbc.pool.OracleDataSource;
public class onjava {
public static void main(String[] argv) throws SQLException, NamingException {
Properties prop = new Properties();
System.setProperty(Context.INITIAL_CONTEXT_FACTORY,"org.apache.naming.java.javaURLContextFactory");
Context initialContext = new InitialContext(prop);
if ( initialContext == null){
System.out.print("JNDI problem. Cannot get InitialContext.");
} else {System.out.print("NO JNDI problemb ");}
// Get DataSource
Context envContext = (Context)initialContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/testdb");
System.out.println("\n -------- Oracle JDBC Connection Testing ------");
try {
Connection jdbcConnection = ((Statement) ds).getConnection();
OracleDataSource ods = ((Wrapper) ds).unwrap(OracleDataSource.class);
jdbcConnection.close();
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
String message = "You are connected!";
System.out.println(message);
}
}
When running java like this, you need to explicitly state the main class. Your command should look something more like java -cp . com.onjava.onjava. However, I don't see the main method in this class either. You need to point to the main method (ie, signature public static void main()).
By the way, it is proper convention to give your classes names that start with a capital letter (Onjava).
Ok so from what you told me, you need to have a main class attached to your project. This means going back to your compiler and creating the main method. To add your code, you will need to do something like this in the main class, which I will call onjavaMain:
public class onjavaMain{
//Main method is this
public static void main(String[] args)
{
//create variable of your onjava class
onjava onJavaConnectToDatabase = new onjava();
onJavaConnectToDatabase.doGet(argument1,argument2);
}
}
Now this is not the complete answer, but this will give you an idea of what you need to do in order to run your project in command line.
Related
I am simply trying to call my testImage() method in Wavemaker. I imported the .jar file after running the application perfectly in Eclipse. However when I call the same method in the .jar file in Wavemaker it gives my this error:
Error
Compile failed with output: [{"filename" : "master/services/MyJavaService1/src/com/demo_jquery/myjavaservice1/MyJavaService1.java","type" : "ERROR","lineNumber" : 134,"columnNumber" : 22,"startPosition" : 4743,"endPosition" : 4751,"message" : "The method testImage() in the type pictures.TestUrl is not applicable for the arguments (java.lang.String)"}]
I will now show you the TestUrl class which I call to invoke my two methods testImage() and getImage():
package pictures;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.imageio.ImageIO;
/*
* By: Victor Foning
*
* This program will consist of two Methods:
*
* The First will Test the Validity and reachability of an validity
* of an image URL.
*
* The second methods will log4j
*
*
*
*
*
*/
public class TestUrl {
public Boolean testImage (String l) {
// String urlString = "http://www.eurobiopark.org/sites/default/files/EurobioparkMashups5.1.png";
System.out.println("Using " + l);
// Open connection
URL u = null;
try {
u = new URL( l);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
URLConnection connection = null;
try {
connection = u.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Check if response code is HTTP_OK (200)
HttpURLConnection httpConnection
= (HttpURLConnection) connection;
int code = 0;
try {
code = httpConnection.getResponseCode();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String message = null;
try {
message = httpConnection.getResponseMessage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(code + " " + message);
if (code == HttpURLConnection.HTTP_OK) {
return true;
} else {
return false;
}
}
public void getImage (String u) {
BufferedImage image =null;
try{
URL url =new URL(u);
// read the url
image = ImageIO.read(url);
ImageIO.write(image, "jpg",new File("C://Users//Foning//Desktop//GeoDataLab//mash7.jpg"));
}catch(IOException e){
e.printStackTrace();
}
}
}
The Picture is downloaded locally and the Console out is this:
Using http://www.eurobiopark.org/sites/default/files/EurobioparkMashups5.1.png
200 OK
true
Here is my TestDownload main Class through which I call my two Methods:
package pictures;
import java.io.IOException;
/*
* By: Victor Foning 17/Septembre/2019
*
* From this Main Methods we will call:
*
* TestUrl.java and the GetImage.java Methods
*
*
*
*/
public class TestDownload {
public static void main(String[] args) {
String path = "http://www.eurobiopark.org/sites/default/files/EurobioparkMashups5.1.png";
// We Begin encapsulating the TestUrl Methods
TestUrl im = new TestUrl();
boolean image = im.testImage(path);
if(image){
im.getImage(path);
System.out.print("true");
}
else{
System.out.print(" victor_WakeUP_false");
}
}
}
Here I then export the .jar file (in Bold) into Wavemaker and Make the same method invocation through my JavaService Class:
package com.demo_jquery.myjavaservice1;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pictures.TestUrl;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.springframework.beans.factory.annotation.Autowired;
import com.wavemaker.runtime.security.SecurityService;
import com.wavemaker.runtime.service.annotations.ExposeToClient;
import com.wavemaker.runtime.service.annotations.HideFromClient;
Here you will find the class getImageFromWaveMaker()I create inside my javaService1 class to invoke my two methods:
package com.demo_jquery.myjavaservice1;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pictures.TestUrl;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.springframework.beans.factory.annotation.Autowired;
import com.wavemaker.runtime.security.SecurityService;
import com.wavemaker.runtime.service.annotations.ExposeToClient;
import com.wavemaker.runtime.service.annotations.HideFromClient;
import com.demo_jquery.myjavaservice1.model.*;
#ExposeToClient
public class MyJavaService1 {
private static final Logger logger = LoggerFactory.getLogger(MyJavaService1.class);
#Autowired
private SecurityService securityService;
public void getImageFromWavemaker( String p) {
String path =
"http://www.eurobiopark.org/sites/default/files/EurobioparkMashups5.1.png";
// We Begin encapsulating the TestUrl Methods
TestUrl im = new TestUrl();
boolean image = im.testImage(path);
if(image){
//im.getImage(url);
logger.info("true");
}
else{
logger.info("victor_WakeUP_false");
}
}
}
Please help me figure out why I get and Error when I run this code?
Thanks to a bit of meditation and positive re-orientation from some good friends I was able to solve this issue.
I came to realize that even though camelcase is accepted when declaring method. I re-declared both methods in my TestUrl Class by starting them with a Capital Letter.
With reference to the Error Code:
Aslo, understanding that all classes in java are derived from the object class and that the String class is one of the most important class in Java. I made that java.lang.String class the Super Class when I created all my Classes in Eclipse.
I did a maven Compile, which generated a .jar file. I proceeded to upload the .jar file in my resource lib file on Wavemaker, Binded my variables accordingly with my JavaService class and the results were good.
Please feel free to express any further perspective on this issue, I would be glad to hear it. Thank you!
I have a a standalone java program and it read the data from REST end point and insert data into table in Server.
package com.test.main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.json.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.test.connectdb.ConDataBase;
import com.test.entity.User;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://jsonplaceholder.typicode.com/todos/");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
System.out.println("DONE2");
int responsecode = conn.getResponseCode();
String inline = "";
if(responsecode == 200){
Scanner sc = new Scanner(url.openStream());
while(sc.hasNext())
{
inline+=sc.nextLine();
}
System.out.println("JSON data in string format");
System.out.println(inline);
sc.close();
}else{
throw new RuntimeException("HttpResponseCode:" +responsecode);
}
//-----------------------------------------------------------------------
Connection con = new ConDataBase().buildConnection();
User[] userList = new Gson().fromJson(inline, User[].class);
System.out.println(userList.length);
for (User user : userList) {
//System.out.println(user.getCompleted());
String insert_date = "insert into XX_USER "
+ "(USER_ID)"
+ "VALUES"
+"('"+user.getCompleted()+"')";
try {
PreparedStatement ps_data = con.prepareStatement(insert_date);
ps_data.executeUpdate();
con.commit();
System.out.println("Successfully Inserted");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.getMessage());
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I need to run this jar file using PLSQL. That means I have transferred this jar file into Linux server path (/home/rest). Oracle database is installed in server. I need to run this jar using PLSQL. Is it possible?
Use the LOADJAVA utility to load the jar file and all other jar dependencies into Oracle's internal classpath (this is different from the operating system's class path).
You will probably also want to change your code to a static method without arguments (rather than main with a string array argument) as it will make invoking the method much simpler.
// package and imports
public class Main {
public static void yourMethodName() {
// your code
}
}
Then you need to use something like:
CREATE PROCEDURE get_todos_from_rest_service AS
LANGUAGE JAVA NAME 'com.test.main.Main.yourMethodName()';
To create a procedure wrapper around the java method which you can then invoke in PL/SQL.
A more detailed example can be found here: Database Java Developer's Guide - Java Stored Procedures Application Example
I have DBUtil class which contains the configuration of database. I have property file which contains the DB details. I am trying to load the property file with this class but I am getting an error on load() method saying The method getProperty(String) is undefined for the type Properties. I really dont know what is wrong.
DBUtil class
package com.varun.util;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.arjuna.ats.internal.arjuna.recovery.Connection;
import com.sun.xml.fastinfoset.sax.Properties;
public class DbUtil {
private static Connection connection = null;
public static Connection getConnection(){
if(connection!=null)
{
return connection;
}
else
{
try{
Properties prop=new Properties();
InputStream inputStream=DbUtil.class.getClassLoader().getResourceAsStream("/db.properties");
prop.load(inputStream); // The method load(InputStream) is undefined for the type Properties
String driver = prop.getProp("");//The method getProp(String) is undefined for the type Properties
String url = prop.getProperty("url");//The method getProperty(String) is undefined for the type Properties
String user = prop.getProperty("user"); //The method getProperty(String) is undefined for the type Properties
String password = prop.getProperty("password"); //The method getProperty(String) is undefined for the type Properties
Class.forName(driver);
connection = (Connection) DriverManager.getConnection(url, user, password);
}catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
}
}
I have commented the error along with the line.
You need to import java.util.Properties; and you have imported the wrong class - com.sun.xml.fastinfoset.sax.Properties
The classes are called the same but they are in different package. You probably use some IDE that automatically does your imports and it has imported the wrong type.
I suspect you've imported the wrong Properties.
Try swapping out
import com.sun.xml.fastinfoset.sax.Properties;
for
import java.util.Properties;
Replace the import line :
import com.sun.xml.fastinfoset.sax.Properties;
With:
import java.util.Properties;
Change the import instead of import com.sun.xml.fastinfoset.sax.Properties use import java.util.Properties
File: SelectServerIntf.java:
import java.rmi.*;
import java.util.*;
public interface SelectServerIntf extends Remote{
HashMap executeSelect() throws RemoteException;
}
File: SelectServerImpl.java:
import java.rmi.*;
import java.sql.*;
import java.rmi.server.*;
import java.util.*;
public class SelectServerImpl extends UnicastRemoteObject implements SelectServerIntf {
public SelectServerImpl() throws RemoteException
{
}
public HashMap executeSelect() throws RemoteException
{
String DRIVER = "com.mysql.jdbc.Driver";
String url ="jdbc:mysql://localhost:3306/abc2";
String Query="select * from student";
Connection con=null;
Statement stat=null;
HashMap hm=null;
try
{
Class.forName(DRIVER);
}
catch(ClassNotFoundException cn)
{
System.out.println("ClassNotFound"+cn);
}
try
{
con= DriverManager.getConnection(url,"root","root");
stat=con.createStatement();
ResultSet rs=stat.executeQuery(Query);
hm=new HashMap();
while(rs.next())
{
int rno=rs.getInt(1);
String name=rs.getString(2);
hm.put(new Integer(rno),name);
}
con.close();
}
catch(SQLException se)
{
System.out.println("SQLException"+se);
}
return(hm);
}
}
File: SelectServer.java:
import java.rmi.*;
import java.net.*;
public class SelectServer {
public static void main(String args[])
{
try
{
SelectServerImpl sip=new SelectServerImpl();
Naming.rebind("SELECT-SERVER", sip);
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
}
File: SelectClient.java:
import java.rmi.*;
import java.util.*;
import java.net.*;
public class SelectClient {
public static void main(String args[])
{
String rmiurl="rmi://"+args[0]+"/SELECT-SERVER";
try
{
SelectServerIntf sit=(SelectServerIntf)Naming.lookup(rmiurl);
HashMap hm2=sit.executeSelect();
int sz=hm2.size();
for(int i=1;i<sz;i++)
{
if(hm2.containsKey(new Integer(i)))
System.out.println(i+":"+hm2.get(new Integer(i)));
}
}
catch(Exception e)
{
System.out.println("Exception"+e);
}
}
}
The above RMI program on execution gives
"Class not found Exception:com.mysql.jdbc.Driver"
SQLException:No Suitable Driver found for jdbc:mysql://localhost:3306/abc2
where abc2 is my database containing respective tables.
The above given connection url and drivers works properly for every code but acccept this rmi.
Experts do you find any modification??
You need to put mysql jdbc driver jars in your server's classpath. It will enable your server to load driver class while calling executeSelect()
getConnection Exception javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
null
when i run below code this is the exception i am getting.
I have already created respective jndi name connectionpools in glassfishv3
pl give me any solution....
Thanks..
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class Test {
/**
* #param args
*/
private static DataSource ds;
private static Context initialContext = null;
public static Connection getConnection()
{
try
{
initialContext = new InitialContext();
ds = (DataSource) initialContext.lookup("jdbc/__TimerPool");
System.out.println("data source "+ds);
return ds.getConnection();
}
catch (Exception e)
{
System.out.println(("getConnection Exception " + e));
}
return null;
}
public static void main(String[] args) {
System.out.println(Test.getConnection());
}
}
ds = (DataSource) initialContext.lookup("jdbc/__TimerPool");
ds = (DataSource) initialContext.lookup("java:comp/jdbc/__TimerPool");
EDIT: Sorry, "java:comp/env/jdbc/__TimerPool".