I have a textarea through which user will write his code and when he press submit button then text should get compiled and result should be displayed.
Can anyone provide any API's available which I can use.?
More Details:
I have a form consisting of textarea where user can write code and submit.
On submit I want to compile this code through jsp page and return output message of compiler.
One more thing I do not Have file of submitted code, I have only string.
string code = request.getparameter("textareaCode");
So, is there any way to compile this code for any one languages ex. C, C++ or Java?
Is there any API's available which I can use to work it?
How to give system call through jsp pages so that I can compile the submitted code?
You can make use of run-time java compilation feature provided in JavaCompiler interface which accepts input/output stream.
Step 1. Convert contents submitted by text-area into input stream.
Step 2. JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
Step 3. Call compiler.run method by providing inputstream(you have created in step 1) as one argument. You can capture the output of compilation thru output stream as another argument.
You can execute command line commands using Runtime.getRuntime().exec("command");
For example if you want to compile a java file then try the following :
import java.io.*;
public class JavaRunCommand {
public static void main(String args[]) {
String s = null;
try {
// Logic to save textarea code into java file.
// then compile a java file "javac fileName.java" command
// using the Runtime exec method
Process p = Runtime.getRuntime().exec("javac fileName.java");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
System.exit(0);
}catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
System.exit(-1);
}
}
}
Related
I'm struggling to input value from Scanner option in Java to a txt file. while I can smoothly read the data using try{} catch{}, I cannot write the data from a scanner to the txt file. I can easily write data to txt file using PrintWriter, but that's not my goal... According to the scenario of the assignment, I have to create the system to input values and store the data text file, which I'm struggling to do.
Please help me with this problem, and provide me a solution...
This is my first Java project. Thanks
Scanner sc = new Scanner(System.in);
String data = sc.nextLine(); //taking input from user
// Use try with resource to release system resources
try ( FileWriter myWriter = new FileWriter("filename.txt"); ) {
myWriter.write(data); //writing into file
}
As you say you have successfully read (and maybe also manipulated) the data. Lets assume you have it ready to be written out as a String data and you also have a String filename of the file's intended name.
You can then do the following:
// generate the File object
File f = Paths.get("./" + filename).toFile();
f.delete(); // remove previous existing file -- equivalent to overwrite
try(BufferedWriter wr = new BufferedWriter(new FileWriter(f))){
wr.append(data); // adding the data into write buffer
wr.flush(); // writing the data out to the file
wr.close(); // closing the buffered writer
} catch (Exception e) {
e.printStackTrace();
}
I am trying to use Forge.min.js encryption method to encrypt one of my key, the encryption look like this in Javascript
EncryptPassword: function (Password, exponent,modulus)
{
modulus = new forge.jsbn.BigInteger(modulus,16);
exponent = new forge.jsbn.BigInteger(exponent, 16);
var publicKey = forge.pki.setRsaPublicKey(modulus, exponent);
return publicKey.encrypt(Password);
}
This is the function that i used in forge.min.js. My problem is that i cant load the js file in c# console, whenever i load the Js file using the method below :
MSScriptControl.ScriptControlClass sc = new MSScriptControl.ScriptControlClass();
sc.Language = "javascript";
sc.AddCode(File.ReadAllText(#"C:\forge-min.js"));
when i load the forge-min.js file using the above method in c# console, it goes to exception with message "Expected Identifier". My question is is there a method to encrypt in c# that produce the same result. Or is there a method that is able to load forge-min.js
*Note: forge-min.js file is in here https://cdnjs.cloudflare.com/ajax/libs/forge/0.9.1/forge.min.js
In my application I need to show information about files as a friendly readable string, based on the file's MIME String. I have the information I need (FYI taken from /usr/share/mime/package/freedesktop.org.xml on Ubuntu 14.04), and I'd like to put everything as a static map<"String","MIMEInfoObject">.
protected class MIMEInfoObject {
//Getters ...
//Setters ...
...
private String mimeType; //Example: "application/pdf
private String defaultDescription; // "PDF document"
private String localDescription; // "Documento PDF"
private String acronym; // "PDF"
private String extendedAcronym; // "Portable Document Format"
private List<String> extensionList; // "pdf .."
private List<String> aliasList; // "application/x-pdf, application/acrobat, ... "
}
I made a shell script that outputs the linux file like this:
<mime-type type="image/vnd.adobe.photoshop">
<comment>Photoshop image</comment>
<comment xml:lang="pt_BR">Imagem do Photoshop</comment>
<glob pattern="*.psd"/>
<alias type="image/psd"/>
<alias type="image/x-psd"/>
<alias type="image/photoshop"/>
<alias type="image/x-photoshop"/>
<alias type="application/photoshop"/>
<alias type="application/x-photoshop"/>
++++END+++
and I used that output in another shell script that generates java code like this:
MIMEInfoObject obj;
obj.setMimeType("application/pdf");
obj.setDefaultDescription("PDF document");
obj.setLocalDescription("Documento PDF");
obj.setAcronym("PDF");
obj.setExtendedAcronym("Portable Document Format");
if (obj.getExtensionList() == null) {
obj.setExtensionList(new ArrayList<String>());
}
extList = obj.getExtensionList();
extList.add("*.pdf");
obj.setExtensionList(extList);
if (obj.getAliasList() == null) {
obj.setAliasList(new ArrayList<String>());
}
aliasList = obj.getAliasList();
aliasList.add("application/x-pdf");
obj.setAliasList(aliasList);
if (obj.getAliasList() == null) {
obj.setAliasList(new ArrayList<String>());
}
aliasList = obj.getAliasList();
aliasList.add("image/pdf");
obj.setAliasList(aliasList);
if (obj.getAliasList() == null) {
obj.setAliasList(new ArrayList<String>());
}
aliasList = obj.getAliasList();
aliasList.add("application/acrobat");
obj.setAliasList(aliasList);
mimeString2Obj.put(obj.getMimeType(), obj);
for (String alias : obj.getAliasList()) {
mimeString2Obj.put(alias, obj);
}
I know the code above is stupid, but it's how I can generate it, but the problem is that it generates about 17000 lines of code like that. Java is complaining about the method's bytes limit, which is 65535, and it's exceeded.
My concern is if anyone has a better idea of how to do this, taking in mind that I'm using GWTP (so I can use JavaScript although I'm not an expert) and my application will run both on Desktop/Mobile browsers and Mobile App (phonegap).
Thanks in advance.
The problem if I understand it correctly is that you're generating java code to explicitly load each object, as opposed to reusing java code to load objects from a data file. Don't do that. If you have more files, for instance, you would have to regenerate your code etc.
You need to create some kind of standardized data file, and create a method to read it. So if your data is CSV, or XML, then you can dump then in one/many files, and then it doesn't matter how much data you have, the java code will look the same. Just a simple loop which keeps reading and loading stuff in your map.
in pseudocode:
while (records.hasMoreRecords()) {
records.read()...
add record to map()
}
Is it possible to execute external bash script and set another file as input for it using Rhino?
e.g. I need to rewrite bash script(exec.sh) with following content:
somescript.sh <fileInput.txt
I've tried many ways but without success:
Reading fileInput.txt as input stream and passing to shell:
var inputStream = new java.io.InputStream(fileInput.txt);
runCommand( "somescript.sh", inputStream);
Writing "somescript.sh <fileInput.txt" to additional bash script and calling runCommand():
message = new FileUtils.writeStringToFile(helpfulScript, "somescript.sh
runCommand("bash", helpfulScript.getCanonicalPath());
Sorry for pure highlight and thanks in advice for any ideas.
You need to pass the input stream in as the input property of an object.
var inputStream = new java.io.FileInputStream("fileInput.txt");
runCommand("somescript.sh", { input: inputStream });
If input is not an InputStream it will be converted to a string and sent to the command directly. Similarly, you can add output and/or err properties to capture the command's standard output and standard error (documentation here).
Following this SO solution here to notify clients of a click event in a PDF document, how is it possible to notify the client when the PDF gets submitted by the client using this.myPDF.submitForm("localhost/Handler.ashx?r=2) function?
The PDF File is created inside a user control then rendered into a HTML object:
string container = ("<object data='/myfile.pdf' type='application/pdf'></object>");
The JS file attached to the PDF is done like this:
var webClient = new WebClient();
string htmlContent = webClient.DownloadString(fileurl + "pdf_script.js");
PdfAction action = PdfAction.JavaScript(htmlContnent, pdfstamper.Writer);
pdfstamper.Writer.SetOpenAction(action);
And the content of the js file:
this.disclosed = true;
if (this.external && this.hostContainer) {
function onMessageFunc(stringArray) {
try {
this.myPDF.submitForm("http://localhost/Handler.ashx?EmpNo=12345" + "#FDF", false);
}
catch (e) {
}
}
function onErrorFunc(e) {
console.show();
console.println(e.toString());
}
try {
if (!this.hostContainer.messageHandler);
this.hostContainer.messageHandler = new Object();
this.hostContainer.messageHandler.myPDF = this;
this.hostContainer.messageHandler.onMessage = onMessageFunc;
this.hostContainer.messageHandler.onError = onErrorFunc;
this.hostContainer.messageHandler.onDisclose = function () { return true; };
}
catch (e) {
onErrorFunc(e);
}
}
When the submitForm call is made the PDF contents (form fields) get saved successfully and an alert is displayed in the PDF by doing this:
message = "%FDF-1.2
1 0 obj
<<
/FDF
<<
/Status("Success!")
>>
>>
endobj
trailer
<</Root 1 0 R>>
%%EOF");
return message;
What I'm trying to do is to get the PDF to callback the client after the form submit call sent from this client, a way to acknowledge the client that the form has been submitted, not in a form of an alert, but rather, a way to trigger a function in the host (the container, an iframe, object...etc).
The FDF response you used was unknown to me, so I've learned something new from your question. I've studied the AcroJS Reference and the FDF specification in the PDF Reference, and now I have a better understanding of what your code does. Thank you for that.
I assume that you already know how to trigger a JavaScript message in an HTML file using a JavaScript call from a PDF. See the createMessageHandler() in the JavaScript Communication between HTML and PDF article.
I interpret your question as: "How to I invoke this method after a successful submission of the data?"
If there's a solution to this question, it will involve JavaScript. I see that one can add JavaScript in an FDF file, but I'm not sure if that JavaScript can 'talk to' HTML. I'm not sure if you can call a JavaScript function in your initial PDF from the FDF response. If it's possible, you should add a JavaScript entry to your PDF similar to the /Status entry.
The value of this entry is a dictionary, something like:
<<
/Before (app.alert\("before!"\))
/After (app.alert\("after"\))
/Doc [/MyDocScript1, (myFunc1\(\)),
/MyDocScript2, (myFunc2\(\))
>>
In your case, I would remove the /Before and /Doc keys. I don't think you need them, I'd reduce the dictionary to:
<<
/After (talkToHtml\(\))
>>
Where talkToHtml() is a method already present in the PDF:
function talkToHtml() {
var names = new Array();
names[0] = "Success!";
try{
this.hostContainer.postMessage(names);
}
catch(e){
app.alert(e.message);
}
}
I don't know if this will work. I've never tried it myself. I'm basing my answer on the specs.
I don't know if you really need to use FDF. Have you tried adding JavaScript to your submitForm() method? Something like:
this.myPDF.submitForm({
cURL: "http://localhost/Handler.ashx?EmpNo=12345",
cSubmitAs: "FDF",
oJavaScript: {
Before: 'app.alert("before!")',
After: 'app.alert("after")',
Doc: ["MyDocScript1", "myFunc1()",
"MyDocScript2", "myFunc2()" ]
}
});
This will only work if you submit as FDF. I don't think there's a solution if you submit an HTML query string.
In case you're wondering what MyDocScript1 and MyDocScript2 are:
Doc defines an array defining additional JavaScript scripts to be
added to those defined in the JavaScript entry of the document’s name
dictionary. The array contains an even number of elements, organized
in pairs. The first element of each pair is a name and the second
is a text string or text stream defining the script corresponding
to that name. Each of the defined scripts is added to those already
defined in the name dictionary and then executed before the script
defined in the Before entry is executed. (ISO-32000-1 Table 245)
I'm not sure if all of this will work in practice. Please let me know either way.