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
Related
I'm trying to use ASTParser in eclipse but facing an NoClassDefFoundError.
I've already followed some guides and imported related 9 jars.
Following are the details:
package test_JDT;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
// import org.eclipse.equinox.common.*;
// import org.eclipse.core.jobs;
class tester {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("hello ast parser");
String javaFilePath = "C:\\Users\\tabzhang\\eclipse-workspace\\test_JDT\\src\\test_JDT/classdemo.java";
byte[] input = null;
try {
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(javaFilePath));
input = new byte[bufferedInputStream.available()];
bufferedInputStream.read(input);
bufferedInputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String str = new String(input);
System.out.println(str);
ASTParser astParser = ASTParser.newParser(AST.JLS3);
astParser.setSource(new String(input).toCharArray());
astParser.setKind(ASTParser.K_COMPILATION_UNIT);
CompilationUnit result = (CompilationUnit) (astParser.createAST(null));
}
}
included jars
the error report
command line
How should I get the code running well?
In Project > Properties: Java Build Path, tab Libraries move all the JARs from the Modulepath to the Classpath.
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 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
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.
i have the following code to test a link to a access database on a new server, everything works with the existing server and i am able to access the folder. !if.exists returns true and i can open the data base using Runtime.getRuntime().exec("run......... + f); so i know it can see the database. im unable to get a reason for the fail but its 100% failing at Connection conn = de.....
can anyone help me.
running gives following output - Java result: -1073741811
package testing;
import connections.LocalProperties;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NewClass {
public static void main(String[] args) {
try {
File f = new File("\\\\***\\***\\****\\***.accdb");
if (!f.exists()) {
System.out.println("file does not exist" + f.getAbsolutePath());
return;
} else {
System.out.println("file does exist" + f.getAbsolutePath());
}
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + f.getAbsolutePath();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String m_URLString = url;
String m_UserName = System.getProperty("user.name");
String m_Password = "*******";
Connection conn = DriverManager.getConnection(m_URLString, m_UserName, m_Password);
conn.close();
} catch (SQLException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
When running i get the following popups:
Java.exe
If you were in the middle of something, the information might be lost, for more information click here
Error signature
App name:java.exe appver 7.0.30.5 modname:msvcr80.dll
I think you are missing this line-
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");