How to run multiple mongodb commands from a java code. I need the mongodb commands to get executed in background when i run the java program. This program throws some exception "Exception in thread "main" java.io.IOException: Cannot run program "db.createCollection("employ")": error=2, No such file or directory at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029) . . .".
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class try1
{
public static void main(String[] args) throws Exception{
String command ="mongo";
String command1="db.createCollection(\"employ\")";
Process proc = Runtime.getRuntime().exec(command);
Process proc1 = Runtime.getRuntime().exec(command1);
BufferedReader reader =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
proc.waitFor();
BufferedReader reader1 =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line1 = "";
while((line1 = reader1.readLine()) != null) {
System.out.print(line1 + "\n");
}
proc1.waitFor();
}
}
I need to run a set of mongo db commands from the java program. The program works with other terminal commands like "ls"(only single command). But there is problem if we give both command1 and command as "ls". Only one ls command gets executed. If trying with only one mongo db command say, "mongo" command does not get executed completely(program does not terminate). Is it because of "proc.waitFor()".
i got the code. db.eval() function serves my purpose. It works perfectly. :)
"query" is the String which stores the mongodb query.
public void qexecute()
{
try{String query="db.products.insert( { item: "card", qty: 15 } )";
MongoClient mongo = new MongoClient("localhost",27017);
DB db = mongo.getDB("test");
DBCollection collection = db.getCollection(tablename);
db.eval(query);
}
catch(UnknownHostException e){
System.out.println(e);
}
catch (MongoException.DuplicateKey e) {
System.out.println("Exception Caught" + e);
}
}
I strongly recommend to use Mongo Spring Data. You can do that:
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;
public class MongoDBCollection {
public static void main(String args[]) {
try {
//Connect to Database
MongoClient mongoClient = new MongoClient("localhost",27017);
DB db = mongoClient.getDB("myDB");
System.out.println("Your connection to DB is ready for Use::"+db);
//Create Collection
DBCollection linked = db.createCollection("employ",new BasicDBObject());
System.out.println("Collection employ created successfully");
} catch(Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
Related
I have tried to create a simple Java application that will read data from the JavaDB.
The purpose is to get the first "UNAME" variable from the database and assign it to the "user" variable and print it.
package giris;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
* #author Ibrahim
*/
public class Giris {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String user = "";
System.out.println("hello world");
try
{
System.out.println("connecting to database");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/deneme", "ASD", "asd");
System.out.println("succesfully connected");
PreparedStatement pr = con.prepareStatement("select UNAME from ASD.Table1");
ResultSet rs = pr.executeQuery();
while(rs.next())
{
user = rs.getString(0);
}
}
catch(Exception e)
{
System.err.println("error");
}
System.out.println(user);
}
}
This is how my DB looks like
However, when I run the application the output is like this:
run:
hello world
connecting to database
error
BUILD SUCCESSFUL (total time: 0 seconds)
Loading driver class logic is missing, please add this
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
add this derbyclient-10.2.2.0.jar to classpath
hope it will help you
You used it correctly, maybe wrong DB details.
BTW, never use catch block like that, you are missing the information stored in e.
Use below code for more information:
public static void yourMethod()
{
try
{
// Some code...
}
catch(Exception e)
{
logError("Got exception during...", e);
}
}
public static void logError(String message, Throwable e)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
logError(message + "\n" + sw.toString());
}
public static void logError(String message)
{
System.err.println("[ERROR] " + message);
}
I have one requirement where I need to start and stop postgreSQL service through java code. I have written below code but I am getting below error:
System error 5 has occurred.
Access is denied.
System error 5 has occurred.
Access is denied.
Below is my code:
package frontend.guifx.pginstallation;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import common.core.Logger;
import frontend.guifx.util.ConstPG;
public class StartAndStopPostgres {
public static String version = "9.5";
public static void main(String[] args){
try {
System.out.println("Execution starts");
copyPostgreSqlConfFileAndRestartPg();
System.out.println("Execution finished");
} catch (IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void copyPostgreSqlConfFileAndRestartPg() throws IOException, InterruptedException {
// TODO Auto-generated method stub
Path path = Paths.get("data/PGLogs");
//if directory exists?
if (!Files.exists(path)) {
try {
Files.createDirectories(path);
} catch (IOException e) {
//fail to create directory
e.printStackTrace();
}
}
Logger.print(StartAndStopPostgres.class, new String[] { "Copying postgresql.conf file ........" });
Path source = Paths.get("data/postgresql.windows.conf");
String copyConfFileTo = getInstallationPath(version);
copyConfFileTo = copyConfFileTo.substring(0, copyConfFileTo.lastIndexOf("\\"));
Path outputDirectoryPath = Paths.get(copyConfFileTo+File.separator+"data");
Files.copy(source, outputDirectoryPath.resolve(outputDirectoryPath.getFileSystem().getPath("postgresql.conf")), StandardCopyOption.REPLACE_EXISTING);
Logger.print(StartAndStopPostgres.class, new String[] { "Tunning datbase starts........" });
Runtime rt = Runtime.getRuntime();
final File file = new File(System.getProperty("java.io.tmpdir") + File.separator + ConstPG.CREATE_RESTART_PG_BAT_FILE);
PrintWriter writer = new PrintWriter(file, "UTF-8");
writer.println("net stop postgresql-x64-"+version);
writer.println("net start postgresql-x64-"+version);
writer.close();
String executeSqlCommand = file.getAbsolutePath();
Process process = rt.exec(executeSqlCommand);
/*final List<String> commands = new ArrayList<String>();
commands.add("cmd.exe");
commands.add("/C");
commands.add("net stop postgresql-x64-9.5");
commands.add("net start postgresql-x64-9.5");
ProcessBuilder b = new ProcessBuilder(commands);
Process process = b.start();*/
//public static final String PG_RESTART_PG_LOG_FILE = PG_LOGS+"/pgRestartProcess.log";
File createPgRestartProcessFile = new File(ConstPG.PG_RESTART_PG_LOG_FILE);
redirectProcessExecutionOutput(process, createPgRestartProcessFile);
int exitVal = process.waitFor();
Logger.print(StartAndStopPostgres.class, new String[] { "EXIT VALUE after tunning the PostgreSql database :::::::::::::::::::::" + exitVal + " Logs written to file at: " + createPgRestartProcessFile.getAbsolutePath() });
}
public static String getInstallationPath( String version) {
//public static final String PROGRAMME_FILES = "C:\\Program Files\\";
// public static final String PROGRAMME_FILES_X86 = "C:\\Program Files (x86)\\";
// public static final String POSTGRESQL = "PostgreSQL";
// public static final String PSQL_PATH = "\\bin\\psql.exe";
//Const values used below are as above
String psql = findFile(ConstPG.PROGRAMME_FILES, ConstPG.POSTGRESQL + "\\" + version + ConstPG.PSQL_PATH);
if (psql == null) {
psql = findFile(ConstPG.PROGRAMME_FILES_X86, ConstPG.POSTGRESQL + "\\" + version + ConstPG.PSQL_PATH);
}
if(psql != null){
psql = psql.substring(0, psql.lastIndexOf("\\"));
}
return psql;
}
public static String findFile(String directoryName, String fileName) {
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
String absolutePath;
if (fList != null) {
for (File file : fList) {
if (file.isFile()) {
absolutePath = file.getAbsolutePath();
if (absolutePath.contains(fileName))
return (absolutePath);
} else if (file.isDirectory()) {
absolutePath = findFile(file.getAbsolutePath(), fileName);
if (absolutePath != null)
return (absolutePath);
}
}
}
return (null);
}
private static void redirectProcessExecutionOutput(Process process, File processFile) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line = null;
FileWriter fw = new FileWriter(processFile.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
while ((line = reader.readLine()) != null) {
Logger.print(StartAndStopPostgres.class, new String[] { line });
bw.write(line);
bw.newLine();
}
bw.close();
}
}
If I start my eclipse as an Administrator then this works fine. Also if I run start and stop commands on command prompt (which is opened as an Administrator i.e. right click on command prompt icon and click 'run as Administrator') then they execute successfully. But if I run the commands on normal command prompt (which is not opened as a administrator) then I get the same error there as well.
Please advise if there is any solution or any approach to solve this problem.
In java there is a option to run windows cmd as administrator
replace your code "commands.add("cmd.exe");" with below code and try
commands.add("runas /profile /user:ADMINUSERNAME \"cmd.exe");
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"};
I am trying to run a database import command from a Java program like this:
public class Test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String[] str = {"imp ASKUL/askul#ASKDB file=askdbinstall.dmp log=askul.log fromuser=askul touser=ASKUL full=N ignore=Y grants=Y indexes=Y;"};
Process pro;
try {
pro = Runtime.getRuntime().exec(str);
} catch (Exception e) {
System.out.println(e);
}
}
}
The error Output is:
java.io.IOException: Cannot run program "imp ASKUL/askul#ASKDB file=askdbinstall.dmp log=askul.log fromuser=askul touser=ASKUL full=N ignore=Y grants=Y indexes=Y;": CreateProcess error=2, The system cannot find the file specified
The file askdbinstall.dmp is present because if I Paster the Same Command in CMD, it is importing the database Dump Quite fine. What is My Mistake?
Added:
From Reimius Suggestion I have also tried this:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
public class Tes {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
String [] cmd = {"imp", "ASKUL/askul#ASKDB file=askdbinstall.dmp",
"log=askul.log", "fromuser=askul", "touser=ASKUL",
"full=N ignore=Y grants=Y indexes=Y;"};
Process process = Runtime.getRuntime().exec(cmd);
InputStream in = process.getInputStream();
InputStreamReader ins=new InputStreamReader(in);
BufferedReader br = new BufferedReader(ins);
String data = null;
while ((data = br.readLine()) != null) {
System.out.println(data);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Output
run:
BUILD SUCCESSFUL (total time: 3 seconds)
No Import is taking place.
Your import command String is being treated as one single command. Try breaking up the tokens. Also check what is being output from Process#getErrorStream:
String[] str = {"imp", "ASKUL/askul#ASKDB file=askdbinstall.dmp",
"log=askul.log", "fromuser=askul", "touser=ASKUL",
"full=N ignore=Y grants=Y indexes=Y;"};
process = Runtime.getRuntime().exec(str);
BufferedReader in =
new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.err.println(line);
}
Aside: ProcessBuilder make the use of parameter passing easier.
I am very new to Java. I have a task with two steps.
I want to read all data from a .csv file.
After reading that data I have to put it into a SQL Server database.
I have done step one. I'm able to read the .csv file data, but I don't know that how to insert it into a database.
Here's my code for fetching the .csv file data:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class DBcvsdataextractor {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String fileName="D:/USPresident Wikipedia URLs Thumbs HS.csv";
try {
BufferedReader br = new BufferedReader( new FileReader(fileName));
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;
while( (fileName = br.readLine()) != null)
{
if(lineNumber++ == 0)
continue;
//break comma separated line using ","
st = new StringTokenizer(fileName, ",");
while(st.hasMoreTokens())
{
//display csv values
tokenNumber++;
System.out.print(st.nextToken() + '\t');
}
//new line
System.out.println(" ");
//reset token number
tokenNumber = 0;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now, how do I insert that data into SQL Server?
The SQL Server has a tool for this.
Like this:
BULK INSERT CSVTest
FROM 'c:\csvtest.txt'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
Use this command in your java, using JDBC connection, for example.
Hope this helps.
SQL Server file CSV
If you really want to do this with Java, and really want to write your own CSV parser as you currently did, you can
Instead of printing out each 'CSV-file value', you will have to store them. You could for example use an ArrayList for each column in the CSV file, and populate those while reading the CSV file
Once the file is read, you can loop over those ArrayList instances again to construct one big INSERT statement for all data, or one INSERT statement for each row you encountered in the CSV file. If you would opt for the last option, it is not even necessary to use those ArrayList instances. In that case you could construct an indiviual INSERT statement while reading the CSV file, and submit it to the DB after each time a row has been read.
I know the approach of constructing your query while reading the CSV file would be possible as well if you want to go for one big INSERT statement, but separating the INSERT from the reading of the CSV file has the big advantage you can replace your own CSV parser later on by a standard one without too much trouble.
You can customize below class to insert data into sql server.
File ImportCsv.java
package com.example.demo;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import com.opencsv.CSVReader;
public class ImportCsv
{
public static void main(String[] args) throws UnsupportedEncodingException, FileNotFoundException
{
readCsv();
}
private static void readCsv() throws UnsupportedEncodingException, FileNotFoundException
{
Reader readerstream = new InputStreamReader(new FileInputStream("D:\\file.csv"), "Unicode");
try (CSVReader reader = new CSVReader(readerstream, ',');
Connection connection = DBConnection.getConnection();)
{
String insertQuery = "Insert into [dbo].[tableName] ([Column1],[Column2],[Column3], [Column4],...[Column8]") values (?,?,?,?,?,?,?,?)";
PreparedStatement pstmt = connection.prepareStatement(insertQuery);
String[] rowData = null;
int i = 0;
while((rowData = reader.readNext()) != null){
for (String data : rowData)
{
//System.out.println(new String(data.replace(" ","")));
String strLine = new String(data.replace(" ",""));
String[] splited = strLine.split("\\s+");
pstmt.setNString(1, splited[0]);
pstmt.setNString(2, splited[1]);
pstmt.setNString(3, splited[2]);
pstmt.setNString(4, splited[3]);
pstmt.setNString(5, splited[4]);
pstmt.setNString(6, splited[5]);
pstmt.setNString(7, splited[6]);
try {
pstmt.setNString(8, splited[7]);
}catch(Exception e) {
}
if (++i % 8 == 0) {
pstmt.addBatch();// add batch
}
if (i % 80 == 0) {// insert when the batch size is 10
pstmt.executeBatch();
}
}}
System.out.println("Data Successfully Uploaded");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
DBConnection.java
package com.example.demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
static {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
String url = "jdbc:sqlserver://localhost:1433;" +
"databasename=myDBName;user=user;password=pwd;sendStringParametersAsUnicode=true;";
Connection con =DriverManager.getConnection(url);
return con;
}
}