Running Javascript Code Used to Run on NodeJS [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a code that is running on NodeJs. We would like to change the technology (to java).
The problem is we have some existing passwords, and I am not sure how to I copy the encryption logic to java.
So, one of the possible solutions is to run the encryption logic in javascript (e.g. command line, embbeded in the java, etc) and get the result back.
The question is - how do I do that?
The nodejs code goes like this:
crypto = require('crypto');
this.salt = this.makeSalt();
encryptPassword: function(password) {
var salt = new Buffer(this.salt, 'base64');
return crypto.pbkdf2Sync(password, salt, iterations, keylen).toString('base64');
crypto.randomBytes(..)
}
makeSalt: function() {
return crypto.randomBytes(numOfBytes).toString('base64');
},
UPDATE:
Following the suggestions here, I added the full code. If the right way of doing it is by transforming the javascript code to java code, can you please help me translated the above code?

You should not do this, if you want random bytes in Java do this. You should be able to replicate the encryption logic in Java.
byte[] b = new byte[20];
new Random().nextBytes(b);
Almost all of the Node.js crypto functions are generic, and should have their own Java counterparts or 3rd party libraries.
Update
If you must run your node code via java you can add this method
public static String runCommand(String command) {
String output = "";
try {
String line;
Process process = Runtime.getRuntime().exec( command );
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()) );
while ((line = reader.readLine()) != null) {
output += line;
}
reader.close();
} catch (Exception exception) {
// ...
}
return output;
}
and run it like this
String encryptedPassword = runCommand("node myEncryption.js --password=1234");

Related

