RandomAccessFile opening file does not work - java

What I am doing is creating two nodes that will talk to each other through text files for example: Node 0 is neighbors with Node 1 and vice versa. Node 0 will open up text file from0to1.txt and Node 1 will open up a textfile from1to0.txt.
I verify the creation of these files in this code:
for(Integer i: neighbors){
File file = new File("from" + myId + "to" + i + ".txt");
try{
boolean fileMade = file.createNewFile();
if(!fileMade){
System.err.println("Node " + myId + ": File could not be created.\n Please delete the files before trying again.");
System.exit(1);
}
/**
boolean fileMade = file.createNewFile();
while(!fileMade){
System.out.println("Node " + myId + ": File is already present.");
System.out.println("Node " + myId + ": Deleting file...");
file.delete();
System.out.println("Node " + myId + ": File deleted");
System.out.println("Node " + myId + ": Trying again...");
fileMade = file.createNewFile();
}
*/
System.out.println("Node " + myId + ": File " + file.getName() + " successfully created.");
}
catch(Exception e){
e.printStackTrace();
}
Once these files have been opened up, I am opening them to write into them.
Each node will be sensing data from these "channels" that are text files. When reading, I am opening up these text files with a RandomAccessFile. When I am writing, I am opening up these text files with a FileWriter/BufferedWriter.
The problem is that when I attempt to open up the text files for reading with a RandomAccessFile, it throws a FileNotFoundException. I have attempted to run f.exist() and it also turns up as false.
Why is it not creating the file/not acknowledging that the file exists?
Here is the code:
for(Integer n: neighbors){
RandomAccessFile raf = null;
File f = new File("from" + n + "to" + nodeID + ".txt");
System.out.println(f.exists());
System.out.println(f.canRead());
//FileReader fr = null;
try{
System.out.println("Trying to open file: " + "from" + n + "to" + nodeID + ".txt");
//System.out.println("Node " + nodeID + ": Setting up Random Access File");
//fr = new FileReader(new File("from" + n + "to" + nodeID + ".txt"));
//System.out.println(fr.read());
//fr.close();
raf = new RandomAccessFile(f, "r");
raf.seek(offsetList.get(n));
/**

Related

how to simulate Excel control codes in String

One web project I'm involved in requires generating a CSV to the user.
One field is notes and there can be multiple notes in the field, separated by a return (alt-enter in Excel), appearing as
A USER entered on 02/17/2023: Test note
A USER entered on 02/17/2023: This is another note
Is it possible to insert control codes into a Java string that Excel will pick up and format the cell properly?
For what it's worth, this was my attempt:
}else if (formType.equalsIgnoreCase("downloadCSV")) {
Date d = new Date();
String filename = "C:/temp/rtTmp" + d.getTime() + ".csv";
File f = new File(filename);
List<Contact> contactList = RetentionTrackDatabaseUtil.getContacts();
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
bw.write("name,"
+ "gender,"
+ "age,"
+ "DOB,"
+ "DOH,"
+ "DOR,"
+ "DOS,"
+ "dateContact,"
+ "reason,"
+ "status,"
+ "empNum,"
+ "shift,"
+ "phone,note(s)\n");
for (Contact c : contactList) {
System.out.println(c.getAge());
bw.append("\"" + c.getName() + "\"" + ","
+ c.getGender() + ","
+ Integer.toString(c.getAge()) + ","
+ (c.getDOB()!=null?RetentionTrackUtil.sdf.format(c.getDOB()):"") + ","
+ (c.getDOH()!=null?RetentionTrackUtil.sdf.format(c.getDOH()):"") + ","
+ (c.getDOR()!=null?RetentionTrackUtil.sdf.format(c.getDOR()):"") + ","
+ (c.getDOS()!=null?RetentionTrackUtil.sdf.format(c.getDOS()):"") + ","
+ (c.getDateContact()!=null?RetentionTrackUtil.sdf.format(c.getDateContact()):"") + ","
+ c.getReason() + ","
+ c.getStatus() + ","
+ c.getEmpNum() + ","
+ c.getShift() + ","
+ c.getPhone() + ",");
for(Note n: c.getNoteList()){
bw.append("(" + n.getEnteredBy() + " on " + RetentionTrackUtil.sdf.format(n.getNoteDate()) + ")" + n.getNote() + "\\n");
}
bw.append("\n");
}
bw.close();
sendFile(response, filename);
}

Neo4j error: java.lang.OutOfMemoryError: GC overhead limit exceeded

I use StatementResult = session.run(Cypher_query) to run cypher query with java. The program in concern is used to import nodes from csv files with LOAD CSV
This error is thrown:
Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
at java.util.logging.SimpleFormatter.format(Unknown Source)
at java.util.logging.StreamHandler.publish(Unknown Source)
at java.util.logging.ConsoleHandler.publish(Unknown Source)
at java.util.logging.Logger.log(Unknown Source)
at java.util.logging.Logger.doLog(Unknown Source)
at java.util.logging.Logger.log(Unknown Source)
at org.neo4j.driver.internal.logging.JULogger.warn(JULogger.java:54)
at org.neo4j.driver.internal.security.TLSSocketChannel.close(TLSSocketChannel.java:477)
at org.neo4j.driver.internal.net.SocketClient.stop(SocketClient.java:192)
at org.neo4j.driver.internal.net.SocketConnection.close(SocketConnection.java:260)
at org.neo4j.driver.internal.net.ConcurrencyGuardingConnection.close(ConcurrencyGuardingConnection.java:178)
at org.neo4j.driver.internal.net.pooling.PooledSocketConnection.dispose(PooledSocketConnection.java:251)
at org.neo4j.driver.internal.net.pooling.PooledConnectionReleaseConsumer.accept(PooledConnectionReleaseConsumer.java:50)
at org.neo4j.driver.internal.net.pooling.PooledConnectionReleaseConsumer.accept(PooledConnectionReleaseConsumer.java:29)
at org.neo4j.driver.internal.net.pooling.PooledSocketConnection.close(PooledSocketConnection.java:200)
at org.neo4j.driver.internal.NetworkSession.closeCurrentConnection(NetworkSession.java:385)
at org.neo4j.driver.internal.NetworkSession.syncAndCloseCurrentConnection(NetworkSession.java:359)
at org.neo4j.driver.internal.NetworkSession.run(NetworkSession.java:102)
at org.neo4j.driver.internal.NetworkSession.run(NetworkSession.java:93)
at org.neo4j.driver.internal.NetworkSession.run(NetworkSession.java:73)
Is there any way to go around that error? Or is there no way except for importing less nodes?
The whole java code:
import java.io.File;
import java.io.FileNotFoundException;
import org.neo4j.driver.v1.AuthTokens;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.neo4j.driver.v1.Record;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Logger;
public class ImporterImprovedVersion {
private static String path = "file:///C:/csvsToImport/csvs";
private int num;
private boolean headerPresent(String filePath) throws FileNotFoundException{
Scanner scanner = new Scanner(new File(filePath));
if(scanner.hasNext()){
String firstLine = scanner.nextLine();
scanner.close();
if(filePath.contains("address")){
System.out.println("address! " + this.num + " " + firstLine.contains("addr_tag_links"));
return firstLine.contains("addr_tag_links");
}else if (filePath.contains("transaction")){
System.out.println("transaction! " + this.num + " " + firstLine.contains("value_bitcoin"));
return firstLine.contains("value_bitcoin");
}else{
System.out.println("wallet! " + this.num + " " + firstLine.contains("primAddress,firstSeenTime"));
return firstLine.contains("primAddress,firstSeenTime");
}
}
scanner.close();
return false;
}
public ImporterImprovedVersion(int num, boolean withOutputIndex, Session session, String mainDir) throws FileNotFoundException{
this.num = num;
//import csvs and create corresponding nodes
String folderPath = ImporterImprovedVersion.path + num + "/";
System.out.println(folderPath);
String queryAddr = null;
if(this.headerPresent(mainDir + num + "\\addresses.csv")){
queryAddr = "LOAD CSV From '" + folderPath + "addresses.csv' AS line"
+ " WITH line"
+ " SKIP 1";
}else{
queryAddr = "LOAD CSV From '" + folderPath + "addresses.csv' AS line";
}
String queryWallet = null;
if(this.headerPresent(mainDir + num + "\\wallet.csv")){
queryWallet = "LOAD CSV From '" + folderPath + "wallet.csv' AS line"
+ " WITH line"
+ " SKIP 1";
}else{
queryWallet = "LOAD CSV From '" + folderPath + "wallet.csv' AS line";
}
File tranFile = new File(mainDir + num + "\\transactionRelation.csv");
String queryTran = null;
System.out.println(tranFile);
System.out.println(tranFile.exists());
if(tranFile.exists()){
if(this.headerPresent(mainDir + num + "\\transactionRelation.csv")){
queryTran = "LOAD CSV From '" + folderPath + "transactionRelation.csv' AS line"
+ " WITH line"
+ " SKIP 1";
}else{
queryTran = "LOAD CSV From '" + folderPath + "transactionRelation.csv' AS line";
}
}else{
if(this.headerPresent(mainDir + num + "\\transactionRelation1.csv")){
queryTran = "LOAD CSV From '" + folderPath + "transactionRelation1.csv' AS line"
+ " WITH line"
+ " SKIP 1";
}else{
queryTran = "LOAD CSV From '" + folderPath + "transactionRelation1.csv' AS line";
}
}
StatementResult sR = session.run(queryWallet
+ " MERGE (w:Wallet { primWallAddr:line[0]})"
+ " ON CREATE SET w.first_seen = line[1], w.last_seen=line[2]");
System.out.println("Wallet nodes created");
sR = session.run(queryAddr + " MERGE (a:Address {AddId:(line[0])})"
+ " SET a.addr_tag_link= CASE WHEN a.addr_tag_link = 'null' or a.addr_tag_link IS NULL THEN line[1] ELSE a.addr_tag_link END,"
+ " a.addr_tag= CASE WHEN a.addr_tag = 'null' or a.addr_tag IS NULL THEN line[2] ELSE a.addr_tag END,"
+ " a.first_seen=line[3], a.last_seen=line[4], a.multiExist= a.multiExist OR apoc.convert.toBoolean(line[6])"
+ " WITH a, line[5] as li5"
+ " MATCH (a), (wa:Wallet) WHERE li5=wa.primWallAddr"
+ " MERGE (a)-[r:BelongTo{uniqueReferenceBelongTo:(a.AddId + wa.primWallAddr)}]->(wa)"
+ " ON CREATE SET r.primWallAddr = wa.primWallAddr,"
+ " wa.first_seen = CASE WHEN apoc.date.parse(wa.first_seen, 's',\"yyyy-MM-dd'T'HH:mm:ss\") < apoc.date.parse(a.first_seen, 's',\"yyyy-MM-dd'T'HH:mm:ss\") THEN wa.first_seen ELSE a.first_seen END,"
+ " wa.last_seen = CASE WHEN apoc.date.parse(wa.last_seen, 's',\"yyyy-MM-dd'T'HH:mm:ss\") > apoc.date.parse(a.last_seen, 's',\"yyyy-MM-dd'T'HH:mm:ss\") THEN wa.last_seen ELSE a.last_seen END");
System.out.println("Address nodes created");
System.out.println("BelongTo rel created");
if(withOutputIndex){
sR = session.run(queryTran
+ " MATCH (senderAddress:Address {AddId:line[0]}), (senderAddress)-[:BelongTo]->(sender:Wallet),"
+ " (receiverAddress:Address {AddId:line[1]}), (receiverAddress)-[:BelongTo]->(receiver:Wallet)"
+ " MERGE (sender)-[r:SendTo{uniqueReferenceTran:(line[2] + line[8])}]->(receiver)"
+ " ON CREATE SET r.tranHashString=line[2],r.time=line[3],r.value_bitcoin=line[4],"
+ "r.value_dollar=line[5],r.type=line[6],r.estChanAddr=line[7],r.outputIndex=line[8]");
}else{
System.out.println("withoutOutputIndex");
sR = session.run(queryTran
+ " MATCH (senderAddress:Address {AddId:line[0]}), (senderAddress)-[:BelongTo]->(sender:Wallet),"
+ " (receiverAddress:Address {AddId:line[1]}), (receiverAddress)-[:BelongTo]->(receiver:Wallet)"
+ " MERGE (sender)-[r:SendTo{uniqueReferenceTran:(line[2] + 'default')}]->(receiver)"
+ " ON CREATE SET r.tranHashString=line[2],r.time=line[3],r.value_bitcoin=line[4],"
+ " r.value_dollar=line[5],r.type=line[6],r.estChanAddr=line[7],r.outputIndex='default'");
}
sR.list();
System.out.println("Tran rel created");
String queryAddrDiffWallet = "MATCH (a:Address)-[:BelongTo]->(w1:Wallet), (a)-[r0:BelongTo]->(w2:Wallet)"
+ " WHERE w1 <> w2"
+ " RETURN count(a)";
sR = session.run(queryAddrDiffWallet);
List<Record> records = sR.list();
System.out.println(records.get(0).get("count(a)").asInt());
System.out.println(records.get(0).get("count(a)").asInt() == 0);
if(records.get(0).get("count(a)").asInt() != 0){
sR = session.run("MATCH (a:Address)-[:BelongTo]->(w1:Wallet), (a)-[r0:BelongTo]->(w2:Wallet)"
+ " WHERE w1 <> w2"
+ " RETURN a");
}
String queryMergeWallet = "MATCH (a:Address)-[:BelongTo]->(w1:Wallet)"
+ " WITH DISTINCT a, min(ID(w1)) as minId"
+ " MATCH (minW:Wallet)"
+ " WHERE ID(minW) = minId"
+ " SET a.primWallAddr = minW.primWallAddr"
+ " WITH DISTINCT minW, a"
+ " MATCH (a)-[r0:BelongTo]->(w2:Wallet)"
+ " WHERE minW <> w2"
+ " WITH DISTINCT minW, w2, r0"
+ " SET minW.first_seen = CASE WHEN apoc.date.parse(minW.first_seen, 's',\"yyyy-MM-dd'T'HH:mm:ss\") < apoc.date.parse(w2.first_seen, 's',\"yyyy-MM-dd'T'HH:mm:ss\") THEN minW.first_seen ELSE w2.first_seen END,"
+ " minW.last_seen = CASE WHEN apoc.date.parse(minW.last_seen, 's',\"yyyy-MM-dd'T'HH:mm:ss\") > apoc.date.parse(w2.last_seen, 's',\"yyyy-MM-dd'T'HH:mm:ss\") THEN minW.last_seen ELSE w2.last_seen END"
+ " WITH DISTINCT minW, w2, r0"
+ " DELETE r0"
+ " WITH DISTINCT minW, w2"
+ " MATCH (b:Address)-[r:BelongTo]->(w2)"
+ " WITH DISTINCT r, minW, w2, b"
+ " DELETE r"
+ " WITH DISTINCT b, minW, w2"
+ " MERGE (b)-[be:BelongTo{uniqueReferenceBelongTo:(b.AddId + minW.primWallAddr)}]->(minW)"
+ " ON CREATE SET be.primWallAddr = minW.primWallAddr"
+ " WITH DISTINCT w2, minW"
+ " MATCH (w3:Wallet)-[r2:SendTo]->(w2)"
+ " MERGE (w3)-[rN:SendTo{uniqueReferenceTran:r2.uniqueReferenceTran}]->(minW)"
+ " ON CREATE SET rN.tranHashString=r2.tranHashString,rN.time=r2.time,"
+ "rN.value_bitcoin=r2.value_bitcoin,rN.value_dollar=r2.value_dollar,"
+ "rN.type=r2.type,rN.estChanAddr=r2.estChanAddr,rN.outputIndex=r2.outputIndex"
+ " WITH DISTINCT w2, minW, r2"
+ " DELETE r2"
+ " WITH DISTINCT w2, minW"
+ " MATCH (w2)-[r1:SendTo]->(w4:Wallet)"
+ " MERGE (minW)-[rN2:SendTo{uniqueReferenceTran:r1.uniqueReferenceTran}]->(w4)"
+ " ON CREATE SET rN2.tranHashString=r1.tranHashString,rN2.time=r1.time,"
+ "rN2.value_bitcoin=r1.value_bitcoin,rN2.value_dollar=r1.value_dollar,"
+ "rN2.type=r1.type,rN2.estChanAddr=r1.estChanAddr,rN2.outputIndex=r1.outputIndex"
+ " WITH DISTINCT r1"
+ " DELETE r1"
;
if(records.get(0).get("count(a)").asInt() != 0){
//merge any wallet containing same addresses and adjust the transaction as well (w2 merge to w1)
try{
sR = session.run(queryMergeWallet);
}catch(Exception e){
e.printStackTrace();
try {
Thread.sleep(20000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
sR = session.run(queryMergeWallet);
}
}
System.out.println("same wallet merged");
System.out.println("----------abc----------------------" + num);
//delete all wallets with no addresses
sR = session.run(
" MATCH (n:Wallet)"
+ " WHERE NOT ()-[:BelongTo]->(n)"
+ " DETACH DELETE n"
);
System.out.println("Wall with no addr deleted");
}
public static void main(String[] args) throws FileNotFoundException{
Driver driver = GraphDatabase.driver( "bolt://localhost:7687", AuthTokens.basic( "neo4j", "neo7474" ) );
try(Session session = driver.session()){
String mainDir = "C:\\Program Files\\neo4j-enterprise-3.1.1\\import\\csvsToImport\\csvs";
// create index
session.run( "CREATE CONSTRAINT ON (addr:Address) ASSERT addr.AddId IS UNIQUE");
session.run( "CREATE CONSTRAINT ON (wa:Wallet) ASSERT wa.primWallAddr IS UNIQUE");
System.out.println("aaa");
int counter = 537;
while(counter < 660){
File dir = new File(mainDir + counter);
if(dir.exists()){
System.out.println("aaa");
ImporterImprovedVersion a = new ImporterImprovedVersion(counter, counter > 260, session, mainDir);
}
counter ++;
}
}
}
}
I imported many rows for nodes and relationships. By the time the exception is thrown, the graph has 184448 relationships, 82179 of them have 8 properties; and 117314 nodes, 69714 of them have 6 properties. I will update my question with this information. (Could the number of nodes and relationships along with their properties be the reason?)
Did you try to increase the heap size in the JVM (-Xmx option)? The CSVs you are trying to import may be too big.
LOAD CSV has built in batching possibilities. So whenever you are running out of memory using LOAD CSV use PERIODIC COMMIT. Read more in documentation.
Example:
USING PERIODIC COMMIT 10000
LOAD CSV WITH HEADERS FROM "file:///customers.csv" AS row
CREATE (:Customer {companyName: row.CompanyName})

How to get ID3Tags information of a audio file in a specific URL?

I am trying to get a ID3Tag information from a audio file in a specific URL, after went throgh this topic i found a following code, it helps to retrive a ID3Tag information from a mp3 file. But my question is how i need to apply the below code that will return a ID3Tag information from a specific URL.
Mp3File mp3file = new Mp3File("SomeMp3File.mp3");
if (mp3file.hasId3v2Tag()) {
ID3v2 id3v2Tag = mp3file.getId3v2Tag();
System.out.println("Track: " + id3v2Tag.getTrack());
System.out.println("Artist: " + id3v2Tag.getArtist());
System.out.println("Title: " + id3v2Tag.getTitle());
System.out.println("Album: " + id3v2Tag.getAlbum());
System.out.println("Year: " + id3v2Tag.getYear());
System.out.println("Genre: " + id3v2Tag.getGenre() + " (" + id3v2Tag.getGenreDescription() + ")");
System.out.println("Comment: " + id3v2Tag.getComment());
System.out.println("Composer: " + id3v2Tag.getComposer());
System.out.println("Publisher: " + id3v2Tag.getPublisher());
System.out.println("Original artist: " + id3v2Tag.getOriginalArtist());
System.out.println("Album artist: " + id3v2Tag.getAlbumArtist());
System.out.println("Copyright: " + id3v2Tag.getCopyright());
System.out.println("URL: " + id3v2Tag.getUrl());
System.out.println("Encoder: " + id3v2Tag.getEncoder());
byte[] albumImageData = id3v2Tag.getAlbumImage();
if (albumImageData != null) {
System.out.println("Have album image data, length: " + albumImageData.length + " bytes");
System.out.println("Album image mime type: " + id3v2Tag.getAlbumImageMimeType());
}
}
But my question is how i need to apply the below code that will return a ID3Tag information from a specific URL:http://podcastdownload.npr.org/anon.npr-podcasts/podcast/510184/223365607/npr_223365607.mp3?_kip_ipx=1453569924-1421846382?
You can write it to a mp3 file locally and then read it
I hope this code helps
URLConnection conn = new URL("http://podcastdownload.npr.org/anon.npr-podcasts/podcast/510184/223365607/npr_223365607.mp3").openConnection();
InputStream is = conn.getInputStream();
OutputStream outstream = new FileOutputStream(new File("D:/tmp/SomeMp3File.mp3"));
byte[] buffer = new byte[4096];
int len;
while ((len = is.read(buffer)) > 0) {
outstream.write(buffer, 0, len);
}
outstream.close();
Mp3File mp3file = new Mp3File("SomeMp3File.mp3");
//and your reading code follows

Java can't do system call

I am using Java to format a poem in LaTeX and then compile it. The LaTeX-ization works perfectly fine, but I somehow can't run the command. Is this a problem with my LaTeX invocation? For some reason, when I use Java to write an equivalent batch file and then run it, Java will do nothing but when I run the batch file from the shell, it works.
/**
*
* #param title the title of the poem
* #param poem a <code>List</code> with one string for each line of the
* poem.
* #throws FileNotFoundException
*/
protected static void writePDF(final String title, List<String> poem) throws FileNotFoundException {
final StringBuilder latex = new StringBuilder(0);
// I know I shouldn't concatenate like this; I'll fix it later.
// eeeewww escapes
latex.append(
"\\documentclass[letterpaper,12pt,article,oneside]{memoir}\n"
+ "\\usepackage[utf8]{inputenc}\n"
+ "\\usepackage{ebgaramond}\n"
+ "\\usepackage{hyperref}\n"
+ "\\usepackage[protrusion,expansion,kerning,tracking,spacing]{microtype}\n"
+ "\\linespread{1.3}\n"
+ "\\nonfrenchspacing\n"
+ "\\microtypecontext{spacing=nonfrench}\n"
+ "\\begin{document}\n"
+ "\\title{" + title + "}\n"
+ "\\author{}\n"
+ "\\date{\\today}\n"
+ "\\maketitle\n"
+ "\\setlength{\\parindent}{0pt}\n"
+ "\\setlength{\\parskip}{\\baselineskip}\n");
// Go Java 8!
poem
.stream()
.map((String s)
// Original poem's in HTML
-> s.replace("<p>", "\n\n").replace("<br>", "\\\\\n"))
.forEach(latex::append);
latex.append("\n\\end{document}");
final String latexstr = latex.toString().replace("...", "\\ldots");
final String filename = title + ".tex";
final File file = new File(filename);
try (final PrintWriter pw = new PrintWriter(new BufferedOutputStream(new FileOutputStream(file)))) {
pw.print(latexstr);
}
final String path = file.getAbsolutePath()
.substring(0, file.getAbsolutePath().lastIndexOf("\\")) + "\\";
System.out.println("Path: " + path);
final String LaTeXcmd = "pdflatex \""
+ path
+ title + "\"";
final File script = new File(""
+ rand.nextDouble()
+ "compile"
+ title.replace(" ", "_")
+ ".bat");
//I originally wanted just to write a batch file and run it from Java.
// try (final PrintWriter pw = new PrintWriter(new BufferedOutputStream(new FileOutputStream(script)))) {
// pw.print(""
// //"#echo off\n"
// + "cd " + path + "\n"
// + LaTeXcmd + "\n"
// // + "del \"" + path + title + ".aux\"\n"
// // + "del \"" + path + title + ".log\"\n"
// // + "del \"" + path + title + ".out\"\n"
// // + "del \"" + path + title + ".tex\"\n"
// // + "start /b \"\" cmd /c del \"%~f0\"&exit /b\n"
//
// + "msg * all\n"
// );
// }
try {
System.out.println("latexcmd " + LaTeXcmd);
final File workingdir = new File(path);
System.out.println("workingdir " + workingdir);
// >>>>>>>>>>>>>>>> IS THIS CORRECT? <<<<<<<<<<<<<<<<
Runtime.getRuntime().exec(LaTeXcmd, new String[]{}, workingdir);
// This statement works perfectly fine (Windows).
// Runtime.getRuntime().exec("msg * all");
} catch (IOException ex) {
Logger.getLogger(PoetryBackend.class.getName()).log(Level.SEVERE, null, ex);
}
}
It's not correct. Try
String command = new String[] {"cmd", "/c", LaTeXcmd };
Runtime.getRuntime().exec(command, new String[]{}, workingdir);
since otherwise you're not executing it through command interpreter, which is what you want if you want it to behave like you would run it from cmd prompt.
This applies to running .bat files as well.

Using wkhtmltopdf with JBoss form based authentication

I am trying to use wkhtml2pdf in JBoss with Java to create PDF files. I was successful, but it only creates a PDF file from my login-page, rather than from the jsp file.
I read that it is possible to add parameters like username or password, and this is what I did:
String command = applicationLocation + "wkhtmltopdf.exe " + "--post j_username=" + username +" --post j_password=" + password + " " + reqURL + "?" + reqQuery + " c:/PDF/" + folderName + "/" + id + "/" + folderName + ".pdf";
But that doesn't create a PDF file, not even an error output. This is how my class looks like:
public class GeneratePDF {
String logUserId = "0";
public String path = "c:/PDF";
String applicationLocation = "C:\\Program Files\\wkhtmltopdf\\";
/**
* This method creates a command which calls wkhtmltopdf from Google in order to create a PDF file.
*
* #param reqURL
* #param reqQuery
* #param folderName
* #param id
*/
public void genrateCmd(String reqURL, String username, String password, String reqQuery, String folderName, String id) {
try {
// make sure c:/eGP exists
File destFoldereGP = new File("c:/eGP");
if (destFoldereGP.exists() == false) {
destFoldereGP.mkdirs();
System.out.println("successfully created c:/eGP");
}
// make sure c:/PDF exists
File destFolderPDF = new File("c:/PDF/");
if (destFolderPDF.exists() == false) {
destFolderPDF.mkdirs();
System.out.println("successfully created c:/PDF");
}
// make sure c:/PDF/foldername exists
File destFolder = new File("c:/PDF/" + folderName);
if (destFolder.exists() == false) {
destFolder.mkdirs();
System.out.println("successfully created c:/PDF/foldername");
}
// make sure c:/PDF/foldername/id exists
File destFolder2 = new File("c:/PDF/" + folderName + "/" + id);
if (destFolder2.exists() == false) {
destFolder2.mkdirs();
System.out.println("successfully created c:/PDF/foldername/id");
}
//For Image change 'wkhtmltopdf.exe' to 'wkhtmltoimage.exe' and '.pdf' to '.jpeg'
String command = applicationLocation + "wkhtmltopdf.exe " + "--post j_username=" + username +" --post j_password=" + password + " " + reqURL + "?" + reqQuery + " c:/PDF/" + folderName + "/" + id + "/" + folderName + ".pdf";
System.out.println("Command to create PDF: " + command);
Runtime.getRuntime().exec(command);
System.out.println("Successfully created a new PDF file.");
} catch (IOException e1) {
System.out.println("Exception: " + e1);
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
Any idea how to create PDFs with wkhtml2pdf and form based authentication in JBoss?
Thanks a lot.

Categories

Resources