postgresql command not executing successfully through java code - java

I have installed the postgresql database and I have to fire few commands on this database through my java code. But the commands are not executing through java code. If I fire the same commands through command prompt they gets execute. Below is my java code:
package frontend.guifx.pginstallation;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class MyMultipleCommandsEx {
public static void main(String a[]) throws InterruptedException{
List<String> commands = new ArrayList<String>();
commands.add("CMD");
commands.add("/c");
commands.add("SET PGPASSWOR=test_admin");
commands.add(psql.exe --dbname=postgres --username=test_admin --port=5433 --command="\"CREATE schema test;\"");
ProcessBuilder pb = new ProcessBuilder(commands);
pb.directory(new File("C:\\Program Files\\PostgreSQL\\9.5\\bin"));
try {
Process prs = pb.start();
int e = prs.waitFor();
System.out.println("Echo command executed, any errors? " + (e == 0 ? "No" : "Yes"));
System.out.println("Echo Output:\n" + output(prs.getInputStream()));
System.out.println("Error code:"+e);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}

Related

Execute jar file using PLSQL

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

Running 2 cmd codes at runtime in java

I want to run 2 cmd commands consecutively. My purpose here, first compile file(with using cmd command not any other things like Java Compiler API), then run.
compiler.java:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
public class compiler {
public static void main(String[] args) {
final String dosCommand = "cmd /c java -cp ";
final String classname = "example";
final String location = "D:\\";
try {
final Process process2 = Runtime.getRuntime().exec("cmd /k javac D:\\example.java"); //I used /k to remain.
final Process process = Runtime.getRuntime().exec(dosCommand + location + " " + classname);
final InputStream in = process.getInputStream();
final InputStream in2 = process.getErrorStream();
int ch, ch2;
while ((ch = in.read()) != -1) {
System.out.print((char) ch);
}
while ((ch2 = in2.read()) != -1) {
System.out.print((char) ch2); // read error here
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
example.java:(in D:// path.)
public class example {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
When I run compiler.java it gives
Error: Couldn't find or load main class example
No problem in example.java. When I compile and run this example.java file in cmd it runs correctly.
My problem is to run 2 cmd commands consecutively. Finally, How can I run cmd commands consecutively?. Thanks...

Executing Ubuntu commands from java program

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class MyCommand {
public static void main(String[] args) {
String [] commandList = {"/bin/bash","-c", "/home/atul/Desktop/javaprogramm/" , "mkdir newmanisha" , "mkdir newmanisha"};
Runtime r = Runtime.getRuntime();
try {
Process p = r.exec(commandList);
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
while(line!=null)
{
System.out.println(line);
line=reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Trying to execute this but nothing happens . I am using ubuntu 13.10.how to do cd in ubuntu using java program. I have used "-c" but it is not working.
Just replace the commandList related line with the following line. That should work ..
String [] commandList = {"/bin/bash", "-c", "cd /home/atul/Desktop/javaprogramm/ && mkdir newmanisha && mkdir newmanisha"};

method not found in java # jboss4.0 and linux environment

In Linux Method not found in jar file
Environment 1: [Working fine with JBoss 4.0 & Windows ]
Environment 2: [Issue in with JBoss 4.0 & Linux]
ERROR MESSAGE:
SEVERE: >> {==================STACK TRACE IS==========================
Sep 4, 2012 5:12:13 PM com.bct.platform.logger.BPMSLogger logString
SEVERE: >> com.bpms.core.exception.BPMSRuntimeException: BEACP015: No
method available like
this->uploadDocument(org.apache.commons.fileupload.FileItem,java.lang.String,java.lang.String)com.bpms.engine.workflowprocessor.actions.ActionCallProgram.executeAction(ActionCallProgram.java:571)
com.bpms.engine.CommonInterface.executeActions(CommonInterface.java:188)
we are call this reflection
Below is the code sample ,Am trying to call the saveALDocument when cant find the Java in Linux environment . In windows its working fine
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.activation.MimetypesFileTypeMap;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
public class FileUpdation
{
public String saveALDocument(FileItem filebuff,String fileName,String fileUuid) throws Exception
{
String uuidURLMap = "Retry...";
System.out.println("***************SaveDOCUment Entered *************");
try {
byte[] content = filebuff.get();
String filename = filebuff.getName();
if (filename != null) {
filename = FilenameUtils.getName(filename);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return uuidURLMap;
}
public String _getDocURL(String uuid)
{
String strUrl = null;
try {
.........
}
catch (Exception e) {
e.printStackTrace();
}
return strUrl;
}
public String _getName(String strUUID) {
return fileName;
}
}
commons-fileupload-1.2.jar and commons-io-1.1.jar , put them in lib

Client Server Program String leak?

My Server Program:-
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
public class GetFileServeredit implements Runnable {
public static final int SERVERPORT = 4747;
public String FileName=null;
public void run() {
try {
ServerSocket svr=new ServerSocket(SERVERPORT);
while(true){
System.out.println("S: Waiting...");
Socket sktClient=svr.accept();
System.out.println("S: Receiving...");
try{
PrintService services[] = PrintServiceLookup.lookupPrintServices(null, null);
PrintWriter out2 = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sktClient.getOutputStream())),true);
/*for(int z=0;z<services.length;z++){
out2.println(services[z]);
}*/
out2.println("aaa 12212");
out2.flush();
out2.close();
sktClient.close();
System.out.println("Transfer complete.");
}
catch(Exception e){
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String [] args){
Thread servThread =new Thread(new GetFileServeredit());
servThread.start();
}
}
My Client Program
:-
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
public class ClientPrinters implements Runnable {
static final int PORT = 4747; //Change this to the relevant port
static final String HOST = "192.***.*.***"; //Change this to the relevant HOST,//(where Server.java is running)
public void run() {
try {
System.out.print("Sending data...\n");
Socket skt = new Socket(HOST, PORT);
ArrayList Printers =new ArrayList();
InputStream inStream = skt.getInputStream();
BufferedReader inm = new BufferedReader(new InputStreamReader(inStream));
while ((inm.read()) != -1) {
Printers.add(inm.readLine());
}
inm.close();
inStream.close();
skt.close();
}
catch( Exception e ) {
System.out.print("Error! It didn't work! " + e + "\n");
}
}
public static void main(String [] args){
Thread cThread =new Thread(new ClientPrinters());
cThread.start();
}
}
The out that i am sending form the server i.e
out2.println("aaa 12212");
becomes 12212 only at the client side,why? where is the other text??
while ((inm.read()) != -1) {
Printers.add(inm.readLine());
}
This line first reads a single and if that succeeds, it tries to read a line. This swallows (and ignores) one character per line.
Also: you don't specify any character encodings in your server and client: This will work (with some restrictions) as long as client and server run using the same locale. But it will break once they use different default encodings.
It's probably best to just specify the encoding to use "on the wire". A great candidate for this is UTF-8:
// server
PrintWriter out2 = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sktClient.getOutputStream(), "UTF-8")),true);
// client
BufferedReader inm = new BufferedReader(new InputStreamReader(inStream, "UTF-8"));
I was not running your code,but.
while ((inm.read()) != -1) {
}
I think .read() consumed some byte.
you should use some buffer(byte[]) and call .read(buffer)!=-1
Perhaps what you intended was
List<String> printers =new ArrayList<String>();
String line;
while ((line = inm.readLine()) != null)
printers.add(line);
Note: use camelCase for field/variable names.

Categories