I am beginner in java.
I want run native application from applet.
I found Run App In Every Browser
Java Code
import com.ms.security.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.io.* ;
import java.util.*;
import netscape.security.PrivilegeManager;
public class RunApp extends Applet implements ActionListener {
TextArea ta = new TextArea (25, 80);
Button startbutton = new Button("Start Application") ;
private static String execommand = "C:\\windows\\notepad.exe" ;
private String osname;
public void init() {
try {
if (Class.forName("com.ms.security.PolicyEngine") != null) { // required for IE
PolicyEngine.assertPermission(PermissionID.SYSTEM);
}
}
catch (Throwable cnfe) {
}
this.setBackground(Color.white) ;
startbutton.addActionListener(this) ;
add(startbutton) ;
startbutton.setBackground(Color.red) ;
try{
PrivilegeManager.enablePrivilege("UniversalExecAccess") ; // required for NN
}
catch(Exception cnfe) {
System.out.println("netscape.security.PrivilegeManager class not found") ;
}
osname = System.getProperty("os.name"); // if NT, Win2000 or WinXP, adjust path
if(osname.equals("Windows NT") || osname.equals("Windows 2000")|| osname.equals("Windows XP"))
execommand = "C:\\winnt\\notepad.exe" ;
}
public void actionPerformed(ActionEvent e) {
if( (e.getActionCommand()).equals("Start Application")) {
try{
PrivilegeManager.enablePrivilege("UniversalExecAccess") ; // required for NN
}
catch(Exception cnfe) {
System.out.println("netscape.security.PrivilegeManager class not found") ;
}
try {
Process proc = Runtime.getRuntime().exec(execommand) ;
}
catch(IOException ieo) {
System.out.println("Problem starting " + execommand) ;
}
// System.out.println("execommand: " + execommand) ;
}
}
}
But when run it say error:package com.ms.security does not exit!
I does not any folder with ms or security name .
I should create folder with ms and then security in root file or should import library ms.security .
where is com.ms.security or netscape.security.PrivilegeManager?
how can download it?i search for download this package but i does not found anythings
I use eclipse for write code.
This package does not exist any more. The tutorial you point to dates from 2002. You can look at this javaranch post: http://www.coderanch.com/t/375470/java/java/Location-Jar-ms-security, and at the Microsoft documentation (https://msdn.microsoft.com/en-us/library/aa242534(v=vs.60).aspx). So basically your code would have worked 13 years ago, but with Microsoft not supporting their own JVM any more it's obsolete. Sorry!
You need to download that jar having this package ,com.ms.security. And b4 compiling your java class set that jar in your classpath from command prompt.
set classpath=%classpath%;path_of_your_jar;
This package is not existed anymore. Microsoft is not supporting their own JVM anymore. You should try to learn java applet in the new way, such as http://www.tutorialspoint.com/java/java_applet_basics.htm.
The import statement import com.ms.security.*; requires you to have a folder com, with a subfolder ms, with a subfolder security, which contains the needed files.
I think you are missing some files for your application.
I recommend reading this post, for the use of imports: https://stackoverflow.com/a/12620773/3234981
Please check your jar file which contain the respective package are present in the classpath or not. If not, push them to classpath and re-compile the same class on a new command line.
Happy Learning.
Related
I'm currently taking my first automated test class and the instructor has us creating a program in Eclipse after loading Selenium and create a step in the program to look at an executable to bring up chrome then designate a website to check. It looks like i am stuck in a loop?
Here is the program:
java program
Here is the result:
program result
any and all help would be appreciated. Thank you for your time.
I think this is what you want
This code is to open the default browser and go to a specific link
You can specify the path of any browser you want from the path in the code
import java.awt.Desktop;
import java.net.URI;
public class openBrowser {
public openBrowser() {
try {
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(new URI("https://www.google.com"));
}
}catch (Exception e) {
// TODO: handle exception
}
}
public static void main(String[]args) {
new openBrowser();
}
}
For your code you can follow the following steps
Download ChromeDriver from here
Extract the zip file and follow the path ( because it is easy ) C:\\chromeDriver\\chromedriver.exe
include the ChromeDriver location in your PATH environment variable
Download the required Libraries from the following junit openqa
Add the Libraries to your project ( Build Path )
then this is your code
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.*;
import org.junit.Test;
public class WebDriverDemo {
#Test
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\chromeDriver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("ChromeDriver");
searchBox.submit();
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Logger.getLogger(WebDriverDemo.class.getName()).log(Level.SEVERE, null, ex);
}
driver.quit();
}
}
During the implementation of the code in the eclipse, many problems occurred, so I advise you to implement the project on NetBeans
I use Java 8 and Windows 8.1
I'm using in my program the bluecove library.
While running the program via eclipse, all works smooth. I'm now trying to deploy my program, and following this post i'm using fat-jar.
When i run the jar file (created by fat-jar), the library can't be located, and i'm getting the exception BlueCove libraries not available as result of this line local = LocalDevice.getLocalDevice();.
In the fat-jar window i tried also to add bluecove-2.1.0.jar to the Class-Path place, and also with the path \src\JoJoServer\bluecove-2.1.0.jar.
I tried also to place the bluecove's jar file in different folders, such as the src, or an external folder.
Although i know it's not recommended, i tried the option of One-Jar, nevertheless it didn't help.
To run the jar (the one created by fat jar) i simply double click the file.
What i'm missing?
This is the entire code:
import java.io.IOException;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
#Override
public void run() {
// retrieve the local Bluetooth device object
LocalDevice local = null;
StreamConnectionNotifier notifier;
StreamConnection connection = null;
// setup the server to listen for connection
try {
local = LocalDevice.getLocalDevice();
local.setDiscoverable(DiscoveryAgent.GIAC);
UUID uuid = new UUID("0000110100001000800000805F9B34FB", false);
System.out.println(uuid.toString());
String url = "btspp://localhost:" + uuid.toString() + ";name=RemoteBluetooth";
notifier = (StreamConnectionNotifier)Connector.open(url);
} catch (BluetoothStateException e) {
System.out.println("Bluetooth is not turned on.");
e.printStackTrace();
return;
}
// ...
}
I have no clue what could be your problem, but I've tried the process and everything works, so just a summary of what I've did. Maybe you will figure it out by following it...
I don't understand how the posted code could be the entire, I see no class definition. :)
So I've modified it to the main method and it works both from the Eclipse and also by running the JAR generated by the FatJar.
The modified code of the BTTest class:
package test;
import java.io.IOException;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
public class BTTest {
public static void main(String[] args) throws Exception{
// retrieve the local Bluetooth device object
LocalDevice local = null;
StreamConnectionNotifier notifier;
StreamConnection connection = null;
// setup the server to listen for connection
try {
local = LocalDevice.getLocalDevice();
local.setDiscoverable(DiscoveryAgent.GIAC);
UUID uuid = new UUID("0000110100001000800000805F9B34FB", false);
System.out.println(uuid.toString());
String url = "btspp://localhost:" + uuid.toString()
+ ";name=RemoteBluetooth";
notifier = (StreamConnectionNotifier) Connector.open(url);
} catch (BluetoothStateException e) {
System.out.println("Bluetooth is not turned on.");
e.printStackTrace();
return;
}
// ...
}
}
To run or produce it, I have just put the bluecove library in the build path and created the fat jar with a simple way:
http://oi60.tinypic.com/vg1jpt.jpg
Starting the generated jar from command line:
D:\testProjects\bttest>java -jar bttest_fat.jar
BlueCove version 2.1.0 on winsock
0000110100001000800000805f9b34fb
BlueCove stack shutdown completed
Can you post a difference to your process?
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 created a report from my NetBeans GUI and It was working fine, but all of a sudden the compiler showing error now.
package dreportsample;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import net.sf.dynamicreports.examples.Templates;
import net.sf.dynamicreports.report.builder.style.StyleBuilder;
import net.sf.dynamicreports.report.constant.HorizontalAlignment;
import net.sf.dynamicreports.report.datasource.DRDataSource;
import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.JRDataSource;
/**
* #author Ricardo Mariaca (dynamicreports#gmail.com)
*/
public class DReportSample {
public DReportSample() {
build();
}
private void build() {
StyleBuilder boldStyle = stl.style().bold();
StyleBuilder boldCenteredStyle = stl.style(boldStyle).setHorizontalAlignment
(HorizontalAlignment.CENTER).setFontSize(15);
StyleBuilder footerLeft = stl.style().setHorizontalAlignment
(HorizontalAlignment.LEFT) ;
StyleBuilder footerRight = stl.style().setHorizontalAlignment
(HorizontalAlignment.RIGHT) ;
//BufferedImage img = new BufferedImage(1200,1200,BufferedImage.TYPE_INT_RGB);
BufferedImage img = null;
try {
// img = ImageIO.read(new File("D:/Hysteresis.png"));
img = ImageIO.read(new File("D:/Hysteresis.png"));
} catch (IOException e) {
}
BufferedImage logo = null;
try {
// img = ImageIO.read(new File("D:/Hysteresis.png"));
logo = ImageIO.read(new File("D:/Logo.jpg"));
} catch (IOException e) {
}
try {
report()//create new report design
// .setColumnTitleStyle(boldStyle)
// .setColumnStyle(boldStyle)
.highlightDetailEvenRows()
.columns(//add columns
col.column(null,"Col_1", type.stringType()),
col.column(null,"Col_2", type.stringType())
)
.summary(
cmp.verticalList()
.add(cmp.text("\n\nHYSTERISIS PLOT").setStyle(boldStyle))
.add(cmp.text("A brief description of what this plot signifies "
+ "which means that change in are related to"
+ " pain relief and subsequently"
+ "should be encouraged \n\n\n\n"))
// .add(cmp.image(getClass().getResourceAsStream
// ("D:/Hysteresis.png")).setFixedDimension(300, 300))
.add(cmp.image(img).setFixedDimension(400, 300))
.add(cmp.text("ANALYSIS\n\n\n").setStyle(boldStyle))
.add(cmp.text("REMARKS\n\n\n\n").setStyle(boldStyle))
.add(cmp.text("Doctor Signature").setStyle(boldStyle))
)
.title(
cmp.horizontalList()
.add(
cmp.image(logo).setFixedDimension(70, 70),
cmp.verticalList()
.add(
cmp.text("Address Line 1").setStyle(boldCenteredStyle),
cmp.text("Address Line 2").setStyle(boldCenteredStyle),
cmp.text("Address Line 3").setStyle(boldCenteredStyle))
)
.newRow()
.add(cmp.filler().setStyle(stl.style().setTopBorder(stl.pen2Point())).setFixedHeight(10))
)//shows report title
// .pageFooter(cmp.pageXofY())//shows number of page at page footer
.pageFooter(
Templates.footerComponent,
//cmp.text("Emsol Software Solution \t\t\t\t\t\t\t\t"
// + " copyright: gauravbvelelx#gmail.com")
cmp.horizontalList()
.add(cmp.text("Emsol Software Solution").setStyle(footerLeft),
cmp.text("copyright: gauravbvelex#gmail.com").setStyle(footerRight))
)
.setDataSource(createDataSource())//set datasource
.show();//create and show report
} catch (DRException e) {
e.printStackTrace();
}
}
private JRDataSource createDataSource() {
DRDataSource dataSource = new DRDataSource("Col_1", "Col_2");
dataSource.add("Name","Sample");
dataSource.add("Age","26");
dataSource.add("Sex","Female");
dataSource.add("Weight","53 Kg");
dataSource.add("BMI","20");
dataSource.add("Massage Duration (Mins)","4.5");
dataSource.add("RPM","26");
dataSource.add("Doctor Attended","Doctor");
dataSource.add("Date","22-Feb-2013");
return dataSource;
}
public static void main(String[] args) {
new DReportSample();
}
}
This code worked fine just few hours back. But now it is suddenly showing error:
Screen shot attached
Same kind of error it is showing at report() and other parts as well. Basically it is not able to recognize various classes and fields of dynamic reports library though the library has been imported successfully, though few hours back it was working well.
The way I am using dynamic reports is by adding the libraries as below:
1) Downloaded dynamicreports-3.1.0-project-with-dependencies
2) Unzipped
3) In my Netbeans Project
Libraries -> Add Jar/folder -> Selecting all files from dynamicreports-3.1.0-project-with-dependencies\dynamicreports-3.1.0\lib
Libraries -> Add Jar/folder -> Selecting all files from dynamicreports-3.1.0-project-with-dependencies\dynamicreports-3.1.0\dist
It worked fine, but then then I changed the name of the folder where I saved dynamicreports-3.1.0-project-with-dependencies, due to which It gave me Reference Error for added libraries. So I again rechanged it to previous name, but since then I am getting the error shown.
I have tried everything, building new project and following the steps mentioned or re downloading new dynamicreports-3.1.0-project-with-dependencies and again following the steps. But nothing seems to work, its frustrating as I was so close to complete my project.
Can anyone help please.
Thanks
Ok.. resolved it..
Below line got deleted causing the errors:
import static net.sf.dynamicreports.report.builder.DynamicReports.*;
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