I'm making a selenium webdriver and I have an enum for the environments I am testing my app in and an enum for the app itself. My problem is I can't figure out how to use the environment enum inside the app enum in order to open it. I have a comment at the two spots I think my problem is. I get an error at the first comment so whatever would go there would be helpful.
public enum ENV
{
QA, STAGE,
PROD, DEV;
public String toString()
{
switch(this)
{
case QA: return "http://****/qa_was8.html";
case STAGE: return "http://****/stage.html";
case PROD: return "http://****/prod.html";
case DEV: return "http://****/index.html";
default: return "http://****/qa_was8.html";
}
}
}
public enum Application
{
ACCOUNTINVENTORY , AUDITACTIONITEMS;
public static Application chooseApp(String args)
{
File file = new File("H:\\InternStuff\\Selenium\\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath() );
WebDriver driver = new InternetExplorerDriver();
for(Application app : Application.values())
{
switch(app)
{
case ACCOUNTINVENTORY:
driver.get(ENV.valueOf(args[1]));//What would go here
driver.findElement(By.linkText("Account Inventory")).click();
driver.findElement(By.name("j_username")).sendKeys("****");
driver.findElement(By.name("j_password")).sendKeys("****");
driver.findElement(By.cssSelector("input[type='submit']")).click();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
driver.findElement(By.className("inputText")).sendKeys("smith");
driver.findElement(By.className("commandExButton")).click();
break;
case AUDITACTIONITEMS:
driver.findElement(By.linkText("AuditAction Items")).click();
driver.findElement(By.name("j_username")).sendKeys("****");
driver.findElement(By.name("j_password")).sendKeys("****");
driver.findElement(By.cssSelector("input[type='submit']")).click();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
driver.findElement(By.className("commandExButton")).click();
default:
System.out.println("...");
}
}
return null;
}
}
public static void main(String[] args)
{
if(args.length != 0)
{
Application app = Application.chooseApp(args[1]);
ENV env = ENV.valueOf(args[0]);
if(app != null)
{
app.toString();
}
else if(env != null)
{
env.toString();// Or maybe is my problem here?
}
}
}
}
If I understand your question, you have a compile time error because you are attempting to treat String args as a String[] in chooseApp. The easiest solution I see is to pass the entire args array to chooseApp,
public static Application chooseApp(String[] args)
// ...
driver.get(ENV.valueOf(args[1]));// <-- now you can access args[1]
then
Application app = Application.chooseApp(args);
Related
My goal is running some process in VirtualMachine using Java. First of all, I have a part of code for create and connect to VB, but i have exception(NullPointer in main Thread) in 21 and 89 lines. I searching some answer to fix this problem, and read that problem look as I haven't Oracle VB. But in my computer i have it , version equals to imported.
So if you have an experience in using this API, or can help me, please, describe in detail how i can fix it. So, my code:
import org.virtualbox_5_1.*;
import org.virtualbox_5_1.ISession;
import org.virtualbox_5_1.IProgress;
import java.util.List;
import java.util.Arrays;
public class Events_5_1 {
static VirtualBoxManager mgr;
static Thread listener;
public static void main(String[] args) {
String vmName = Long.toString(System.currentTimeMillis()); // Берем рандомное значение имени VirtualMachine
System.out.println("Creating VirtualBox instance");
mgr = VirtualBoxManager.createInstance(null);
try {
listener = new EventWorker();
listener.start();
try {
//Создаем пустую машину и сохраняем на диск
IMachine vm = mgr.getVBox().createMachine(null, vmName, null, "Other", null);//тестить , разобраться с параметрами
vm.saveSettings();
mgr.getVBox().registerMachine(vm);
vm = mgr.getVBox().findMachine(vmName);
ISession session = mgr.getSessionObject();
IProgress p = vm.launchVMProcess(session, "headless", null); // Вместо headless - ставим процесс ??
p.waitForCompletion(-1);
try {
if (p.getResultCode() != 0) {
throw new RuntimeException(p.getErrorInfo().getText());
} else {
p = session.getConsole().powerDown();
p.waitForCompletion(-1);
if (p.getResultCode() != 0) {
throw new RuntimeException(p.getErrorInfo().getText());
} else {
}
}
} finally {
session.unlockMachine();
while (!SessionState.Unlocked.equals(vm.getSessionState())) {
try {
System.out.println("Waiting for session unlocked");
Thread.sleep(1000L);
} catch (InterruptedException e) {
System.err.println("Interrupted while vaiting for session unlocked");
}
}
System.out.println("Deleting machine");
vm.deleteConfig(vm.unregister(CleanupMode.DetachAllReturnHardDisksOnly));
}
} finally {
listener.interrupt();
try {
listener.join(5000);
} catch (InterruptedException e) {
System.err.println("Inerrupted while vaiting for EventWorker stop");
}
if (listener.isAlive()) {
System.err.println("Event worked did not stop in a timely fashion");
} else {
System.out.println("event worker stoped");
}
}
} finally {
mgr.disconnect();
mgr.cleanup();
System.out.println("Disconecting from VirtualBox");
}
}
static class EventWorker extends Thread {
IEventListener el;
#Override
public void run() {
System.out.println("EventWorker started");
el = mgr.getVBox().getEventSource().createListener();
//TODO: connect gradle, mvnrepository.com idea connect datasource postgre
List<VBoxEventType> types = Arrays.asList(VBoxEventType.OnSessionStateChanged, VBoxEventType.OnMachineStateChanged,
VBoxEventType.OnMachineRegistered);
mgr.getVBox().getEventSource().registerListener(el, types, false);
try{
while(!isInterrupted()){
mgr.waitForEvents(0);
IEvent rawEvent = mgr.getVBox().getEventSource().getEvent(el , 1000);
if(rawEvent==null) continue;
try{
System.out.println("Got event type "+rawEvent.getType());
if(VBoxEventType.OnSessionStateChanged.equals(rawEvent.getType())){
ISessionStateChangedEvent event = ISessionStateChangedEvent.queryInterface(rawEvent);
System.out.println("Machine "+event.getState()+" for machine "+event.getMachineId());
}
if(VBoxEventType.OnMachineRegistered.equals((rawEvent.getType()))){
IMachineRegisteredEvent event = IMachineRegisteredEvent.queryInterface(rawEvent);
System.out.println("Machine "+event.getMachineId()+" has been "+(event.getRegistered() ? "registered":"unregistered"));
}
if(VBoxEventType.OnMachineStateChanged.equals(rawEvent.getType())){
IMachineStateChangedEvent event = IMachineStateChangedEvent.queryInterface(rawEvent);
System.out.println("Machine "+event.getMachineId()+" state changed to "+event.getState());
}
}finally {
mgr.getVBox().getEventSource().eventProcessed(el,rawEvent);
}
}
}catch(Throwable t){
t.printStackTrace();
}finally {
mgr.getVBox().getEventSource().unregisterListener(el);
System.out.println("EventWorker finished");
}
}
}
}
If you are to plain copy/paste adapt my code, you should at least stick to the code structure and flow.
You've moved code around for some reasons and variables are not initialized timely, which is why you get NPEs.
Here is the working version for VirtualBox 5.1.x
I'm a novice when it comes to JSPs and JAVA.
How do I get the output from the below code to display on a jsp, considering that it runs everything from the main and contains non-public methods, a nested static class etc?
I know that we are not supposed to use java code on jsp but my first step in this proof on concept exercise is to get the code running and returning data from a backend then I can set about using EL etc.
I can run the program, with the correct config settings, from within Eclipse and all works fine with the output appearing on the console but I'm really not sure how to access it from within a jsp.
How do I access the static class and static methods from a jsp if they aren't public?
All help greatly appreciated.
public class CustomDestinationDataProvider
{
static class MyDestinationDataProvider implements DestinationDataProvider
{
private DestinationDataEventListener eL;
private HashMap<String, Properties> secureDBStorage = new HashMap<String, Properties>();
public Properties getDestinationProperties(String destinationName)
{
try
{
//read the destination from DB
Properties p = secureDBStorage.get(destinationName);
if(p!=null)
{
//check if all is correct, for example
if(p.isEmpty())
throw new DataProviderException(DataProviderException.Reason.INVALID_CONFIGURATION, "destination configuration is incorrect", null);
return p;
}
return null;
}
catch(RuntimeException re)
{
throw new DataProviderException(DataProviderException.Reason.INTERNAL_ERROR, re);
}
}
public void setDestinationDataEventListener(DestinationDataEventListener eventListener)
{
this.eL = eventListener;
}
public boolean supportsEvents()
{
return true;
}
//implementation that saves the properties in a very secure way
void changeProperties(String destName, Properties properties)
{
synchronized(secureDBStorage)
{
if(properties==null)
{
if(secureDBStorage.remove(destName)!=null)
eL.deleted(destName);
}
else
{
secureDBStorage.put(destName, properties);
eL.updated(destName); // create or updated
}
}
}
} // end of MyDestinationDataProvider
//business logic
void executeCalls(String destName)
{
JCoDestination dest;
try
{
dest = JCoDestinationManager.getDestination(destName);
dest.ping();
System.out.println("Destination " + destName + " works");
step4WorkWithTable(dest);
}
catch(JCoException e)
{
e.printStackTrace();
System.out.println("Execution on destination " + destName+ " failed");
}
}
static Properties getDestinationPropertiesFromUI()
{
//adapt parameters in order to configure a valid destination
Properties connectProperties = new Properties();
// Add code here to set config settings
return connectProperties;
}
public static void main(String[] args)
{
MyDestinationDataProvider myProvider = new MyDestinationDataProvider();
//register the provider with the JCo environment;
//catch IllegalStateException if an instance is already registered
try
{
com.sap.conn.jco.ext.Environment.registerDestinationDataProvider(myProvider);
}
catch(IllegalStateException providerAlreadyRegisteredException)
{
//somebody else registered its implementation,
//stop the execution
throw new Error(providerAlreadyRegisteredException);
}
String destName = "????";
CustomDestinationDataProvider test = new CustomDestinationDataProvider();
//set properties for the destination and ...
myProvider.changeProperties(destName, getDestinationPropertiesFromUI());
//... work with it
test.executeCalls(destName);
}
public static void step4WorkWithTable(JCoDestination dest) throws JCoException
{
JCoFunction function = dest.getRepository().getFunction("BAPI_COMPANYCODE_GETLIST");
if(function == null)
throw new RuntimeException("BAPI_COMPANYCODE_GETLIST not found in SAP.");
try
{
function.execute(dest);
}
catch(AbapException e)
{
System.out.println(e.toString());
return;
}
JCoStructure returnStructure = function.getExportParameterList().getStructure("RETURN");
if (! (returnStructure.getString("TYPE").equals("")||returnStructure.getString("TYPE").equals("S")) )
{
throw new RuntimeException(returnStructure.getString("MESSAGE"));
}
JCoTable codes = function.getTableParameterList().getTable("COMPANYCODE_LIST");
for (int i = 0; i < codes.getNumRows(); i++)
{
codes.setRow(i);
System.out.println(codes.getString("COMP_CODE") + '\t' + codes.getString("COMP_NAME"));
}
//move the table cursor to first row
codes.firstRow();
for (int i = 0; i < codes.getNumRows(); i++, codes.nextRow())
{
function = dest.getRepository().getFunction("BAPI_COMPANYCODE_GETDETAIL");
if (function == null)
throw new RuntimeException("BAPI_COMPANYCODE_GETDETAIL not found in SAP.");
function.getImportParameterList().setValue("COMPANYCODEID", codes.getString("COMP_CODE"));
//We do not need the addresses, so set the corresponding parameter to inactive.
//Inactive parameters will be either not generated or at least converted.
function.getExportParameterList().setActive("COMPANYCODE_ADDRESS",false);
try
{
function.execute(dest);
}
catch (AbapException e)
{
System.out.println(e.toString());
return;
}
returnStructure = function.getExportParameterList().getStructure("RETURN");
if (! (returnStructure.getString("TYPE").equals("") ||
returnStructure.getString("TYPE").equals("S") ||
returnStructure.getString("TYPE").equals("W")) )
{
throw new RuntimeException(returnStructure.getString("MESSAGE"));
}
JCoStructure detail = function.getExportParameterList().getStructure("COMPANYCODE_DETAIL");
System.out.println(detail.getString("COMP_CODE") + '\t' +
detail.getString("COUNTRY") + '\t' +
detail.getString("CITY"));
}//for
}
}
I'm trying to find a way to detect when a flash drive has been plugged into my computer. So far, the solution I found was to poll FileSystem#getFileStores for changes. This does indeed tell me when the flash drive has been inserted, but as far as I can tell there is no way to retrieve the location for it. FileStore#type and FileStore#name both seem highly unreliable as their return value is implementation specific, but they appear to be the only methods that might return any relevant information that might help find the directory for the FileStore.
With that in mind, the following code:
public class Test {
public static void main(String[] args) throws IOException {
for (FileStore store : FileSystems.getDefault().getFileStores()) {
System.out.println(store);
System.out.println("\t" + store.name());
System.out.println("\t" + store.type());
System.out.println();
}
}
}
Gave me this output:
/ (/dev/sda5)
/dev/sda5
ext4
/* snip */
/media/TI103426W0D (/dev/sda2)
/dev/sda2
fuseblk
/media/flashdrive (/dev/sdb1)
/dev/sdb1
vfat
As it turns out, FileStore#type returns the format of the drive and FileStore#name returns the location of the device file for the drive. As far as I can tell, the only method which has the location of the drive is the toString method, but extracting the path name out of it seems dangerous because I'm not sure how well that particular solution would hold up on other operating systems and future versions of Java.
Is there something I'm missing here or is this simply not possible purely with Java?
System Information:
$ java -version
java version "1.7.0_03"
OpenJDK Runtime Environment (IcedTea7 2.1.1pre) (7~u3-2.1.1~pre1-1ubuntu2)
OpenJDK Client VM (build 22.0-b10, mixed mode, sharing)
$ uname -a
Linux jeffrey-pc 3.2.0-24-generic-pae #37-Ubuntu SMP Wed Apr 25 10:47:59 UTC 2012 i686 athlon i386 GNU/Linux
Here's a temporary work around until a better solution is found:
public Path getRootPath(FileStore fs) throws IOException {
Path media = Paths.get("/media");
if (media.isAbsolute() && Files.exists(media)) { // Linux
try (DirectoryStream<Path> stream = Files.newDirectoryStream(media)) {
for (Path p : stream) {
if (Files.getFileStore(p).equals(fs)) {
return p;
}
}
}
} else { // Windows
IOException ex = null;
for (Path p : FileSystems.getDefault().getRootDirectories()) {
try {
if (Files.getFileStore(p).equals(fs)) {
return p;
}
} catch (IOException e) {
ex = e;
}
}
if (ex != null) {
throw ex;
}
}
return null;
}
As far as I know, this solution will only work for Windows and Linux systems.
You have to catch the IOException in the Windows loop because if there is no CD in the CD drive an exception is thrown when you try to retrieve the FileStore for it. This might happen before you iterate over every root.
This is what I have ended up doing. This is limited to Windows + UNIX but avoids using external tools or additional library calls. It steals the information Java already has in the FileStore objects
LinuxFileStore definitely extends UnixFileStore, so it will work. Same deal for Solaris. Since Mac OS X is UNIX, it probably works there but I'm not sure because I couldn't see its subclass in any place I was looking.
public class FileStoreHacks {
/**
* Stores the known hacks.
*/
private static final Map<Class<? extends FileStore>, Hacks> hacksMap;
static {
ImmutableMap.Builder<Class<? extends FileStore>, Hacks> builder =
ImmutableMap.builder();
try {
Class<? extends FileStore> fileStoreClass =
Class.forName("sun.nio.fs.WindowsFileStore")
.asSubclass(FileStore.class);
builder.put(fileStoreClass, new WindowsFileStoreHacks(fileStoreClass));
} catch (ClassNotFoundException e) {
// Probably not running on Windows.
}
try {
Class<? extends FileStore> fileStoreClass =
Class.forName("sun.nio.fs.UnixFileStore")
.asSubclass(FileStore.class);
builder.put(fileStoreClass, new UnixFileStoreHacks(fileStoreClass));
} catch (ClassNotFoundException e) {
// Probably not running on UNIX.
}
hacksMap = builder.build();
}
private FileStoreHacks() {
}
/**
* Gets the path from a file store. For some reason, NIO2 only has a method
* to go in the other direction.
*
* #param store the file store.
* #return the path.
*/
public static Path getPath(FileStore store) {
Hacks hacks = hacksMap.get(store.getClass());
if (hacks == null) {
return null;
} else {
return hacks.getPath(store);
}
}
private static interface Hacks {
Path getPath(FileStore store);
}
private static class WindowsFileStoreHacks implements Hacks {
private final Field field;
public WindowsFileStoreHacks(Class<?> fileStoreClass) {
try {
field = fileStoreClass.getDeclaredField("root");
field.setAccessible(true);
} catch (NoSuchFieldException e) {
throw new IllegalStateException("file field not found", e);
}
}
#Override
public Path getPath(FileStore store) {
try {
String root = (String) field.get(store);
return FileSystems.getDefault().getPath(root);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Denied access", e);
}
}
}
private static class UnixFileStoreHacks implements Hacks {
private final Field field;
private UnixFileStoreHacks(Class<?> fileStoreClass) {
try {
field = fileStoreClass.getDeclaredField("file");
field.setAccessible(true);
} catch (NoSuchFieldException e) {
throw new IllegalStateException("file field not found", e);
}
}
#Override
public Path getPath(FileStore store) {
try {
return (Path) field.get(store);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Denied access", e);
}
}
}
}
I've not really explored this area of java, but I found this, which seems to be related. It uses File.listRoots()
There also seems to be a number of related questions linked there too.
This works for Windows:
public Path getFileStoreRootPath(FileStore fs) throws Exception {
for (Path root : FileSystems.getDefault().getRootDirectories()) {
if (Files.isDirectory(root) && Files.getFileStore(root).equals(fs)) {
return root;
}
}
throw new RuntimeException("Root directory for filestore " + fs + " not found");
}
Basically, by filtering by condition Files.isDirectory(root) we are excluding all CD/DVD drives which will throw IOException when compact-disc is not inserted.
Okay, I'm trying to create a custom client for Minecraft (don't worry, my question has nothing to do with Minecraft in particular), and I added an abstract class to manage a configuration file using Java's built-in Properties system. I have a method that loads a properties file or creates it if it doesn't already exist. This method is called at the beginning of all my other methods (although it only does anything the first time its called).
The properties file gets created just fine when I run Minecraft the first time, but somehow when I run it the second time, the file gets blanked out. I'm not sure where or why or how I'm wiping the file clean, can someone please help me? Here's my code; the offending method is loadConfig():
package net.minecraft.src;
import java.util.*;
import java.util.regex.*;
import java.io.*;
/**
* Class for managing my custom client's properties
*
* #author oxguy3
*/
public abstract class OxProps
{
public static boolean configloaded = false;
private static Properties props = new Properties();
private static String[] usernames;
public static void loadConfig() {
System.out.println("loadConfig() called");
if (!configloaded) {
System.out.println("loading config for the first time");
File cfile = new File("oxconfig.properties");
boolean configisnew;
if (!cfile.exists()) {
System.out.println("cfile failed exists(), creating blank file");
try {
configisnew = cfile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
configisnew=true;
}
} else {
System.out.println("cfile passed exists(), proceding");
configisnew=false;
}
FileInputStream cin = null;
FileOutputStream cout = null;
try {
cin = new FileInputStream(cfile);
cout = new FileOutputStream(cfile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (!configisnew) { //if the config already existed
System.out.println("config already existed");
try {
props.load(cin);
} catch (IOException e) {
e.printStackTrace();
}
} else { //if it doesn't exist, and therefore needs to be created
System.out.println("creating new config");
props.setProperty("names", "oxguy3, Player");
props.setProperty("cloak_url", "http://s3.amazonaws.com/MinecraftCloaks/akronman1.png");
try {
props.store(cout, "OXGUY3'S CUSTOM CLIENT\n\ncloak_url is the URL to get custom cloaks from\nnames are the usernames to give cloaks to\n");
cout.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
String names = props.getProperty("names");
System.out.println("names: "+names);
try {
usernames = Pattern.compile(", ").split(names);
} catch (NullPointerException npe) {
npe.printStackTrace();
}
System.out.println("usernames: "+Arrays.toString(usernames));
configloaded=true;
}
}
public static boolean checkUsername(String username) {
loadConfig();
System.out.println("Checking username...");
for (int i=0; i<usernames.length; i++) {
System.out.println("comparing "+username+" with config value "+usernames[i]);
if (username.startsWith(usernames[i])){
System.out.println("we got a match!");
return true;
}
}
System.out.println("no match found");
return false;
}
public static String getCloakUrl() {
loadConfig();
return props.getProperty("cloak_url", "http://s3.amazonaws.com/MinecraftCloaks/akronman1.png");
}
}
If it's too hard to read here, it's also on Pastebin: http://pastebin.com/9UscXWap
Thanks!
You are unconditionally creating new FileOutputStream(cfile). This will overwrite the existing file with an empty one. You should only invoke the FileOutputStream constructor when writing a new config file.
if (configloaded)
return;
File cfile = new File("oxconfig.properties");
try {
if (cfile.createNewFile()) {
try {
FileOutputStream cout = new FileOutputStream(cfile);
props.setProperty("names", "oxguy3, Player");
props.setProperty("cloak_url", "http://...");
...
cout.flush();
} finally {
cout.close();
}
} else {
FileInputStream cin = new FileInputStream(cfile);
try {
props.load(cin);
} finally {
cin.close();
}
}
configloaded=true;
} catch(IOException ex) {
e.printStackTrace();
}
What is the preferred method to determine if the Sun Java Plugin is installed in the browser?
java deployment toolkit
script src="http://java.com/js/deployJava.js"
if (deployJava.versionCheck('1.6'))
{
alert("1.6 installed")
}
You may also consider PluginDetect script.
This isn't an answer for your exact question but is offered as a solution for determining the browser itself. Don't be too harsh, this is really old code that I wrote some time ago.
import java.applet.*;
public class BrowserDetector extends Applet {
public void init() {
if (isNetscape()) {
System.out.println("This browser is a Netscape Browser.");
}
if (isMicrosoft()) {
System.out.println("This browser is a Microsoft Browser.");
}
System.out.println("VM Type: " + getVMType());
}
public static boolean isNetscape() {
try {
Class.forName("netscape.applet.MozillaAppletContext");
} catch (ClassNotFoundException e) {
System.out.println("This browser is not a Netscape Browser.");
return false;
}
return true;
}
public static boolean isMicrosoft() {
try {
Class.forName("com.ms.applet.GenericAppletContext");
} catch (ClassNotFoundException e) {
System.out.println("This browser is not a Microsoft Browser.");
return false;
}
return true;
}
public String getVMType() {
String theBrowser = "No VM";
String appletContext = getAppletContext().toString();
if (appletContext.startsWith("sun.applet.AppletViewer"))
theBrowser = "APPLETVIEWER";
else if (appletContext.startsWith("netscape.applet."))
theBrowser = "NETSCAPE";
else if (appletContext.startsWith("com.ms.applet."))
theBrowser = "MICROSOFT";
else if (appletContext.startsWith("sunw.hotjava.tags.TagAppletPanel"))
theBrowser = "HOTJAVA";
else if (appletContext.startsWith( "sun.plugin.navig.win32.AppletPlugin"))
theBrowser = "NETSCAPEPLUGIN";
else if (appletContext.startsWith( "sun.plugin.ocx.ActiveXApplet"))
theBrowser = "MICROSOFTPLUGIN";
else if (appletContext.startsWith( "sun.plugin.viewer.context.IExplorerAppletContext"))
theBrowser = "MICROSOFTPLUGINJRE1.4";
return theBrowser;
}
}