i have 2 #RequestMapping; the first uploades a video to my server and the second execute a transcoding linux command.
every #RequestMapping is working but i am tryig from a week to get the filename of the uploaded file from the first #RequestMapping and send it to the second one.
please help me !
this is the first One:
#RequestMapping(value = "/uploadajax", method = RequestMethod.POST)
#ResponseBody
public List<ObjectNode> uploadMultipleFiles(Model model, MultipartHttpServletRequest request, HttpServletResponse response,
Principal principal) throws IOException {
CommonsMultipartFile multipartFile = null;
Iterator<String> iterator = request.getFileNames();
ObjectMapper objectMapper = new ObjectMapper();
FileMeta fileMeta = null;
while (iterator.hasNext()) {
String key = iterator.next();
multipartFile = (CommonsMultipartFile) request.getFile(key);
String uploadedFileName = multipartFile.getOriginalFilename();
try {
List<ObjectNode> listFileNode = new ArrayList<ObjectNode>();
byte[] bytes = multipartFile.getBytes();
String phyPath = request.getSession().getServletContext().getRealPath("/");
String repoUserPath=phyPath+"resources/"+user.getId();
System.out.println("-------------"+user.getId()+"------------------");
System.out.println("####"+repoUserPath);
File repoUSer = new File(repoUserPath);
if (!repoUSer.exists()) {
repoUSer.mkdir();
String filepath =repoUserPath+"/"+multipartFile.getOriginalFilename();
System.out.println("####"+filepath);
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(filepath));
stream.write(bytes);
stream.close();
fileMeta = new FileMeta();
fileMeta.setFileName(multipartFile.getOriginalFilename());
fileMeta.setFileSize((multipartFile.getSize()/1024)/1024+" Mb");
fileMeta.setFileType(multipartFile.getContentType());
fileMeta.setPathfile("http://89.40.113.84:8080/ProjectTranscode/resources/"+user.getId()+"/"+multipartFile.getOriginalFilename());
fileMeta.setLinkdelete("/var/lib/tomcat7/webapps/ProjectTranscode/resources/"+user.getId()+"/"+multipartFile.getOriginalFilename());
serviceMangerTranscode.save(fileMeta);
fileMeta.setUser(user);
serviceMangerTranscode.updateFile(fileMeta);
file= fileMeta;
model.addAttribute("Nomf", file.getFileName());
System.out.println("created!!");
String[] cmdArray = {"ffprobe","-show_streams","-i",filepath };
model.addAttribute("filepath",filepath);
System.out.println("ffprobe2........!!");
//String[] cmdArray = {"ping","www.google.com" };
Process process = Runtime.getRuntime().exec(cmdArray);
InputStream processInputStream =process.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(processInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = null;
System.out.println("<OUTPUT>");
while ( (line = bufferedReader.readLine()) != null){
ObjectNode node = objectMapper.createObjectNode();
System.out.println(line);
node.put("line",line );
listFileNode.add(node);
}
line ="aaa";
ObjectNode node = objectMapper.createObjectNode();
node.put("line",line );
System.out.println("</OUTPUT>");
return listFileNode;
}else {
long size = FileUtils.sizeOfDirectory(repoUSer);
System.out.println("size 1"+(size/1024)/1024);
if ((size/1024)/1024 >100) {
ObjectNode node = objectMapper.createObjectNode();
node.put("error","Size Not Supported for Your repository !");
listFileNode.add(node);
}else{
System.out.println("choix2!!++");
String filepath =repoUserPath+"//"+multipartFile.getOriginalFilename();
System.out.println("####"+filepath);
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(filepath));
stream.write(bytes);
stream.close();
// fileMeta = new FileMeta();
fileMeta.setFileName(multipartFile.getOriginalFilename());
fileMeta.setFileSize((multipartFile.getSize()/1024)/1024+" Mb");
fileMeta.setFileType(multipartFile.getContentType());
fileMeta.setPathfile(filepath);
fileMeta.setLinkdelete("/var/lib/tomcat7/webapps/ProjectTranscode/resources/"+user.getId()+"/"+multipartFile.getOriginalFilename());
serviceMangerTranscode.save(fileMeta);
fileMeta.setUser(user);
serviceMangerTranscode.updateFile(fileMeta);
file= fileMeta;
model.addAttribute("filedetails", fileMeta);
System.out.println("fichier créé!!");
String[] cmdArray = {"ffprobe","-show_streams","-i",filepath };
System.out.println("ffprobe executee........!!");
Process process = Runtime.getRuntime().exec(cmdArray);
InputStream processInputStream =process.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(processInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = null;
System.out.println("<OUTPUT>");
while ( (line = bufferedReader.readLine()) != null){
ObjectNode node = objectMapper.createObjectNode();
// if (line.contains("codec_type") || line.contains("duration_ts")){
System.out.println(line);
node.put("line",line );
listFileNode.add(node);
}//}
line ="bbb";
ObjectNode node = objectMapper.createObjectNode();
node.put("line",line );
System.out.println("</OUTPUT>");
System.out.println("size 2"+(size/1024)/1024);
return listFileNode;
}
}
} catch (Exception e) {
return null;
}
}
return null;
}
and this is the second one:
#RequestMapping(value ="/Transcodage", method = RequestMethod.POST)
public String Trascoood(Model model, HttpServletRequest request, HttpServletResponse response
) throws IOException {
//Recuperation des valeurs utilisateur:
String userIDD =request.getParameter("useridd");
String newFileName =request.getParameter("newFileName");
String encolist=request.getParameter("encolist");
String codeclist=request.getParameter("codeclist");
String bitrate=request.getParameter("bitratevideo");
String Nomf= request.getParameter("mapping1Form");
System.out.println("NOMFFFFFFFFFFF: " + Nomf);
int userIDDD = Integer.parseInt(userIDD);
User user = userv.getUserById(userIDDD);
ObjectMapper objectMapper = new ObjectMapper();
org.codehaus.jackson.node.ObjectNode node = objectMapper.createObjectNode();
//file= serviceMangerTranscode.getFileById(idfile);
ModelAndView modelUserHome = new ModelAndView("userhome");
//System.out.println("file path : " + file.getPathfile() +"*************************************************");
System.out.println("userIDD: " + userIDD + "...............................................");
System.out.println("newFileName: " + newFileName + "...............................................");
System.out.println("encolist: " + encolist + "...............................................");
String newFileN = new StringBuilder().append(".").append(newFileName).append(".").append(encolist).toString();
System.out.println("FILE NAME + EXTENTION: " + newFileN + "...............................................");
//node.put("success", "true");
String[] cmdArray = {"sudo", "ssh", "-tt", "root#89.40.113.84", "/root/dved", "-l", "89.40.112.120,89.40.112.248", "you.mp4", "-s",newFileN};
//String[] cmdArray = {"sudo", "/root/dve", "-l", "89.40.112.120,89.40.112.248", "/root/greece.mkv", "-s",".teeeeeeeeeeeeest.avi" };
//String[] cmdArray = {"sudo","/root/dve","-s",".encoded.avi","-l","89.40.112.248","/root/greece.mkv" };
List<ObjectNode> listFileNode = new ArrayList<ObjectNode>();
try{
Runtime rt = Runtime.getRuntime();
ProcessBuilder pb = new ProcessBuilder(cmdArray);
Process proc = pb.start();
//Process proc = rt.exec(cmdArray);
int rc =0;
rc = proc.waitFor(); // Wait for the process to finish.
System.out.printf("Script executed successfully in ", rc);
InputStream stderr = proc.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("<ERROR___EXEC>");
while ( (line = br.readLine()) != null){
System.out.println(line);
node.put("line",line );
listFileNode.add(node);
}
System.out.println("</ERROR___EXEC>");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
InputStream processInputStream =proc.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(processInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
System.out.println("<RESULTAT___EXEC>");
while ( (line = bufferedReader.readLine()) != null){
System.out.println(line);
node.put("lineR",line );
listFileNode.add(node);
}
System.out.println("</RESULTAT___EXEC>");
}catch (Throwable t)
{
t.printStackTrace();
}
model.addAttribute("usersize",user.getUserfiles().size());
model.addAttribute("listfiles",user.getUserfiles());
model.addAttribute("user",user);
model.addAttribute("MsgTranscode","Votre video a bien ete encodee, vous pouvez desormais la telecharger de votre portfolio!");
return "userhome";
}
Thank you for your reply, i think it cannot be done so i put the data in the database than recover it in the second RequestMapping
Related
I made one scheduler for scheduling some task
public class CronTriggerApp {
#SuppressWarnings("rawtypes")
public static void main(String[] args) throws Exception {
System.out.println("****************************************************************************");
System.out.println("* *");
System.out.println("* Note : Please Place Jar and Properties file in same Folder *");
System.out.println("* *");
System.out.println("****************************************************************************");
Properties cronProp = Utility.getPropFileData();
Set set = cronProp.entrySet();
Iterator itr = set.iterator();
while (itr.hasNext()) {
Map.Entry entry = (Map.Entry) itr.next();
String propKey = (String)entry.getKey();
String propValue = (String)entry.getValue();
String timeArr[] = propValue.split(":");
String seconds = timeArr[2];
String minuts = timeArr[1];
String hour = timeArr[0];
String cronExp = seconds.trim()+" "+minuts.trim()+" "+hour.trim()+" "+"? "+ "* "+ "MON-FRI";
System.out.println("Is Valid Time Declaration: "+CronExpression.isValidExpression(cronExp));
if(CronExpression.isValidExpression(cronExp)) {
JobDataMap map = new JobDataMap();
map.put("TAG", propKey);
JobKey jobKey = new JobKey("jobObj"+propKey, "group"+propKey);
JobDetail jobObj = JobBuilder.newJob(ScheduleTask.class).withIdentity(jobKey).setJobData(map).build();
//CRON_SCHEDULE = 0 46 11,12 ? * MON-FRI
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("TriggerName"+propKey, "group"+propKey)
.withSchedule(CronScheduleBuilder.cronSchedule(cronExp)).build();
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(jobObj, trigger);
}else {
System.out.println("Please Provide Time in HOUR:MINUTS:SECONDS[(0-23):(1-59):(1-59)] Formate for "+propKey);
}
}
}
when trigger execute below class will be called
public class ScheduleTask implements Job {
#SuppressWarnings("static-access")
public void execute(JobExecutionContext arg) throws JobExecutionException{
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println("Today's Date time : "+dtf.format(now));
OutputStream stdin = null;
BufferedReader stdError = null;
BufferedReader stdInput = null;
JobDataMap jobDataObj = arg.getMergedJobDataMap();
String tag = (String)jobDataObj.get("TAG");
System.out.println(tag);
//"OB" "Opening Bell" "Sensex:45,778,Nifty:75,888"
String headerAndmessage = SchedulerDto.pshNotification(tag);
String argumentParam = tag+" "+headerAndmessage;
Hashtable<String, String> hashTable = new Hashtable<String, String> ();
hashTable.put("REQDATA",headerAndmessage);
hashTable.put("ACTION","I");
String uniqueId = SchedulerDto.reqRespLog(hashTable);
File file = new File("");
String filepath = file.getAbsolutePath()+file.separator+"IVLGenericAlerts.jar";
String cmdwithArg =" java -jar " +filepath+" "+argumentParam ;
System.out.println("command and jar path detail with database response: "+cmdwithArg);
try {
// suppose cmdWithArg is java -jar D:\\user_workspace\\IVLGenericAlerts.jar
**Process process = Runtime.getRuntime().exec(cmdwithArg);**
stdin = process.getOutputStream ();
stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
System.out.println("Here is the standard output of the command:");
String lastLine = null;
String currentLine = null;
System.out.println("is output" + (currentLine = stdInput.readLine()) != null);
while ((currentLine = stdInput.readLine()) != null) {
lastLine = currentLine;
System.out.println("abc");
System.out.println(currentLine);
}
System.out.println("before xml");
String xmlToJson = "<?xml version=\"1.0\" ?>"+lastLine;
JSONObject xmlJSONObj = XML.toJSONObject(xmlToJson);
String jsonPrettyPrintString = xmlJSONObj.toString();
JSONObject jsonObject = new JSONObject(jsonPrettyPrintString);
System.out.println(jsonObject);
JSONObject enp = (JSONObject)jsonObject.get("Envelope");
JSONObject Body = (JSONObject)enp.get("Body");
JSONObject RESULT = (JSONObject)Body.get("RESULT");
Object SUCCESS = RESULT.get("SUCCESS");
Object RecipientId = RESULT.get("RecipientId");
Object ORGANIZATION_ID = RESULT.get("SUCCESS");
hashTable.put("ACTION","U");
Map<String, String> hm = new HashMap<String, String>();
hm.put("SUCCESS", SUCCESS.toString());
hm.put("RecipientId", RecipientId.toString());
hm.put("ORGANIZATION_ID", ORGANIZATION_ID.toString());
hashTable.put("RESPDATA",hm.toString());
hashTable.put("UNIQUEID", uniqueId);
SchedulerDto.reqRespLog(hashTable);
//System.out.println(hashTable.toString());
System.out.println("Here is the standard error of the command (if any):\n");
System.out.println("in error");
stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((currentLine = stdError.readLine()) != null) {
System.out.println(currentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
stdin.close();
stdError.close();
stdInput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
You can see in just above class String variable cmdWithArg. when i run it from eclipse this will give output but when i make jar from eclipse with other destination then this will not give any output we are using our custom jar for output IVLGenericAlerts.jar .hope you understand
problem resolved we need to just put escaping double quotes "" when we access folder in command prompt
In my java application, I need to run a Jboss server with the file standalone.bat.
I tried ProcessBuilder, and though it did start the server, my application is blocked waiting for the server to go down
#RequestMapping(value = "api/project/liststart", method = RequestMethod.POST)
public HttpEntity<Boolean> postListServer(#RequestBody ListStart modules) throws Throwable {
String cmd = "";
Boolean response = false;
ProcessBuilder processBuilder = new ProcessBuilder();
String path = "C:\\jboss-as-7.1.1.Final\\bin\\";
String command = standelone.bat+ " >sometext.txt" ;
processBuilder.command("cmd.exe", "/c", command);
processBuilder.directory(new File(path));
Process process = processBuilder.start();
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
String ligne;
while ((ligne = reader.readLine()) != null) {
System.out.println(ligne);
}
int exitCode = process.waitFor();
System.out.println("\nExited with error code : " + exitCode);
String F = path + "\\SomeFile.txt";
System.out.println("------------------------file: " + F);
File file = new File(F);
Scanner scanner = new Scanner(file);
//now read the file line by line...
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if (line.contains("Started server")) {
response = true;
System.out.println("-------------------------------------" + response.toString());
}
}
ResponseEntity responseEntity = new ResponseEntity<Boolean>(response, HttpStatus.OK);
return responseEntity;
}
}
I expect the method above to return true value, but it's being blocked before a value can be returned.
It seems like scanner.hasNextLine() can't get out from while cycle, so try like this :
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if (line.contains("Started server")) {
response = true;
System.out.println("-------------------------------------" + response.toString());
return new ResponseEntity<Boolean>(response, HttpStatus.OK);
} else {
return new ResponseEntity<Boolean>(response, HttpStatus.OK);
}
}
I have a program that encode and decodes with my custom cipher, text files and lossless media files, but the problem is that over 2MB it crashes.
void doTheRabi(File f, byte[] hashedPass) {
try {
// BufferedReader br = new BufferedReader(new InputStreamReader(new
// FileInputStream(f))); // legge il file
// String response = new
// String(Files.readAllBytes(Paths.get(f.getAbsolutePath()))); // scrive tutto
// il file in memoria
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String response = new String(); // ASSEGNO IL CONTENUTO DEL FILE IN QUESTA STRINGA
for (String line; (line = br.readLine()) != null; response += line + "\n")
;
response = response.replace("\n", "newline").replace("\r", "newrow"); // rimpiazzo le new line con "newline"
// e "newrow"
byte[] encodedfile = response.getBytes(StandardCharsets.UTF_8); // trasformo il file in byte
byte[] result = new byte[encodedfile.length]; // variabile temporanea
int hpc = 0;
for (int i = 0; i < result.length; i++) {
result[i] = (byte) (encodedfile[i] + hashedPass[hpc++]); // algoritmo rabi
if (hpc == hashedPass.length) {
hpc = 0;
}
}
String encodedresult = Base64.getEncoder().encodeToString(result); // restituisco il risultato in base64
FileWriter fw = new FileWriter(f);
PrintWriter pw = new PrintWriter(fw);
pw.print("");
pw.append(encodedresult /* + "extension=" + extString */); // scrivo nel file tutto il risultato
pw.flush();
pw.close();
fw.close();
br.close();
String path = f.getAbsolutePath();
String newName = path + ".rab1";
f.renameTo(new File(newName));
} catch (Exception e) {
console.appendText("Error: " + e.getMessage() + "\n");
e.printStackTrace();
}
}
// operazione inversa
void killTheRabi(File f, byte[] hashedPass) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String response = new String();
for (String line; (line = br.readLine()) != null; response += line)
;
byte[] decodedfile = Base64.getDecoder().decode(response);
byte[] result = new byte[decodedfile.length];
int hpc = 0;
for (int i = 0; i < result.length; i++) {
result[i] = (byte) (decodedfile[i] - hashedPass[hpc++]);
if (hpc == hashedPass.length) {
hpc = 0;
}
}
String resultString = bytesToString(result);
String finalres = resultString.replace("newline", "\n").replace("newrow", "\r");
FileWriter fw = new FileWriter(f);
PrintWriter pw = new PrintWriter(fw);
pw.print("");
pw.append(finalres);
pw.flush();
pw.close();
fw.close();
br.close();
String path = f.getAbsolutePath();
String newName = path.replace(".rab1", "");
f.renameTo(new File(newName));
} catch (Exception e) {
console.appendText("Error: " + e.getMessage() + "\n");
e.printStackTrace();
}
}
What am I doing wrong? I think it's because the memory gets full, since java uses a virtual machine, but I don't know a way to enhance the memory usage, maybe using buffers but am I not using them already?
Since you are possibly holding quite a bit of data in memory, try the following:
Increase maximum heap size to be used by the JVM by starting with the parameter -Xmx2048m or more
Needed help with Java program that takes avro.avsc schema file and avrofile as input and converts them to text file in java.
This java code worked for me hope is helpful for others.
import java.io.;
import java.util.;
import org.apache.avro.*;
import org.apache.avro.generic.*;
import org.apache.avro.file.*;
import org.apache.avro.io.*;
public class AvrotoTextFormatter
{
public static void main ( String args[]) throws Exception
{
InputStream in = null;
in = new FileInputStream(args[0]);
BufferedReader br;
BufferedInputStream inStream = new BufferedInputStream(in);
PrintWriter pr1 = new PrintWriter(args[1], "UTF-8");
PrintWriter pr = new PrintWriter(args[2], "UTF-8");
StringTokenizer st;
StringTokenizer st1;
int row_counter = 0;
String header_fields = "";
String content_records = "";
String sCurrentLine = "";
GenericDatumReader<Object> reader = new GenericDatumReader<Object>();
DataFileStream<Object> fileReader = new DataFileStream<Object>(inStream, reader);
pr1.println(fileReader.getSchema().getFields());
pr1.close();
br = new BufferedReader(new java.io.FileReader(args[1]));
while ((sCurrentLine = br.readLine()) != null)
{
st = new StringTokenizer(sCurrentLine," ");
while (st.hasMoreTokens())
{
header_fields = header_fields + st.nextToken() + "|";
st.nextToken();
st.nextToken();
}
}
header_fields = header_fields.substring(1,header_fields.length()-1);
pr.println(header_fields);
File file = new File(args[0]);
DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(fileReader.getSchema());
DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(file, datumReader);
GenericRecord user = null;
while (dataFileReader.hasNext())
{
content_records = "";
user = dataFileReader.next(user);
st1 = new StringTokenizer(header_fields,"|");
while (st1.hasMoreTokens())
{
content_records = content_records + user.get(st1.nextToken()) + "|";
}
content_records = content_records.substring(0,content_records.length()-1);
pr.println(content_records);
}
fileReader.close();
br.close();
pr.close();
}
}
Found snippet with spark to do the same is faster and easier.
Sharing so that will be helpful to others
import org.apache.avro.mapreduce.AvroKeyInputFormat
import org.apache.avro.mapred.AvroKey
import org.apache.hadoop.io.NullWritable
val avroRdd = sc.newAPIHadoopFile("/sit/data/presentation/bbsbi/alayer/test/000000_0", classOf[AvroKeyInputFormat[String]], classOf[AvroKey[String]], classOf[NullWritable]).keys.map(_.toString)
val n=avroRdd.map(_.split(",").map(_.split(":")(1).trim).map(l=>l.substring(l.indexOf("\"")+1,l.lastIndexOf("\""))).mkString("|"))
n.collect.foreach(println)
Below code working for me
private static JSONArray readJsonFromAvro(String absFilePath)throws IOException,
InterruptedException
{
JSONArray jsonarray = new JSONArray();
InputStream in = new FileInputStream(absFilePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedInputStream inStream = new BufferedInputStream(in);
GenericDatumReader<Object> reader = new GenericDatumReader<Object>();
DataFileStream<Object> fileReader = new DataFileStream<Object>(
inStream, reader);
try {
final Schema schema = fileReader.getSchema();
final JsonEncoder encoder = EncoderFactory.get().jsonEncoder(
schema, baos);
for (final Object datum : fileReader) {
//writer.write(datum, encoder);
JSONObject jsonObj = new JSONObject(datum.toString());
jsonarray.put(jsonObj);
}
encoder.flush();
System.out.println();
} finally {
fileReader.close();
}
return jsonarray;
}
How can I run below program? I mean what are 3 command line input I can provide?
import org.apache.avro.*;
import org.apache.avro.generic.*;
import org.apache.avro.file.*;
import org.apache.avro.io.*;
public class AvrotoTextFormatter
{
public static void main ( String args[]) throws Exception
{
InputStream in = null;
in = new FileInputStream(args[0]);
BufferedReader br;
BufferedInputStream inStream = new BufferedInputStream(in);
PrintWriter pr1 = new PrintWriter(args[1], "UTF-8");
PrintWriter pr = new PrintWriter(args[2], "UTF-8");
StringTokenizer st;
StringTokenizer st1;
int row_counter = 0;
String header_fields = "";
String content_records = "";
String sCurrentLine = "";
GenericDatumReader<Object> reader = new GenericDatumReader<Object>();
DataFileStream<Object> fileReader = new DataFileStream<Object>(inStream, reader);
pr1.println(fileReader.getSchema().getFields());
pr1.close();
br = new BufferedReader(new java.io.FileReader(args[1]));
while ((sCurrentLine = br.readLine()) != null)
{
st = new StringTokenizer(sCurrentLine," ");
while (st.hasMoreTokens())
{
header_fields = header_fields + st.nextToken() + "|";
st.nextToken();
st.nextToken();
}
}
header_fields = header_fields.substring(1,header_fields.length()-1);
pr.println(header_fields);
File file = new File(args[0]);
DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(fileReader.getSchema());
DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(file, datumReader);
GenericRecord user = null;
while (dataFileReader.hasNext())
{
content_records = "";
user = dataFileReader.next(user);
st1 = new StringTokenizer(header_fields,"|");
while (st1.hasMoreTokens())
{
content_records = content_records + user.get(st1.nextToken()) + "|";
}
content_records = content_records.substring(0,content_records.length()-1);
pr.println(content_records);
}
fileReader.close();
br.close();
pr.close();
}
}
I'm spawning a process in Java using the following code:
Process newExec = null;
BufferedReader outStream = null;
BufferedReader inStream = null;
BufferedReader errStream = null;
StringBuffer outputBuffer = new StringBuffer();
String PATH_TO_EXEC = config.getExecPath();
try {
newExec = Runtime.getRuntime().exec(PATH_TO_EXEC + " " + args);
}
catch(IOException e){
outputBuffer.append("Error in running executable.");
e.printStackTrace();
return outputBuffer.toString();
}
After the process is spawned it expects some input through stdin. How would I stream strings to this newly-spawned program?
Process newExec = null;
BufferedReader outStream = null;
BufferedReader inStream = null;
BufferedReader errStream = null;
StringBuffer outputBuffer = new StringBuffer();
String PATH_TO_EXEC = config.getExecPath();
try {
newExec = Runtime.getRuntime().exec(PATH_TO_EXEC + " " + args);
PrintWriter o = new PrintWriter(newExec.getOutoutStream());
o.println("input to process");
o.flush();
}
catch(IOException e){
outputBuffer.append("Error in running executable.");
e.printStackTrace();
return outputBuffer.toString();
}