Java- Load file from same package in NB platform application - java

I have the following piece of code,
public void vbsCalled() {
try {
String file = "src\\com\\first\\hello\\hello.vbs";
Runtime.getRuntime().exec("wscript " + file + " ");
} catch (IOException ex) {
Logger.getLogger(RunVBS.class.getName()).log(Level.SEVERE, null, ex);
}
}
I am using netbeans IDE,
Scenario 1:
I create a new java project (New Project -> Java -> Java Application)
The project Structure looks like below,
--Java Application1
-Source Packages
-com.first.hello //Package
-ClassWhichHaveVbsCalledMethod.java
-hello.vbs
with this am able to call the hello.vbs from same package and no error.
Scenario 2:
I create a netbeans platform application (New project - > Netbeans Modules ->NetBeans platform Application)
The project Structure looks like below,
RunVBS.java has the vbsCalled() Method and with the hello.vbs in same package as scenario 1,
Now, it looks for the file in
"C:\application1\src\com\first\hello\hello.vbs"
and shows no such file found error.
How can i load the file in netbeans platform application as like scenario1.

Create a folder in your project's root directory called release
Move hello.vbs to the release/ folder
Use the InstalledFileLocator class to get the runtime path of your file.
Here is what your vbsCalled() method would then look like.
public void vbsCalled() {
try {
File file = InstalledFileLocator.getDefault().locate(
"hello.vbs", // filename relative to the release/ directory
"com.first.hello", // Your module's code name base __not package!__
false);
Runtime.getRuntime().exec("wscript " + file.getAbsolutePath() + " ");
} catch (IOException ex) {
Logger.getLogger(RunVBS.class.getName()).log(Level.SEVERE, null, ex);
}
}
See DevFaqInstalledFileLocator for more details

Related

Unable to locate and load file in Eclipse IDE, File not found

I'm new to Java, and I am facing this issue in Eclipse. Even after pointing it to the correct file, it shows a file not Found Error.
I am trying to compile code from a Java file using the Java Compiler API.
The code words fine in Visual Studio with setting everything in root, But gives this error in Eclipse with all these directories.
Also, why are there three different src folders in the image?
My project structure
package com.example.app;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.IOException;
public class compilier {
public static void main(String[] args) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int result = compiler.run(null, null, null, new File("com/example/app/Code.java").getAbsolutePath());
if (result == 0)
{
System.out.println("File Compiled");
}
try {
String package_dir = "/demo/src/main/java/com/example/app";
try{
ProcessBuilder builder = new ProcessBuilder("java", package_dir.concat("/Code"));
builder.redirectErrorStream(true);
File outfile = new File((package_dir.concat("/output.txt")));
builder.redirectOutput();
builder.start();
if (outfile.length() > 3000)
{
System.out.println("Exceeded buffer limit");
System.exit(1);
}
} catch(IOException e) {
e.printStackTrace();
}
} catch (Exception err) {
System.out.println("Error!");
err.printStackTrace();
}
}
}
Error Message
Your path looks wrong. The /demo directory would need to be in the root of your current drive.
Also, the output of a Maven build is found in the target directory. The Java class files are generated there, and the resource files are copied over from src/main/res hierarchy. The .Java files are lost. You could add a Maven task to copy the .Java files but this would be very nonstandard.
Finally you need to load resource files using the classpath. There are lots of examples on the Internet. Otherwise you may end up with a project that finds the file in Eclipse but not when deployed in a .jar or .war file.
Happy hunting.

can I get the directory of another file?

I have created an auto-updater for my java program. but at the end of the download it downloads the file to desktop. I can to get where is the program file and update it?
this is my code:
#Override
public void run() {
if(!Debug) {
try {
FileUtils.copyURLToFile(new URL("fileurl"), new File(System.getenv("APPDATA") + "\\file.zip"));
UnzipUtility unzip = new UnzipUtility();
File deskfile = new File(System.getProperty("user.home") + "/Desktop/file.jar");
if(deskfile.exists()) {
deskfile.delete();
}
unzip.unzip(System.getenv("APPDATA") + "\\file.zip", System.getProperty("user.home") + "/Desktop");
File file = new File(System.getenv("APPDATA") + "\\file.zip");
file.delete();
Successfull = true;
} catch (IOException e) {
Successfull = false;
}
try {
Updater.sleep(0L);
}catch(Exception e) {
e.printStackTrace();
}
}
}
this is the code present in my external updater jar and I need to find the main program directory what can I do?
For example, if the main program is in any other directory except the Desktop, the update will always download it to the desktop ... I need it to change the file that executes the command to start the updater
If your external updater is in the same directory as your mail application you can use:
System.getProperty("user.dir");
This will give you the current folder. You can find more details here: https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
If this is not the case i see the following options:
ask the user before updating for the installation folder
store the installation folder in property file inOS user data // update jar folder.
regards, WiPu

File not reading in selenium - maven framewaork

