Using java export oracle and obtain the status - java

I want to use Java export Oracle database, and obtain the export status(indicates success or failure), if the operation failed, should return the reason why failed.
But I have trouble in this problem, the export is success,but the label I defined is always false and return [].
What should I do to get the true status or obtain the failure details.
public class DumpFile {
/**
* Default constructor
*/
public DumpFile() {
}
/**
* #return
* #throws InterruptedException
*/
public static boolean LoadToOracle(String Path) throws InterruptedException {
String importStr = "imp scott/tiger#orcl file="+Path+" full=y ignore=y";
Process process_oracle = null;
boolean flag = false;
List<String[]> processListOracle = new ArrayList<String[]>();
try {
process_oracle = Runtime.getRuntime().exec(importStr);
process_oracle.waitFor();
BufferedReader input = new BufferedReader(new InputStreamReader(
process_oracle.getInputStream(), "utf8"));
String line = "";
while ((line = input.readLine()) != null) {
System.out.println(line);
String[] content = line.split("\n");
processListOracle.add(content);
}
int exevalue = process_oracle.waitFor();
System.out.println("exevalue:"+exevalue);
input.close();
} catch (Exception e) {
e.printStackTrace();
}
for (String[] line : processListOracle)
for (String temp : line) {
if (temp.trim().equals("successfully"))
flag = true;
}
return flag;
}
public static String exportFromOracle(String FileName) throws InterruptedException {
String Path="/home/oracle/output/";
String exportStr = "exp scott/tiger#orcl file="+Path+FileName;
Process process_oracle = null;
boolean flag = false;
List<String[]> processListOracle = new ArrayList<String[]>();
try {
process_oracle = Runtime.getRuntime().exec(exportStr);
BufferedReader input = new BufferedReader(new InputStreamReader(
process_oracle.getInputStream(), "utf8"));
String line = "";
while ((line = input.readLine()) != null) {
System.out.println("line:"+line);
String[] content = line.split("\n");
processListOracle.add(content);
}
int exevalue = process_oracle.waitFor();
System.out.println("exevalue:"+exevalue);
input.close();
} catch (Exception e) {
e.printStackTrace();
}
for (String[] line : processListOracle)
for (String temp : line) {
if (temp.trim().equals("successfully"))
flag = true;
}
System.out.println("flag:"+flag);
if (flag==true)
return flag+"test"+Path;
else{
for (String[] line : processListOracle)
System.out.println(line);
}
return processListOracle.toString();
}
public static void main(String[] args) throws Exception {
String a=exportFromOracle("test.dmp");
System.out.println("a.isEmpty:"+a.isEmpty());
System.out.println(a);
}
}
OUTPUT:
exevalue:0
a.isEmpty:false
[]

I have solved this problem by "log file", I use imp export the database and output the log file, then I use Java to read the log file, to obtain the status.

Related

Output issues: Passing from BufferedReader to array method

