I'm trying to execute cmd command in Java applet, I tried this code
import java.io.InputStream;
import java.io.IOException;
import java.applet.Applet;
import java.awt.*;
public class execute extends Applet{
String output="";
public void init(){
try {
// Execute command
String command = "MYCMDCOMMAND";
Process child = Runtime.getRuntime().exec(command);
// Get the input stream and read from it
InputStream in = child.getInputStream();
int c= in.read();
while ((c = in.read()) != -1) {
output =output+((char)c);
}
in.close();
}
catch (IOException e) {
}
System.out.println(output);
}
public void paint(Graphics g){
g.drawString(output,60,100);
}
}
And then wrote this html file and saved it in the same directory:
<html>
<head><title>Applet</title>
<body>
<applet code="execute.class",height="200" width="200">
</body>
</html>
What I'm trying to do here is to run the ls shell command in an applet and display the results.
The code compiles with no errors. But when I open the html file in the browser, I just get a gray square.
Is this because of security issues that I don't get anything? Or is it because of an error in the code?
You must be careful about some things.
You have to Copy & paste your Html file to .bin file after you compiled
Your HTML file name is Applet and your class name execute.class so it means you do not have package if u have you must save your html file as "PACKAGENAME/execute.class",
At Control Panel / Java you must disable Security
Related
I'm trying to run a python script whenever a button on my gui (swing) is pressed. However, the script never runs and I'm not sure how to fix this. I know the script works fine independently, it should be py not python because windows, and my file system ntfs.
So far I've been trying to use code that can be summarized as below:
myBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Process p = Runtime.getRuntime().exec("py myScript.py");
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
});
I don't think I can chmod ntfs stuff but I tried setting permissions via right clicking the python file and trying to mess with the security settings. Full control for the script to users does nothing.
The python script has the following permissions, my guess is my code isn't working because it does not have execute permissions.
-rw-r--r--
Use complete python executable path instead of "py". It executes the file with just read permissions.
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Sample {
public static void main(String[] args) throws Exception {
try {
Process p = Runtime.getRuntime().exec("C:/Windows/py myScript.py");
String cmdOutput = null;
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
// read the output from the command
while ((cmdOutput = stdInput.readLine()) != null) {
System.out.println(cmdOutput);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
myScript.py
print("This line will be printed.")
Output:
C:\Users\Administrator\Documents\demo>javac Sample.java
C:\Users\Administrator\Documents\demo>java Sample
This line will be printed.
I'm trying to get a Java applet to display in the browser - I know this question has been asked a number of times but I can't seem to find the answer that works specifically for this case - over the past few days I've tried everything from moving the HTML file to various places in the directory structure to using <applet> vs. the deployJava() API.
The code runs fine as a standalone applet in Eclipse, but when I try to run it in the browser I get either a "ClassNotFound" or "ClassDefNotFound" exception. I've packaged the code into a .jar and placed the .jar within the same folder as the HTML file, with my java code as follows:
package myPackage;
import java.awt.*;
import java.applet.*;
public class myClass extends java.applet.Applet{
public void init(){
String latLong = getParameter("unUsedParameter");
}
public void paint(Graphics g){
g.drawString("Hello World",50,25);
}
}
and the Javascript code is as follows:
<script src="https://www.java.com/js/deployJava.js"></script>
<section id = "java">
<script type="text/javascript">
var attributes = {
code:'myClass.class',
archive: 'myApplet.jar',
width:500, height:500
};
var parameters = {latLong: total_path};
var version = '1.8';
deployJava.runApplet(attributes, parameters, version);
</script>
</section>
I also tried using codebase: 'myApplet.jar' instead of archive: but that didn't work either - I keep getting one of the same two exceptions. HELP!
EDIT: First off, the code: attribute was incorrect in my original post, it should have read 'myClass.class' (this is corrected above). The answer that got it working was changing the code: attribute to code: 'myApplet/myClass' - thanks for your help!
Change your 'code' parameter to 'myPackage.myClass', instead of 'myApplet.class'.
You have more insights about the declaration in this post, which I've shown a way that works Angular.js and Java Applet
ie:
<script>
<!-- applet id can be used to get a reference to the applet object -->
var attributes = { id:'cdigApplet', code:'cdig.CDigApplet', archive:'cdig-applet-1.0.jar', width:1, height:1, classloader_cache:'false'} ;
var parameters = {persistState: false, cache_option:'no' } ;
deployJava.runApplet(attributes, parameters, '1.8');
</script>
My Applet
package cdig;
import java.applet.Applet;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Base64;
/**
*
* #author Ulysses Marins
*/
public class CDigApplet extends Applet
{
private static final long serialVersionUID = 1L;
String ret;
CDigApplet applet = this;
#SuppressWarnings({ "rawtypes", "unchecked" })
public String signFile(String fileID, String pin, String token)
{
AccessController.doPrivileged(new PrivilegedAction()
{
#Override
public Object run()
{
try
{
File objFile = new File(token);
System.out.println("Iniciando processo de assinatura.");
objFile.sign("json", sig);
System.out.println(ret);
} else {
throw new IllegalArgumentException("Não foi possível iniciar processo de assinatura.");
}
}
catch (Exception e)
{
String sl = "{\"success\":false," + "\"message\":\"" + e.getMessage() + "\"}";
ret = sl;
System.out.println(sl);
}
return null;
}
});
return ret;
}
public void init(){
}
public void destroy(){
}
}
Browsers are becoming more and more reluctant to run applets. Chrome itself won't support the java plugin anymore very soon. Additionally, Java itself is requiring more or more secured applications. Your version of Java matters a lot. Versions >=7 require signed applications.
What's more, the error messages when applets fail to run for these reasons are generally very cryptic or inexistant.
What's clear is that you at least need to self-sign your applet, and declare some properties in the jar's manifest, such as the fact that you want to run the code in a sandbox (which will relax a bit the security restrictions).
Problem: Java applet can't load resources located inside its jar when run locally on windows platforms. The same applet can load the resources if it is launched from a web server instead of launched locally or if it's launched locally on a linux system. In all cases the applet is launched using an applet tag.
Steps to reproduce
1) Build applet class code below and create a jar containing the following:
TestApplet.class
iconimg.png
test.html
META-INF folder (standard manifest with one line: "Manifest-Version: 1.0")
Here's a link to the image png file I used:
http://flexibleretirementplanner.com/java/java-test/iconimg.png
The file test.html has one line:
<h1>Text from test.html file</h1>
2) create launch.html in same folder as test.jar as follows:
<html><center><title>Test Applet</title><applet
archive = "test.jar"
code = "TestApplet.class"
name = "Test Applet"
width = "250"
height = "150"
hspace = "0"
vspace = "0"
align = "middle"
mayscript = "true"
></applet></center></html>
3) With test.jar in the same local folder as launch.html, click on launch.html
4) Notice that getResource() calls for imgicon.png and test.html both return null.
5) Upload launch.html and test.jar to a web server and load launch.html and notice that the resources are found.
TestApplet.java
import java.applet.AppletContext;
import java.io.IOException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TestApplet extends JApplet {
public TestApplet() {
try {
jbInit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void init() {
JPanel topPanel = new JPanel();
JLabel iconLabel;
URL url = TestApplet.class.getClassLoader().getResource("iconimg.png");
if (url != null)
iconLabel = new JLabel(new ImageIcon(url));
else
iconLabel = new JLabel("getResource(iconimg.png)==null");
topPanel.add(iconLabel);
URL url2;
url2 = TestApplet.class.getClassLoader().getResource("test.html");
if (url2 == null) {
JLabel errorLabel = new JLabel("getResource(test.html) == null");
topPanel.add(errorLabel);
} else {
try {
JEditorPane htmlPane = new JEditorPane(url2);
topPanel.add(htmlPane);
} catch (IOException ioe) {
System.err.println("Error displaying " + url2);
}
}
getContentPane().add(topPanel);
}
private void jbInit() throws Exception { }
}
Oracle has decided to modify the behavior of getDocumentBase(), getCodeBase() and getResource() because security reasons since 1.7.0_25 on Windows: http://www.duckware.com/tech/java-security-clusterfuck.html
It seems there is a lot of discussion about this change because it breaks some important valid and secure use cases.
After further research and discovering that this is a windows-only problem, I'm calling this one answered.
It's almost certainly a java 1.7.0.25 bug. The applet runs fine from a web server and also runs fine locally on a virtual Ubuntu system (using VirtualBox on windows). Hopefully the bug report i submitted will be helpful to the java folks.
Thanks for the responses. Btw, it was Joop's comment about case sensitivity that spurred me to test a linux system just for kicks. Thanks for that!
I want to write a Java program to delete ~12 directories or files which are under my home directory. I am able to do this by using
Process proc = Runtime.getRuntime().exec("rm -rf *path*")
But I have to run this command 12 times or I can keep it in loop. What I really want is to have a file in my home directory that contains the names of all the directories and files to delete in it. My Java program should go to the home directory, read the file, and delete all the specified files.
I am stuck at the very first step – I am not able to cd to the home directory. Please let me know how can I achieve this.
Thanks for all of your replies.
But, here I don't really want to use the Java util classes rather I want to learn a way using which I can run Linux commands in my Java class. Being a deployment Intern, I have to reset the environment every time before deploying a new environment for the customer. For this, I repeatedly use some basic Linux commands. I can write a shell script to do this but for this time, I want to write a Java class in which I can put all these Linux commands and run from one class.
The commands which I use are:
kill all java processes which are started by the admin ONLY – for this I need to use multiple Linux commands with “pipe”
Remove all 12-directories/files from home directory
stop some services (like siebel, etc.) – for this I need to go under the particular directories and run ./shutdown.sh or ./stop_ns, etc.
run some database scripts – to reset the database schemas
again start the services – same as step 2 except this time I need to run ./start_ns, etc.
I really appreciate if you can let me know
a. How can I navigate into a directory using Java code
b. How can I run multiple Linux commands using pipe using Java code
Why do you need to "go" to the home directory? Just read the file wherever you are:
String homeDirectory = System.getProperty("user.home");
File file = new File(homeDirectory, "filenames.txt"); // Or whatever
// Now load the file using "file" in the constructor call to FileInputStream etc
It's very rarely a good idea to require that a process changes working directory just to do the right thing.
You dont need to change directory. You can just read file using absolute path using FileReader(String fileName).
For deleting entire directories, try Apache Commons IO's class FileUtils:
FileUtils.deleteDirectory(new File(System.getProperty("user.home")));
Or use cleanDirectory to delete everything in home but not home itself:
FileUtils.cleanDirectory(new File(System.getProperty("user.home")));
If you want to delete specific files only (e.g. those matching a name pattern), list the files first, then delete them:
File startDir = new File(System.getProperty("user.home"));
//this should return the leaf files first, then the inner nodes of the directory tree
Collection<File> files = FileUtils.listFiles(startDir , someFileFiler, someDirFilter);
for(File f : files) {
f.delete();
}
"cd" is a shell internal command, not a executable program.
Even you can change dir in java program by whatever means like JNA, when it exit, the current dir in shell is not changed, because the java program runs in another process than the shell.
But we still can do something about it.
eg. I want to make a new shell command called xcd, it popup a GUI shows a list let you select directories existed in bash history, and change current dir to it for you.
in ~/.bashrc add a line:
xcd(){
XCDRES=`xcd.sh`
if [ "$XCDRES" ]; then
cd "$XCDRES"
fi
}
2.xcd.sh is
#!/bin/bash
java -cp $PATH1/xcd.jar neoe.xcd.Main
and add xcd.sh to PATH
the java program is
package neoe.xcd;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
public class Main {
public static String getUserHomeDir() {
return System.getProperty("user.home");
}
public static void main(String[] args) throws Exception {
new Main().run();
}
public static String readString(InputStream ins, String enc) throws IOException {
if (enc == null)
enc = "UTF-8";
BufferedReader in = new BufferedReader(new InputStreamReader(ins, enc));
char[] buf = new char[1000];
int len;
StringBuffer sb = new StringBuffer();
while ((len = in.read(buf)) > 0) {
sb.append(buf, 0, len);
}
in.close();
return sb.toString();
}
private String[] selection = new String[1];
private void run() throws Exception {
File hisfile = new File(getUserHomeDir(), ".bash_history");
if (!hisfile.exists()) {
System.err.println(".bash_history not exists, quit");
return;
}
String[] ss = readString(new FileInputStream(hisfile), null).split("\n");
List<String> res = new ArrayList<String>();
Set uniq = new HashSet();
for (String s : ss) {
s = s.trim();
if (!s.startsWith("cd /")) {
continue;
}
s = s.substring(3);
File f = new File(s);
if (f.isDirectory()) {
s = f.getAbsolutePath();
if (uniq.contains(s)) {
continue;
}
uniq.add(s);
res.add(s);
}
}
if (res.isEmpty()) {
System.err.println("no cd entry, quit");
return;
}
Collections.sort(res);
String cd1 = selectFromList(res);
if (cd1 == null) {
System.err.println("not selected, quit");
return;
}
doCd(cd1);
}
private void doCd(String cd1) throws Exception {
System.out.println(cd1);
}
private String selectFromList(List<String> res) {
final JList list = new JList(res.toArray());
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JDialog frame = wrapFrame(new JScrollPane(list), "select dir to cd");
list.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() > 1) {
String s = (String) list.getSelectedValue();
selection[0] = s;
frame.dispose();
}
}
});
list.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
int kc = e.getKeyCode();
if (kc == KeyEvent.VK_ESCAPE) {
frame.dispose();
} else if (kc == KeyEvent.VK_ENTER) {
String s = (String) list.getSelectedValue();
selection[0] = s;
frame.dispose();
}
}
});
frame.setVisible(true);
frame.requestFocus();
return selection[0];
}
private JDialog wrapFrame(JComponent comp, String title) {
JDialog frame = new JDialog();
frame.setTitle("select dir to cd");
frame.setModal(true);
frame.add(comp);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(400, 600);
frame.setLocationRelativeTo(null);
return frame;
}
}
use xcd in shell.
You can't really do that. Java programs don't really allow you to change the "current working directory" as most people understand it (not without using native code, anyway). The normal Java approach is to open a File instance on the directory you want to manipulate, and then use operations on that instance to manipulate the files/directories in question.
For details on how to delete directories programatically in Java, see: Delete directories recursively in Java
I simply put the class file and the html file in the same directory. And I call the applet with this:
<p align="center">
<applet code="/ShowImage.class" width="200" height="200">
</applet>
</p>
Obviously this doesn't work. What is the most convenient way to setup local development?
edit:
My applet code:
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
/**
*
* #author PCKhoi
*/
public class ShowImage extends Applet {
private BufferedImage img;
public void init() {
try {
URL url = new URL(getCodeBase(), "what_I_think.jpg");
img = ImageIO.read(url);
} catch (IOException e) {
}
}
public void paint(Graphics g){
g.drawImage(img,20,20, null);
}
}
Try this
<HTML>
<HEAD>
</HEAD>
<BODY>
<APPLET ALIGN="CENTER" CODE="ShowImage.class" WIDTH="800" HEIGHT="500"></APPLET>
</BODY>
</HTML>
and please post your applet code
Some notes:
The code as published (at this instant) does not compile
Do not swallow exceptions in broken code
To compile and run..
prompt> javac ShowImage.java
prompt> appletviewer ShowImage.java
Code (note that the image name will need to be changed back).
//<applet code="ShowImage" width="200" height="200"></applet>
import java.applet.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.net.URL;
/**
* #author PCKhoi
*/
public class ShowImage extends Applet {
private BufferedImage img;
public void init() {
try {
URL url = new URL(getCodeBase(), "icon.png");
img = ImageIO.read(url);
} catch (IOException e) {
e.printStackTrace();
}
}
public void paint(Graphics g){
g.drawImage(img,20,20, null);
}
}
The important line of the source, in relation to your question, is the first, commented line. It supplies an HTML element that the Applet Viewer will parse and use as a pseudo-HTML.
I think I know why it doesn't load now. The applet was wrapped inside a complex netbeans project, that's why putting the class file and the html file inside the same directory didn't work.
My solution is to use a simple IDE such as DrJava if you don't need project functionality.