Can anyone please help me .
I have one java file that calls C++ code (which interacts with hardware device, i.e. a scanner to login into the application, that means on login window user does not have to enter username/password, just have to scan the badge). I am launching the java through .bat file in Windows 10. My java program is a JavaFx project. It does have a menu item as "Switch User", "Logout". That means if the user clicks on "Switch User", then application should exits and restart should happen (i.e. the login window).
Now When I launch the .bat file first time, the java is called perfectly and it calls my .dll file (which has C++ code) and scans the badge perfectly. If I click on Switch User, the java application exits, but it does not re-launch again. I can see the re-launch command in the command window, but it hangs from there.
Note: This working fine in Windows 7.
At this point of time, I don't have control over the C++ code. But if I required, I can request the concerned team.
Here is my code to call the C++, .dll
ScanReader.java
import com.sun.jna.Library;
import com.sun.jna.Native;
public class ScanReader {
private File dllFile;
public interface LoadDLL extends Library {
LoadDLL INSTANCE = (LoadDLL) Native.loadLibrary("ScanReaderCPP", LoadDLL.class);
int readCard();
}
public void loadDll(String name) throws IOException {
InputStream in = ScanReader.class.getResourceAsStream("/" + name);
byte[] buffer = new byte[1024];
int read = -1;
if (in == null ) return;
dllFile = new File(new File(System.getProperty("java.io.tmpdir")), name);
FileOutputStream fos = new FileOutputStream(dllFile);
while ((read = in.read(buffer)) != -1) {
fos.write(buffer, 0, read);
}
fos.close();
in.close();
System.setProperty("jna.library.path", dllFile.getParent());
}
public String readCard() {
try {
loadDll("ScanReader.dll");
} catch (IOException e1) {
e1.printStackTrace();
}
LoadDLL loadDLL = LoadDLL.INSTANCE;
cnum = loadDLL.readCard();
dllFile.delete();
loadDLL = null;
return String.valueOf(cnum);
}
}
RelaunchUtil.java
public class RelaunchUtil {
public static void restart() throws IOException {
try {
final String launchCommand = "C:\\MY_BATCH_FILES\\my_project.bat";
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
try {
Runtime.getRuntime().exec(launchCommand);
} catch (IOException e) {
e.printStackTrace();
}
}
});
System.exit(-1);
} catch (Exception e) {
e.printStackTrace();
throw new IOException("Error while trying to restart the application", e);
}
}
}
ScanReaderCPP.cpp
int ScanReaderCPP::readCard() {
HANDLE ghSemaphore;
DWORD dwWaitResult;
BOOL bContinue = TRUE;
Related
I have 4 jButtons that execute each specific program (Browsers for the time being), I need to make a conditional that tells a user that if a path to that specific program doesn't exist it will open a webpage with that specific browser in mind.
This piece of code repeats itself and I need to optimise it. I tried making another method where I would use if statement but instead it just gave me a lot of issues while executing each button.
Warning_MSG(); is just another method with jOptionPane to confirm if a user wants to open an external application, etc etc.
private void chromeMouseClicked(java.awt.event.MouseEvent evt) {
File file = new File("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe");
if(!file.exists()){
try {
URI url = new URI("https://google.com/chrome");
java.awt.Desktop.getDesktop().browse(url);
System.err.println("File Error, Google Chrome is not found!\n");
} catch (IOException | URISyntaxException e) {
System.err.println("Unknown Error, Exception found\n" + e);
}
}else {
Warning_MSG(file);
}
}
private void firefoxMouseClicked(java.awt.event.MouseEvent evt) {
File file = new File("C:\\Program Files\\Mozilla Firefox\\firefox.exe");
if(!file.exists()){
try {
System.err.println("File Error, Mozilla Firefox is not found!\n");
URI url = new URI("https://www.mozilla.org/en-GB/firefox/download/thanks/");
java.awt.Desktop.getDesktop().browse(url);
} catch (IOException | URISyntaxException e) {
System.err.println("Unknown Error, Exception found\n" + e);
}
}else {
Warning_MSG(file);
}
}
private void ieMouseClicked(java.awt.event.MouseEvent evt) {
File file = new File("C:\\Program Files (x86)\\Internet Explorer\\iexplore.exe");
if(!file.exists()){
System.err.println("File Error, iExplorer is not found! \n");
}else {
Warning_MSG(file);
}
}
private void edgeMouseClicked(java.awt.event.MouseEvent evt) {
File file = new File("C:\\Windows\\SystemApps\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\\MicrosoftEdge.exe");
if(!file.exists()){
System.err.println("File Error, Microsoft Edge is not Found! \n");
}else {
Warning_MSG(file);
}
}
The question is, how can I optimise these pieces of code so that I don't have to repeat the same thing all over again with other programs but instead run certain things only when conditions are met?
You can create an enum with 2 parameters (exe path, download page)
enum Browser
{
Chrome("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", "https://google.com/chrome"),
Firefox("C:\\Program Files\\Mozilla Firefox\\firefox.exe", "https://www.mozilla.org/en-GB/firefox/download/thanks/"),
IExplorer("C:\\Program Files (x86)\\Internet Explorer\\iexplore.exe", "https://google.com/internet-explorer"),
Edge("C:\\Windows\\SystemApps\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\\MicrosoftEdge.exe", "https://google.com/download-edge");
private final String _filePath, _downloadPageURL;
Browser(String filePath, String downloadPage)
{
_filePath = filePath;
_downloadPageURL = downloadPage;
}
private String getDownloadPageURL()
{
return _downloadPageURL;
}
private String getFilePath()
{
return _filePath;
}
public boolean exists()
{
return new File(getFilePath()).exists();
}
public void openDownloadPage()
{
try
{
Desktop.getDesktop().browse(new URI(getDownloadPageURL()));
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Then, all you have to do is a simple check at your methods.
private void chromeMouseClicked(java.awt.event.MouseEvent evt)
{
final Browser chrome = Browser.Chrome;
if (!chrome.exists())
{
chrome.openDownloadPage();
System.err.println("File Error, Google Chrome is not found!\n");
return;
}
// The browser exists at this line. So create your code
// ...
}
There is nothing wrong with the code but when i compiles it, the header of console shows this
<terminated> CopyFileToNewFile[Java Application]C:\Program Files\Java\jre1.8.0_45\bin\javaw.exe
package com.princess;
public class CopyFileToNewFile {
public static void main(String[] args)
{
try(
FileInputStream in = new FileInputStream("myfile.txt");
FileOutputStream out = new FileOutputStream("new.txt");
) {
int c;
while((c=in.read())!=-1)
{
out.write(c);
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
}
}
I am using JAVA 1.7 version also i'm not used to with Eclipse
<terminated> in Eclipse simply means the program finished executing, not that something went wrong.
If you want to keep the program "alive", you have to make it wait for something, like user input, Thread.sleep(), or something else.
I try to code a Java program which uses Drozer (a tool written in Python to test vulnerabilities in Android app). I need to execute commands directly from Java and so far everything goes pretty well, but I have a problem when an interavtive session of drozer starts. It seems that the problem occurs when EOF needs to be handled, since ctrl + D also can't stop the session. Here is what I get after hitting ctrl + D
*** Unknown syntax: EOF
Here is the code I use to connect from Java to Drozer, after running it, my program starts infinite loop printing the same error: *** Unknown syntax: EOF.
Any other command works like a charm. Any ideas what do I do wrong?
Cheers
public class test1 {
public static void main(String a[]) throws InterruptedException, IOException {
List<String> commands = new ArrayList<String>();
List<String> commands1 = new ArrayList<String>();
commands.add("/usr/local/bin/drozer");
commands.add("console");
commands.add("connect");
ProcessBuilder pb = new ProcessBuilder(commands);
pb.redirectErrorStream(true);
try {
Process prs = pb.start();
Thread inThread = new Thread(new In(prs.getInputStream()));
inThread.start();
Thread.sleep(1000);
OutputStream writeTo = prs.getOutputStream();
writeTo.write("oops\n".getBytes());
writeTo.flush();
writeTo.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
class In implements Runnable {
private InputStream is;
public In(InputStream is) {
this.is = is;
}
#Override
public void run() {
try {
byte[] b = new byte[1024];
int size = 0;
while ((size = is.read(b)) != -1) {
System.out.println(new String(b));
}
is.close();
} catch (IOException ex) {
Logger.getLogger(In.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I'm trying to enter some value in external application using Java.
Java application looks like this:
Runtime runtime = Runtime.getRuntime();
// ... str build ...
proc = runtime.exec(str);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
bw.write(value);
bw.flush();
bw.close();
if (proc.waitFor() != 0)
// error msg
// the end
Application hangs at waitFor method.
External application looks like this:
welcome banner
please enter 8 character input:
Welcome banner is printed using printf and input is taken with SetConsoleMode/ReadConsoleInput. ReadConsoleInput reads one char and they are masked with * character.
Help
you can use:
proc.getOutputStream().write("some date".getBytes())
keep in mind that you HAVE to read everything the app send to stdout and stderr, else it might get stuck writing there.
I use a generic class to read it in a different thread.
usage is like:
InputStreamSucker inSucker = new InputStreamSucker(proc.getInputStream());
InputStreamSucker errSucker = new InputStreamSucker(proc.getErrorStream());
proc.waitFor();
int exit = process.exitValue();
inSucker.join();
errSucker.join();
InputStreamSucker code is here:
public class InputStreamSucker extends Thread
{
static Logger logger = Logger.getLogger(InputStreamSucker.class);
private final BufferedInputStream m_in;
private final ByteArrayOutputStream m_out;
private final File m_outFile;
public InputStreamSucker(InputStream in) throws FileNotFoundException
{
this(in, null);
}
public InputStreamSucker(InputStream in, File outFile) throws FileNotFoundException
{
m_in = new BufferedInputStream(in, 4096);
m_outFile = outFile;
m_out = new ByteArrayOutputStream();
start();
}
#Override
public void run()
{
try
{
int c;
while ((c = m_in.read()) != -1)
{
m_out.write(c);
}
}
catch (IOException e)
{
logger.error("Error pumping stream", e);
}
finally
{
if (m_in != null)
{
try
{
m_in.close();
}
catch (IOException e)
{
}
}
try
{
m_out.close();
}
catch (IOException e)
{
logger.error("Error closing out stream", e);
}
if (m_outFile != null)
{
byte data[] = m_out.toByteArray();
if (data.length > 0)
{
FileOutputStream fo = null;
try
{
fo = new FileOutputStream(m_outFile);
fo.write(data);
}
catch (IOException e)
{
logger.error("Error writing " + m_outFile);
}
finally
{
try
{
if (fo != null) fo.close();
}
catch (IOException e)
{
logger.error("Error closing " + m_outFile);
}
}
}
}
}
}
public String getOutput()
{
return new String(m_out.toByteArray());
}
}
Got the answer! The trick is to use WriteConsoleInput() API because program expects keyboard event, not text ... That's why the waitFor() waited forever! :)
I need to read a bunch of binary files from a Java script running on Windows.
However, the folder that the files are in has limited permissions. I (i.e. my Windows username) have permissions to read them, but the user that Java runs as (this is part of a web application) does not. If I pass my own username and Windows network password into Java at runtime, is there a way I can read those files using my own permissions rather than the web user's?
(Note that this is NOT happening over the web; this is a one-time import script running in the context of a web application.)
You could create a network share and then connect via jCIFS
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFileInputStream;
public class Example
{
public static void main(String[] args)
{
SmbFileInputStream fis = null;
try
{
fis = new SmbFileInputStream("smb://DOMAIN;USERNAME:PASSWORD#SERVER/SHARE/filename.txt");
// handle as you would a normal input stream... this example prints the contents of the file
int length;
byte[] buffer = new byte[1024];
while ((length = fis.read(buffer)) != -1)
{
for (int x = 0; x < length; x++)
{
System.out.print((char) buffer[x]);
}
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (SmbException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (fis != null)
{
try
{
fis.close();
}
catch (Exception ignore)
{
}
}
}
}
}
If the files are on a network-share you could use the net tool. With
runtime.exec("net use ...")
to open and close the share. I guess that should work