Formatting data and inputting to a database in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am getting hardware data from cmd using a process builder in java.
//get info from cmd
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("cmd.exe", "/c", "systeminfo ");
try {
Process process = processBuilder.start();
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
//write the output to the variables
String line;
//a loop which ensures all the data is read in
while ((line = reader.readLine()) != null) {
hardwareInfo.add(line);//hardwareInfo is an arraylist i currently save all this information to
}
This returns all the relevant information and more. my output looks like the following:
[, Host Name: LJDESKTOP, OS Name: Microsoft Windows 10 Education, OS Version: 10.0.18363 N/A Build 18363
etc...
I want to add some of these fields into an SQL database based on their names(e.g. Host Name: - yes, OS Name: - No). The SQL connection is set up I just need to find the best way to save these varibles so I can insert them straight into my database.
So how do I get rid of the Host Name: and still enter LJDESKTOP into my database and the same principle for the rest of the information I get from the cmd command.
I am also trying to consider efficiency, I want this to be as computationally "light" as possible but this isn't essential.
What I have tried so far:
I have tried splitting the string at the ":" for each varible and trimming. This gives me exactly the information I need but then I can't save it to individual variables. This is because the bit I trimmed is how I determine what my varibles are. (Could I potentially add the trim function to my setter?)
I have tried:
while ((line = reader.readLine()) != null) {
if (line.startsWith("Host Name:")) {
setHostname(line.replaceFirst("Host Name: ", ""));}
the if statements are repeated for each variable, however everytime this adds each variable to my array everytime it goes through the while loop.
You can try it like this:
...
final Map<String,String> inputValues = new HashMap<>();
//a loop which ensures all the data is read in
while ((line = reader.readLine()) != null) {
// Read each line as key and value into a the inputValues map
final String[] pieces = line.split(":",2); // only split at the first ':'!
// Was a ':' found, e.g. the string split into two pieces?
if ( pieces.length > 1 ) {
String key = pieces[0]; // e.g. "Host Name"
String value = pieces[1]; // e.g. " LJDESKTOP"
value = value.trim(); // remove leading/trailing whitespaces from value
inputValues.put(key,value); // Store key+value to map.
}
}
// Now we can access the input values by key, e.g.:
String hostName = inputValues.get("Host Name");
String osName = inputValues.get("OS Name");
// To do: Do something with the values above, e.g. send to DB...

How to run Microsoft access macro from Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
We are using Access database for a project along with Java. We have some Macros in Access database and we need to run those from Java. Is there any way to execute those macros from Java?
The following code works for me in NetBeans 8 on Windows 8.1. It writes a temporary VBScript file and then runs it using cscript.exe:
package runaccessmacro;
import java.io.*;
public class RunAccessMacro {
public static void main(String[] args) {
String dbFilePath = "C:\\Users\\Public\\Database1.accdb";
String vbsFilePath = System.getenv("TEMP") + "\\javaTempScriptFile.vbs";
File vbsFile = new File(vbsFilePath);
PrintWriter pw;
try {
pw = new PrintWriter(vbsFile);
pw.println("Set accessApp = CreateObject(\"Access.Application\")");
pw.println("accessApp.OpenCurrentDatabase \"" + dbFilePath + "\"");
pw.println("accessApp.DoCmd.RunMacro \"doRidLogUpdate\"");
pw.println("accessApp.CloseCurrentDatabase");
pw.println("accessApp.Quit");
pw.close();
Process p = Runtime.getRuntime().exec("cscript /nologo \"" + vbsFilePath + "\"");
p.waitFor();
BufferedReader rdr =
new BufferedReader(new InputStreamReader(p.getErrorStream()));
int errorLines = 0;
String line = rdr.readLine();
while (line != null) {
errorLines++;
System.out.println(line); // display error line(s), if any
line = rdr.readLine();
}
vbsFile.delete();
if (errorLines == 0) {
System.out.println("The operation completed successfully.");
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
Notes:
This will only work on a Windows machine with Microsoft Access (the actual application, not just the Access Database Engine) installed.
The "bitness" of the JVM under which the Java code runs should match the "bitness" of the version of Access installed (i.e., both 64-bit or both 32-bit).
Some tweaking may be required under certain circumstances, e.g., Java code being executed by a web server may be prohibited from shelling out to cscript.exe by default.

make java communicate with a C++ program [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a C++ program which uses command line as its mean for IO. I don't know C++, nor do I have the program's source code. I want my java application to open the C++ program , give some input and gather the result from the C++ code. Is there a way?
UPDATE: I need to enter the input at runtime.
You can use java.lang.Runtime
For example:
public class TestRuntime {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("test.bat");
// test.bat or test.sh in linux is script with command to run (c++) program
// or direct path to application's exec
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In addition, you can read about difference between Runtime and ProcessBuilder in this topic.

reading both stdin and arguments from command line java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm having trouble reading both arguments and stdin from the command line when running a java file. I can read in arguments on their own and stdin on it's own but not together; for example:
java myFile 6 2 < numbers.txt
I can get it to store 6 and 2 in an array but then it just stores "<" and "text.txt" also. I've been unable to find anything online describing a similar problem so not really sure where to begin.
Command-line arguments are received in the String[]-typed parameter of the main method. Input redirection is done the same as for any other process invoked at the command line. The bytes can be retrieved by reading from stdin until EOF is reached.
Command: java myClass myArg < myFile
public static void main(String[] args)
{
System.out.println("Arg 1 = " + args[0] + "\nStdin = ");
try (InputStreamReader isr = new InputStreamReader(System.in)) {
int ch;
while((ch = isr.read()) != -1)
System.out.print((char)ch);
}catch(IOException e) {
e.printStackTrace();
}
}
For more info:
http://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html
http://docs.oracle.com/javase/tutorial/essential/io/cl.html

How to retrieve specific information from a certain website? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am developing a java web application and I want to know how to take a certain field (table and/or output-text) value from a certain website. Assuming that this component has always the same ID does anyone know how can I retrieve this information?
I don't know if anyone has ever faced this issue but if anyone has any idea please share.
Thank you.
In general:
1.) Retrieve the pages markup by reading it through an HTTPConnection to the URL in your application
2.) Parse the Markup using a framework like jsoup and retrieve the value you need.
More specifically, here is some example code for jsoup:
HttpClient http = new DefaultHttpClient();
String htmlcode = "";
HttpGet request = new HttpGet("http://www.example.com");
HttpResponse response = null;
try {
response = http.execute(request);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(response != null){
BufferedReader read = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while((line = read.readLine()) != null){
htmlcode += line;
}
}
// at this point we have the pages markup
Document doc = Jsoup.parse(htmlcode);
Elements lis = doc.getElementsByTag("li"); // get all entries in lists
for(Element el : lis){
String val = el.text().trim();
// do something for each list entry
}
You are talking about web scraping, check this library for php:
http://simplehtmldom.sourceforge.net/

Categories