I've compiled and debugged my program, but there is no output. I suspect an issue passing from BufferedReader to the array method, but I'm not good enough with java to know what it is or how to fix it... Please help! :)
public class Viennaproj {
private String[] names;
private int longth;
//private String [] output;
public Viennaproj(int length, String line) throws IOException
{
this.longth = length;
this.names = new String[length];
String file = "names.txt";
processFile("names.txt",5);
sortNames();
}
public void processFile (String file, int x) throws IOException, FileNotFoundException{
BufferedReader reader = null;
try {
//File file = new File("names.txt");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void sortNames()
{
int counter = 0;
int[] lengths = new int[longth];
for( String name : names)
{
lengths[counter] = name.length();
counter++;
}
for (int k = 0; k<longth; k++)
{
int counter2 = k+1;
while (lengths[counter2]<lengths[k]){
String temp2;
int temp;
temp = lengths[counter2];
temp2 = names[counter2];
lengths[counter2] = lengths[k];
names[counter2] = names[k];
lengths[k] = temp;
names[k] = temp2;
counter2++;
}
}
}
public String toString()
{
String output = new String();
for(String name: names)
{
output = name + "/n" + output;
}
return output;
}
public static void main(String[] args)
{
String output = new String ();
output= output.toString();
System.out.println(output+"");
}
}
In Java, the public static void main(String[] args) method is the starting point of the application.
You should create an object of Viennaproj in your main method. Looking at your implementation, just creating an object of Viennaproj will fix your code.
Your main method should look like below
public static void main(String[] args) throws IOException
{
Viennaproj viennaproj = new Viennaproj(5, "Sample Line");
String output= viennaproj.toString();
System.out.println(output);
}
And, if you are getting a FileNotFound exception when you execute this, it means that java is not able to find the file.
You must provide complete file path of your file to avoid that issue. (eg: "C:/test/input.txt")

Reading string value from a text file to java arraylist in Java

I want to read string value by splitting | include white space from text file and store to Account class.This is my function for read text file.
public ArrayList<Account> loadAccount(String fn) throws IOException{
ArrayList<Account> account = new ArrayList<Account>();
Scanner infile = new Scanner(new InputStreamReader (new FileInputStream(fn)));
while(infile.hasNextLine()){
String accountNo = infile.nextLine();
String legencyNo = infile.nextLine();
Account c = new Account(accountNo, legencyNo);
account.add(c);
}
infile.close();
return account;
}
This is Account class.
public class Account {
private int id;
private String accountNo;
private String legencyNo;
}
This is AccountInformation.txt.
Account Number | Legacy Key | Description
80000001|7001111|
80000002| |
80000003|7001234|Testing
Update: This is my readFile class.Now, It's ok.I'm using StringUtils.
public static List<Account> readFile() {
String file = "C:\\Dev\\JBoss\\UpdateAccountNumber\\source\\AccountInformation.txt";
BufferedReader br = null;
String line = "";
String splitter = "\\|";
List<Account> accountList = new ArrayList<Account>();
try {
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
String[] accounts = org.apache.commons.lang3.StringUtils.split(line, splitter);
String accountNo = "",legencyNo="";
for(int i = 0;i<accounts.length;i++){
if (i == 0){
accountNo = (accounts[0] == null) ? "" : accounts[0];
}
if (i==1){
legencyNo = (accounts[1] == null) ? "" : accounts[1];
}
}
Account a = new Account(accountNo,legencyNo);
accountList.add(a);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return accountList;
}
Just try as. Which mean split string include space .
String[] accounts = line.split(splitter, -1);
Fixed code:
Account class:
class Account
{
private int id;
private String accountNo;
private String legencyNo;
public Account(String accountNo, String legencyNo)
{
this.accountNo = accountNo;
this.legencyNo = legencyNo;
}
#Override
public String toString()
{
return this.accountNo + " " + this.legencyNo;
}
}
Test class:
public class Test
{
public static List<Account> readFile()
{
String file = "C:\\workspace\\practise\\test.txt";
BufferedReader br = null;
String line = "";
String splitter = "\\|";
List<Account> accountList = new ArrayList<Account>();
try
{
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null)
{
Account a = null;
String[] accounts = line.split(splitter);
if (accounts.length > 1)
{
a = new Account(accounts[0], accounts[1]);
} else
{
a=new Account(accounts[0], "");
}
accountList.add(a);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
if (br != null)
{
try
{
br.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
return accountList;
}
public static void main(String[] args)
{
List<Account> acct = readFile();
for (Account account : acct)
{
System.out.println(account);
}
}
}
Test file:
Account Number|Legacy Key|Description
80000001|7001111|
80000002||
80000003|7001234|Testing
The problem in above code was that when you split in second record there is only one string present i.e 80000002, so you are trying to use accounts[1], but accounts length itself is 1 so you will have to handle with if clause on accounts.length. you can try above code its working. From next time i would suggest you to run your code in debug mode to check where you are getting exception.
If i understood your problem correctly, you need to change your loop
while(infile.hasNextLine()){
String line= infile.nextLine();
String[] tokens = line.split("\\|");
Account c = new Account(tokens[0], tokens[1]);
account.add(c);
}
There are two reasons for that,
First, your all data required are in single line 80000001|7001111|, so calling nextLine will bring you next row rather than data which you required
Second, it might cause you exception, as you are checking is next line exist, and ther you try to read two lines, which will obviousky fail if you have only one line

How to use String.split with a text file to add to a simple array

My goal is to read in a text file and add each element to a simple array (the elements are separated by a comma). The last method readData() is the one I can't figure out.
My code so far :
public class VersionChooser {
private Scanner scan;
private StockManager aManager = new StockManager("StockManager");
public VersionChooser() {
this.scan = new Scanner(System.in);
}
public void chooseVersion() {
this.readData();
this.runTextOption();
}
private void runTextOption() {
StockTUI tui = new StockTUI(this.aManager);
}
public StockManager readData() {
String fileName;
System.out.println("Enter the name of the file to be used");
fileName = this.scan.nextLine();
System.out.println(fileName);
try (final BufferedReader br = Files.newBufferedReader(new File("fileName").toPath(),
StandardCharsets.UTF_16)) {
for (String line; (line = br.readLine()) != null;) {
final String[] data = line.split(",");
StockRecord record = new StockRecord(data[0], Double.valueOf(data[4]));
this.aManager.getStockList().add(record);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
}
StockRecord :
public class StockRecord {
private String date;
private double closingPrice;
public StockRecord(String date, double closingPrice) {
this.date = date;
this.closingPrice = closingPrice;
}
public String getDate() {
return this.date;
}
public double getClosingPrice() {
return this.closingPrice;
}
public String toString() {
return "On " + this.date + " this stock had a closing price of $"
+ this.closingPrice;
}
}
Step1 : Read the file line by line.
Step2: Split the line by ","
Step3 : Construct the String[] to StockRecord.
try (final BufferedReader br = Files.newBufferedReader(new File("stock.txt").toPath(),
StandardCharsets.UTF_8)) {
List<StockRecord> stocks = new ArrayList<StockRecord>();
br.readLine() ; // to avoid first line
for (String line; (line = br.readLine()) != null;) { // first step
final String[] data = line.split(","); // second step
StockRecord record = new StockRecord(data[0], Double.valueOf(data[1]));
stocks.add(record); // third step
}
} catch (IOException e) {
e.printStackTrace();
}
Your stockRecord doesn't has all records. and for demo purpose i did assumed 2 element is closing price . change accordingly

Java deleting blank line in an txt file

I delete some lines from an text file that works fine but I have an problem with blank lines.
Those still inside the .txt file and I don't know how to remove or put those up I searched for an solution on google and here but I failed.
Have anybody an idea how I can remove blank lines?
I tried it with:
currentLine.trim().length() == 0 ); but still with out success
Tanks
public static String COMMENT_LINE = "--.*";
public static String CREATE_BUFFERPOOL = "CREATE BUFFERPOOL.*";
public static String GRANT_USE = "GRANT USE.*";
public static String CONNECT_TO = "CONNECT TO.*";
public static Logger log = Logger.getLogger(Main.class);
//CHANGE PATH
public static String INPUT_FILE_PATH = "C://Users//dpa//Desktop//BW//bwcsvtest.txt";
public static String OUTPUT_FILE_PATH "C://Users//dpa//Desktop//BW//BWFormated.txt";
public static String TRANSFORM_FILE_PATH = "C://Users//dpa//Desktop//BW//BWtransformed.txt";
public static String CSV_FILE_PATH = "C://Users//dpa//Desktop//BW//result.csv";
public static void main(String[] args) throws IOException {
//log.debug("Formating File");
formatTxt(INPUT_FILE_PATH,OUTPUT_FILE_PATH);
log.debug("Formating File complete");
//CsvTransformer csvTransformer = new CsvTransformer(OUTPUT_FILE_PATH,TRANSFORM_FILE_PATH);
//csvTransformer.parseCSVInput();
//csvTransformer.writeDataToCsv(CSV_FILE_PATH);
}
public static void formatTxt(String inputFilePath, String outputFilePath) throws IOException {
File inputFile = new File(inputFilePath);
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
File tempFile = new File(outputFilePath);
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
while ((currentLine = reader.readLine()) != null) {
currentLine = currentLine.trim();
if (currentLine.matches(COMMENT_LINE)) {
log.debug(currentLine);
log.debug("Commentline deleted");
continue;
}
if (currentLine.matches(CREATE_BUFFERPOOL)) {
log.debug(currentLine);
log.debug("CREATE BUFFERPOOL deleted");
continue;
}
if (currentLine.matches(GRANT_USE)) {
log.debug(currentLine);
log.debug("GRANT USE deleted");
continue;
}
if (currentLine.matches(CONNECT_TO)) {
log.debug(currentLine);
log.debug("CONNECT TO deleted");
continue;
}
writer.write(currentLine.replace("\t", ""));
writer.newLine();
}
reader.close();
writer.close();
}
}
Why not add, just after currentLine = currentLine.trim();, this code:
if (currentLine.isEmpty())
continue;
currentLine = currentLine.trim();
if (!currentLine .equals("")) // don't write out blank lines
{
writer.write(currentLine , 0, currentLine .length());
}

Error while running customized java class

I have created a sequence file out of directory and then given index according to groups I want so that I can create groups using that index. This groups are then given one by one to my customized java class which gives information based on the file present in the group.
My problem is that some time it runs perfectly but some time gives different errors like null pointer exception, data type of field not found.
The problem is may be due to size of group. Because I am creating folder based group and then do the fetches the information from that folder inside my customized jar.
So how can I resolve this issue?
Below is my java class code:
public class OperateDirectory extends EvalFunc<DataBag>{
public TupleFactory tupleFactory = TupleFactory.getInstance();
public BagFactory bagFactory = BagFactory.getInstance();
public DataBag exec(Tuple input) throws IOException{
ArrayList<String> protoTuple = new ArrayList<>();
DataBag dataBag = bagFactory.newDefaultBag();
/* Create Directory */
if(input == null)
return dataBag;
if(input.size() != 2)
return dataBag;
long id = (long)input.get(0);
DataBag infoBag = (DataBag)input.get(1);
Iterator<Tuple> it = infoBag.iterator();
File dir = new File("/tmp/TestFolder"+id);
if(dir.exists())
{
FileUtils.cleanDirectory(dir);
}
else
{
dir.mkdir();
}
while(it.hasNext())
{
Tuple file_details = (Tuple)it.next();
if(file_details != null && file_details.size()==3)
{
String file_name = (String)file_details.get(1);
BytesWritable file_contents = (BytesWritable)file_details.get(2);
File f = new File(dir.getPath()+"/"+file_name);
f.deleteOnExit();
writeToFile(file_contents, f);
}
}
/* Perform operation here */
File f = new File("output"+id+".log");
ProcessBuilder performProcess1 = new ProcessBuilder("processes/processor", dir.getPath(),f.getPath());
Process process1 = performProcess1.start();
try
{
process1.waitFor();
if(f.exists() && f.length()>0)
{
ProcessBuilder performProcess2 = new ProcessBuilder("perl", "scripts/ParseFile.pl", f.getPath());
Process process2 = performProcess2.start();
InputStream is = process2.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null)
{
if(!line.isEmpty())
{
String [] tmpArray = line.split(",");
if(tmpArray.length == 2)
{
protoTuple.clear();
protoTuple.add(tmpArray[0]);
protoTuple.add(tmpArray[1]);
dataBag.add(tupleFactory.newTuple(protoTuple));
}
}
}
}
else
{
protoTuple.clear();
protoTuple.add("Error");
protoTuple.add("File "+f.getPath()+" does not exists ");
dataBag.add(tupleFactory.newTuple(protoTuple));
}
}
catch(Exception e)
{
protoTuple.clear();
protoTuple.add("Error ");
protoTuple.add(e.getMessage());
dataBag.add(tupleFactory.newTuple(protoTuple));
}
try
{
FileUtils.cleanDirectory(dir);
FileUtils.deleteDirectory(dir);
}
catch(Exception e)
{
}
return dataBag;
}
void writeToFile(BytesWritable value, File binaryFile) throws IOException{
FileOutputStream fileOut = new FileOutputStream(binaryFile);
fileOut.write(value.getBytes(), 0, value.getLength());
fileOut.close();
}
}

Categories