I tried to create a quick framework. in that I created below-mentioned classes:
Config file(All browsers path)
configDataProvider java class(reads the above file)
BrowserFactory class(has firefox browser object)
configDataProviderTest class(access data from dconfigDataProvider class)
now its not reading the paths mentioned in config.properties file.
I have provided all correct path and attached screenshots:
Looks like a problem is at your ConfigDataProvider class.
Firstly, you using Maven for building your project. Maven has defined project structure for code sources and for resources:
/src/main/java
/src/main/resorces
Thus, much better to put your .properties file there.
Second, you don't need to set the full path to your config file.
Relative path will be just enough. Something like below:
public class PropertiesFileHandler {
private static Logger log = Logger.getLogger(PropertiesFileHandler.class);
public static final String CONFIG_PROPERTIES = "src/main/resources/config.properties";
public static final String KEY = "browser.type";
public static BrowserType readBrowserType() {
BrowserType browserType = null;
Properties properties = new Properties();
try (InputStream inputStream = new BufferedInputStream(new FileInputStream(CONFIG_PROPERTIES))) {
properties.load(inputStream);
browserType = Enum.valueOf(BrowserType.class, properties.getProperty(KEY));
} catch (FileNotFoundException e) {
log.error("Properties file wasn't found - " + e);
} catch (IOException e) {
log.error("Problem with reading properties file - " + e);
}
return browserType;
}
}
Lastly, if you are building framework you don't need to put everything under src/main/test. This path specifies tests with future possibilities to be executed with maven default lifecycle - mvn test.
The core of your framework can look like:
Two things which I noticed:
Don't give path in your properties path within ""
all the path seperators should be replaced with double backward slash \\ or single forward slash /

How to load external properties file with Java without rebuilding the Jar?

I use gradle which structures projects in maven style so I have the following
src/main/java/Hello.java and src/main/resources/test.properties
My Hello.java look like this
public class Hello {
public static void main(String[] args) {
Properties configProperties = new Properties();
ClassLoader classLoader = Hello.class.getClassLoader();
try {
configProperties.load(classLoader.getResourceAsStream("test.properties"));
System.out.println(configProperties.getProperty("first") + " " + configProperties.getProperty("last"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
This works fine. however I want to be able to point to .properties file outside of my project and I want to it to be flexible enough that I can point to any location without rebuilding the jar every time. Is there a way to this without using a File API and passing file path as an argument to the main method?
You can try this one, which will first try to load properties file from project home directory so that you don't have to rebuild jar, if not found then will load from classpath
public class Hello {
public static void main(String[] args) {
String configPath = "test.properties";
if (args.length > 0) {
configPath = args[0];
} else if (System.getenv("CONFIG_TEST") != null) {
configPath = System.getenv("CONFIG_TEST");
}
File file = new File(configPath);
try (InputStream input = file.exists() ? new FileInputStream(file) : Hello.class.getClassLoader().getResourceAsStream(configPath)) {
Properties configProperties = new Properties();
configProperties.load(input);
System.out.println(configProperties.getProperty("first") + " " + configProperties.getProperty("last"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
You can send the properties file path as argument or set the path to an environment variable name CONFIG_TEST
Archaius may be complete overkill for such a simple problem, but it is a great way to manage external properties. It is a library for handling configuration: hierarchies of configuration, configuration from property files, configuration from databases, configuration from user defined sources. It may seem complicated, but you will never have to worry about hand-rolling a half-broken solution to configuration again. The Getting Started page has a section on using a local file as the configuration source.

Export war from headless Eclipse

How do I export a WAR file from an Eclipse .web project programmatically with Java?
I have big problems with war ant task due to complex project structure(
ProjectX.web has a dependency from ProjectX.java) and i'm very confused by the
WebComponentExportWizard implementation.
Is there any WTP API to use? (like this old version http://www.eclipse.org/webtools/jst/components/j2ee/api/j2ee_operationsAPI.html )
After some heavy fight i manage to obtain the war file trough this method:
#SuppressWarnings("restriction")
public static void exportWar(IProject webProject) throws CoreException {
WebComponentExportDataModelProvider modelProvider = new WebComponentExportDataModelProvider();
IDataModel dataModel = DataModelFactory.createDataModel(modelProvider);
dataModel.setBooleanProperty(IJ2EEComponentExportDataModelProperties.EXPORT_SOURCE_FILES, false);
dataModel.setBooleanProperty(IJ2EEComponentExportDataModelProperties.OVERWRITE_EXISTING, true);
dataModel.setStringProperty(IJ2EEComponentExportDataModelProperties.PROJECT_NAME, webProject.getName());
dataModel.setStringProperty(IJ2EEComponentExportDataModelProperties.ARCHIVE_DESTINATION, webProject
.getLocation().append(webProject.getName()).addFileExtension("war").toOSString());
dataModel.setProperty(
IJ2EEComponentExportDataModelProperties.COMPONENT,
ComponentCore.createComponent(webProject));
IDataModelOperation modelOperation = dataModel.getDefaultOperation();
try {
log.debug("Start the export war operation");
modelOperation.execute(null, null);
}
catch (ExecutionException e) {
log.error("Error when exporting .war project", e);
}
}
I used org.eclipse.wst.server.core.util.PublishHelper.publishZip() like below, and it works for me.
IPath war = workDirectory.append("app.war");
PublishHelper publishHelper = new PublishHelper(null);
J2EEFlexProjDeployable deployable =
new J2EEFlexProjDeployable(project, ComponentCore.createComponent(project));
publishHelper.publishZip(deployable.members(), war, null);

Categories