overwraith Posted August 16, 2012 Posted August 16, 2012 I have found that often one wants to write an ASCII file, like a batch file, or something, and then wants to convert the file to Duck Script which involves; batch.bat~ Bat cmd Bat cmd Bat cmd Bat cmd Duck Script~ REM INPUT FILE BATCH.BAT STRING copy con batch.bat ENTER STRING Bat cmd ENTER STRING Bat cmd ENTER STRING Bat cmd ENTER STRING Bat cmd ENTER It would be really Awesome if we could write a JAVA/PYTHON/C++/C program to do this automatically. A java program could probably serve both as a command line called program, aswell as a GUI program, using a cmd line flag or the prescence of multiple flags to differentiate between the run states. Quote
Xcellerator Posted August 16, 2012 Posted August 16, 2012 Shouldn't be too hard, considering that you're just taking input and pasting it into a new script and then outputting to a new file. A little STDIO should do the trick.. Quote
Dnucna Posted August 17, 2012 Posted August 17, 2012 (edited) Hi, I just done a little awk for that :) gedit convert.sh &chmod +x convert.sh./convert.sh script.bat[/CODE][CODE]#!/bin/bashawk 'BEGIN{print "DELAY 3000\n"\"GUI R\n"\"DELAY 300\n"\"STRING cmd\n"\"ENTER\n"\"DELAY 300\n"\"STRING copy con BATCH.BAT\n"\"ENTER"}{print "STRING "$0"\nENTER"}END{print "CTRL z\n"\"STRING BATCH.BAT\n"\"ENTER"}' $1[/CODE] Edited August 17, 2012 by Dnucna Quote
overwraith Posted August 19, 2012 Author Posted August 19, 2012 (edited) I probably should have mentioned that I use a Windows box, but theres probably windows option for bash...Im glad that a couple of people were interested in my topic. After I posted this topic I began working on a java solution, and I will post it here. I am working on a GUI option for the java program, right now only command line options work. There are a couple of bugs in the code, like when typing the ^Z character to end the console input you must type it adjacent to text, not on a line by its self. Remember to compile first, then use the java command on the command prompt to run the class.I had a few problems with uploading the file, so I will just copy and paiste the text here; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Formatter; import java.io.File; import java.io.FileWriter; public class ToDuckScript { static final String USAGE = "ToDuckScript.java\n" + "\n" + "Usage:\n" + "ToDuckScript Runs the GUI interface.\n" + "ToDuckScript -i [file ..] Specifies input file.\n" + "ToDuckScript -i [file ..] -o [file ..] Specifies input & output files.\n" + "ToDuckScript -con Input string using the console.\n" + "ToDuckScript -con -o [file ..] Console input paired with file.\n" + "ToDuckScript -?/-h/-H/-help Displays the help screen.\n" + "\n" + "Arguments:\n" + "-i [file ..] Input file.\n" + "-o [file ..] Output file.\n" + "-con Console string input.\n" + "-?/-h/-H/-help Help Screen.\n" + "\n" + "Output method can be omitted to display the output screen to the command prompt."; public static void main(String[] args){ String input = null; String outputFile = null; String duckScript = null; boolean console = false; //bool console determines whether or not are inputting to the console. if (args.length > 0){//run in command line mode //Get command line input first. for(int i = 0 ; i < args.length ; i++){ if(args[i].equals("-?") || args[i].equalsIgnoreCase("-h") || args[i].equalsIgnoreCase("-help")){ //print out help/usage System.out.print(USAGE); System.exit(0); }else if(args[i].equalsIgnoreCase("-con")){ //console input of a string to convert to duck script //escape input with ctrl + z character console = true; }else if(args[i].equalsIgnoreCase("-i")){ //input a file to convert to duck script try{ input = readFile(args[i + 1]); //System.out.println(fileContents); }catch(IOException ex){ex.printStackTrace();} }else if(args[i].equalsIgnoreCase("-o")){ //output duck script representation to a file. outputFile = args[i + 1]; } }//end loop //get command line prompt input. if(console = true){ input = getConsoleInput(); //System.out.println(input); } try{ duckScript = toDuckScript(input, (new File(outputFile)).getName()); }catch(NullPointerException ex){ duckScript = toDuckScript(input, "BATCH.bat"); //could make name random } if(outputFile == null){ //if there's no output file, print to console. System.out.println(); System.out.println(duckScript); } else if(outputFile != null){ writeString(duckScript, outputFile); } }else{ //run in GUI mode System.out.println("args < 0"); } }//end main public static void writeString(String str, String outFile){ try{ BufferedWriter out = new BufferedWriter(new FileWriter(outFile)); out.write(str); out.close(); }catch(IOException ex){ ex.printStackTrace(); } }//end method writeString() public static String toDuckScript(String input, String fileName){ StringBuffer output = new StringBuffer(); String toks[] = input.split("(?<=[\\n]+)"); Formatter fmt = new Formatter(output); //The Formatter object is the sprintf() for java programmers. fmt.format("REM INPUT FILE %s%n", fileName); fmt.format("STRING copy con %s%n", fileName); for(String tok : toks) fmt.format("%s%s%s", "STRING ", tok.endsWith("\n") ? tok :tok + System.getProperty("line.separator"), "ENTER" + System.getProperty("line.separator")); //The formatter object appends to the StringBuffer object. /*Ternary operator is described as an inline if() statement. * BoolOperator ? TrueArg : FalseArg*/ /*CONTROL z *ENTER*/ fmt.format("CONTROL Z%nEnter%n", null); fmt.flush(); fmt.close(); return output.toString(); }//end method toDuckScript() //http://stackoverflow.com/questions/5837823/read-input-until-controld //getConsoleInput() inspired by code at stackoverflow.com public static String getConsoleInput(){ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuffer out = new StringBuffer(); /*Bug in this code... * If ctrl+z is on a line by its self, java will not interpret it * as a ctrl+z character for some reason, if the ctrl+z character is * adjacent to text, the exit condition works just fine. */ while(true){ try{ int c = in.read(); if(c != 26)//!ctrl + z out.append((char)c); else break; }catch(IOException ex){ ex.printStackTrace(); } }//end loop return out.toString(); }//end method getConsoleInput() public static String readFile(String fileName) throws IOException{ BufferedReader in = new BufferedReader(new FileReader(fileName)); StringBuffer fileContents = new StringBuffer();//mutable string String line; while((line = in.readLine()) != null){ fileContents.append(line); fileContents.append('\n');//apparently readLine does'nt append the '\n' }//end loop in.close(); return fileContents.toString(); }//end method readFile() }//end class Edited February 17, 2013 by midnitesnake Quote
overwraith Posted August 20, 2012 Author Posted August 20, 2012 (edited) Finally finished the full java solution feel free to modify, or improve. Use the -help/-h/-H/-? command line flags for directions on how to use. When inputting a string on the command prompt using the -con flag, remember that the ctrl+z character must be adjacent to the last line of text you wish to input. There is a slight bug in the code that does not allow the ctrl+z character to be recognized if on a line by its self.***File: ToDuckScript.java*** import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Formatter; import java.io.File; import java.io.FileWriter; import javax.swing.JFrame; public class ToDuckScript { static final String USAGE = "ToDuckScript.java\n" + "\n" + "Usage:\n" + "ToDuckScript Runs the GUI interface.\n" + "ToDuckScript -i [file ..] Specifies input file.\n" + "ToDuckScript -i [file ..] -o [file ..] Specifies input & output files.\n" + "ToDuckScript -con Input string using the console.\n" + "ToDuckScript -con -o [file ..] Console input paired with file.\n" + "ToDuckScript -?/-h/-H/-help Displays the help screen.\n" + "\n" + "Arguments:\n" + "-i [file ..] Input file.\n" + "-o [file ..] Output file.\n" + "-con Console string input.\n" + "-?/-h/-H/-help Help Screen.\n" + "\n" + "Output method can be omitted to display the output screen to the command prompt."; public static void main(String[] args){ String input = null; String outputFile = null; String duckScript = null; boolean console = false; //bool console determines whether or not are inputting to the console. if (args.length > 0){//run in command line mode //Get command line input first. for(int i = 0 ; i < args.length ; i++){ if(args[i].equals("-?") || args[i].equalsIgnoreCase("-h") || args[i].equalsIgnoreCase("-help")){ //print out help/usage System.out.print(USAGE); System.exit(0); }else if(args[i].equalsIgnoreCase("-con")){ //console input of a string to convert to duck script //escape input with ctrl + z character console = true; }else if(args[i].equalsIgnoreCase("-i")){ //input a file to convert to duck script try{ input = readFile(args[i + 1]); //System.out.println(fileContents); }catch(IOException ex){ex.printStackTrace();} }else if(args[i].equalsIgnoreCase("-o")){ //output duck script representation to a file. outputFile = args[i + 1]; } }//end loop //get command line prompt input. if(console = true){ System.out.println("Please Input commands to convert to duck script: "); input = getConsoleInput(); } try{ duckScript = toDuckScript(input, (new File(outputFile)).getName()); }catch(NullPointerException ex){ duckScript = toDuckScript(input, "BATCH.bat"); //could make name random } if(outputFile == null){ //if there's no output file, print to console. System.out.println(); System.out.println(duckScript); } else if(outputFile != null){ writeString(duckScript, outputFile); } }else{ //run in GUI mode JFrame frame = new ToDuckScriptUI(); } }//end main public static void writeString(String str, String outFile){ try{ BufferedWriter out = new BufferedWriter(new FileWriter(outFile)); out.write(str); out.close(); }catch(IOException ex){ ex.printStackTrace(); } }//end method writeString() public static String toDuckScript(String input, String fileName){ StringBuffer output = new StringBuffer(); String toks[] = input.split("(?<=[\\n]+)"); Formatter fmt = new Formatter(output); //The Formatter object is the sprintf() for java programmers. fmt.format("REM INPUT FILE %s%n", fileName); fmt.format("STRING copy con %s%n", fileName); for(String tok : toks) fmt.format("%s%s%s", "STRING ", tok.endsWith("\n") ? tok :tok + System.getProperty("line.separator"), "ENTER" + System.getProperty("line.separator")); //The formatter object appends to the StringBuffer object. /*Ternary operator is described as an inline if() statement. * BoolOperator ? TrueArg : FalseArg*/ /*CONTROL z *ENTER*/ fmt.format("CONTROL Z%nEnter%n", null); fmt.flush(); fmt.close(); return output.toString(); }//end method toDuckScript() //http://stackoverflow.com/questions/5837823/read-input-until-controld //getConsoleInput() inspired by code at stackoverflow.com public static String getConsoleInput(){ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuffer out = new StringBuffer(); /*Bug in this code... * If ctrl+z is on a line by its self, java will not interpret it * as a ctrl+z character for some reason, if the ctrl+z character is * adjacent to text, the exit condition works just fine. */ while(true){ try{ int c = in.read(); if(c != 26)//!ctrl + z out.append((char)c); else break; }catch(IOException ex){ ex.printStackTrace(); } }//end loop return out.toString(); }//end method getConsoleInput() public static String readFile(String fileName) throws IOException{ BufferedReader in = new BufferedReader(new FileReader(fileName)); StringBuffer fileContents = new StringBuffer();//mutable string String line; while((line = in.readLine()) != null){ fileContents.append(line); fileContents.append('\n');//apparently readLine does'nt append the '\n' }//end loop in.close(); return fileContents.toString(); }//end method readFile() }//end class ***File: ToDuckScriptUI.java*** import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.ScrollPaneConstants; import javax.swing.JButton; import javax.swing.SwingUtilities; import javax.swing.JOptionPane; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.io.File; import java.io.IOException; import javax.swing.JFrame; public class ToDuckScriptUI extends JFrame{ public static void main(String [] args){ JFrame frame = new ToDuckScriptUI(); frame.setVisible(true); }//end main public ToDuckScriptUI(){ JPanel panel = new DuckScriptPanel(); this.add(panel); this.pack(); this.setTitle("ToDuckScript"); this.setResizable(false); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); this.setVisible(true); }//end constructor }//end class ToDuckScriptUI class DuckScriptPanel extends JPanel implements ActionListener{ private JTextField txtSrc, txtDest; private JTextArea txtAreaInput, txtAreaDuckScript; private JButton btnEnter, btnClear, btnSave, btnExit; private String fileName, destFile; private String input, duckScript; public DuckScriptPanel(){ this.setLayout(new GridBagLayout()); //Row 1 this.add(new JLabel("Src File: "), getConstraints(0, 0, 1, 1, GridBagConstraints.CENTER)); this.add(txtSrc = new JTextField(15), getConstraints(1, 0, 1, 1, GridBagConstraints.CENTER)); this.add(new JLabel("Dest File: "), getConstraints(2, 0, 1, 1, GridBagConstraints.CENTER)); this.add(txtDest = new JTextField(15), getConstraints(3, 0, 1, 1, GridBagConstraints.CENTER)); //Row 2 this.add(new JLabel("String Input: "), getConstraints(0, 1, 1, 1, GridBagConstraints.CENTER)); this.add(new JLabel("Duck Script: "), getConstraints(2, 1, 1, 1, GridBagConstraints.CENTER)); //Row 3 txtAreaInput = new JTextArea(10, 25); txtAreaInput.setLineWrap(true); this.add(new JScrollPane(txtAreaInput, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS , ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER), getConstraints(0, 2, 2, 2, GridBagConstraints.CENTER)); txtAreaDuckScript = new JTextArea(10, 25); txtAreaDuckScript.setLineWrap(true); this.add(new JScrollPane(txtAreaDuckScript, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS , ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER), getConstraints(2, 2, 2, 2, GridBagConstraints.CENTER)); //Row 5 //Buttons arranged from most to least used. this.add(btnEnter = new JButton("Enter"), getConstraints(0, 4, 1, 1, GridBagConstraints.CENTER)); btnEnter.addActionListener(this); this.add(btnClear = new JButton("Clear"), getConstraints(1, 4, 1, 1, GridBagConstraints.CENTER)); btnClear.addActionListener(this); this.add(btnSave = new JButton("Save"), getConstraints(2, 4, 1, 1, GridBagConstraints.CENTER)); btnSave.addActionListener(this); this.add(btnExit = new JButton("Exit"), getConstraints(3, 4, 1, 1, GridBagConstraints.CENTER)); btnExit.addActionListener(this); }//end constructor //a method for setting grid bag constraints private GridBagConstraints getConstraints( int gridx, //column int gridy, //row int gridwidth, //number of additional columns component uses int gridheight, //number of additional rows component uses int anchor) { //used to modify alignment. GridBagConstraints c = new GridBagConstraints(); c.insets = new Insets(5, 5, 5, 5); c.ipadx = 0;//padding around the component vertically c.ipady = 0;//padding around the component horizontally c.gridx = gridx;//column c.gridy = gridy;//row c.gridwidth = gridwidth;//number of additional columns component uses c.gridheight = gridheight;//number of additional rows component uses c.anchor = anchor;//The last parameter, used to modify alignment return c; }//end getConstraints METHOD @Override public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if(source == btnEnter){ if(!txtSrc.getText().equals("")){ //Given File Name. fileName = txtSrc.getText(); try{ input = ToDuckScript.readFile(fileName); txtAreaInput.setText(input); duckScript = ToDuckScript.toDuckScript(input, (new File(fileName)).getName()); txtAreaDuckScript.setText(duckScript); return; }catch(IOException ex){ JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(this), "Unable to open specified file. ", "IO Error", JOptionPane.ERROR_MESSAGE); return; } }else if(!txtAreaInput.getText().equals("")){ //Given text in txtAreaInput input = txtAreaInput.getText(); fileName = "Batch.bat"; duckScript = ToDuckScript.toDuckScript(input, fileName); txtAreaDuckScript.setText(duckScript); return; }else{ JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(this), "Either the Src File, or String Input text boxes must have input. ", "User Error", JOptionPane.ERROR_MESSAGE); return; } } else if(source == btnClear){ txtSrc.setText(null); txtDest.setText(null); txtAreaInput.setText(null); txtAreaDuckScript.setText(null); fileName = null; destFile = null; input = null; duckScript = null; } else if(source == btnSave){ if(destFile != null) ToDuckScript.writeString(duckScript, destFile); else JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(this), "Please Input a destination and press Enter before pressing save. ", "Error", JOptionPane.ERROR_MESSAGE); } else if(source == btnExit){ System.exit(0); } }//end method actionPerformed() }//end class DuckScriptPanel Edited February 17, 2013 by midnitesnake formatting Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.