I made a structure change in my project, and I am getting this error
Project Structure:
enter image description here
the platform notifies me of the following error:
Step failed
java.lang.NullPointerException: inStream parameter is null
at java.base/java.util.Objects.requireNonNull(Objects.java:233)
at java.base/java.util.Properties.load(Properties.java:407)
at com.crm.framework.config.ConfigReader.ReadProperty(ConfigReader.java:19)
at com.crm.framework.config.ConfigReader.PopulateSettings(ConfigReader.java:11)
at steps.TestInitialize.Initialize(TestInitialize.java:21)
This is my ConfigReader, which is shown in the above error
ConfigReader:
package com.crm.framework.config;
import com.crm.framework.base.BrowserType;
import java.io.IOException;
import java.util.Properties;
public class ConfigReader {
public static void PopulateSettings() throws IOException {
ConfigReader reader = new ConfigReader();
reader.ReadProperty();
}
private void ReadProperty() throws IOException {
//Create Property Object
Properties p = new Properties();
//Load the property file available in same package
p.load(getClass().getResourceAsStream("GlobalConfig.properties"));
//Get AUTConnection String
Settings.AUTConnectionString = p.getProperty("AUTConnectionString");
//Get Reporting String
Settings.ReportingConnectionString = p.getProperty("ReportingConnectionString");
//Get LogPath
Settings.LogPath = p.getProperty("LogPath");
//Get DriverType
Settings.DriverType = p.getProperty("DriverType");
//Get ExcelSheetPath
Settings.ExcelSheetPath = p.getProperty("ExcelSheetPath");
//Get AUT
Settings.AUT = p.getProperty("AUT");
//Browser Type
Settings.BrowserType = BrowserType.valueOf(p.getProperty("BrowserType"));
}
}
I also attach the code of the TestInitialize, file that contains the #Before to run the test cases
TestInitialize:
package steps;
import com.crm.framework.base.DriverContext;
import com.crm.framework.base.FrameworkInitialize;
import com.crm.framework.config.ConfigReader;
import com.crm.framework.config.Settings;
import com.crm.framework.utilities.LogUtil;
import io.cucumber.java.Before;
// import io.cucumber.java.Before;
import java.io.IOException;
public class TestInitialize extends FrameworkInitialize {
#Before
public void Initialize() throws IOException {
//Initialize config
ConfigReader.PopulateSettings();
//Logging
Settings.Logs = new LogUtil();
Settings.Logs.CreateLogFile();
Settings.Logs.Write("Framework initialize");
//Create Test Cycle for Reporting
/*
Pending
*/
Settings.Logs.Write("Test Cycle Created");
InitializeBrowser(Settings.BrowserType);
Settings.Logs.Write("Browser initialize");
DriverContext.Browser.GotoUrl(Settings.AUT);
Settings.Logs.Write("Navigate to URL: " + Settings.AUT);
}
}
Here is the most likely culprit:
https://docs.oracle.com/javase/10/docs/api/java/util/Properties.html#getProperty(java.lang.String)
From Javadoc:
public String getProperty​(String key)
Searches for the property with the specified key in this property list. If the key is not found in
this property list, the default property list, and its defaults,
recursively, are then checked. The method returns null if the property
is not found.
Properties are case sensitive. Make sure that:
The property file you need exists, then
The property key inside the file exists and lastly
It is spelled out the exact same way it appears in the file.
As a failsafe, you could use getProperty(key, defaultValue)which it is similar to the one above, except that it returns the passed default value instead of null in cases where the property key being passed to the method doesn't exist in the given property file.
Also, make sure the PATH to the property file is correct. Understanding how file paths are resolved when running from IDE and from deploy environment could also be an issue if you don't understand how resources are resolved.
Related
I'm trying to read a keystore as a resource. Sample code below. The problem I'm running into is that inputStream remains null.
import java.io.InputStream;
import java.util.List;
import org.linguafranca.pwdb.kdbx.KdbxCreds;
import org.linguafranca.pwdb.kdbx.simple.SimpleDatabase;
import org.linguafranca.pwdb.kdbx.simple.SimpleEntry;
import org.linguafranca.pwdb.Credentials;
import org.apache.log4j.Logger;
public class Security {
private static final String PATH = null;
private static final String KEYSTORE_PASSWORD = "admin";
static List<SimpleEntry> entries = null;
final static Logger logger = Logger.getLogger(Security.class);
public Security(){
//TODO: initialize security and it's passwords
}
public static void init(){
try {
//InputStream inputStream = new FileInputStream(".keePass.kdbx");
InputStream inputStream = Security.class.getClassLoader().getResourceAsStream("keePass.kdbx");
// password credentials
Credentials credentials = new KdbxCreds(KEYSTORE_PASSWORD.getBytes());
SimpleDatabase database = SimpleDatabase.load(credentials, inputStream);
// Jaxb implementation seems a lot faster than the DOM implementation
// visit all groups and entries and list them to console
entries = database.getRootGroup().getEntries();
}catch(Exception exception){
logger.error(exception);
}
}
}
First I thought it's just a matter of path, however even though the file itself resides next to the classes, I can't load it.
Even if I use absolute path, result is the same.
What is the mistake I'm making?
When you are using getClassLoader().getResourceAsStream("...") it tries to find the file in the root of classpath. Try to use:
Security.class.getResourceAsStream("keePass.kdbx");
In this case it will try to find the file in the same location as the Security class
See more What is the difference between Class.getResource() and ClassLoader.getResource()?
I'm trying to add new XParameter for standard Status property with this code
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.parameter.XParameter;
import org.apache.commons.io.IOUtils;
import com.example.common.util.ical.ICalUtil;
import java.io.FileInputStream;
import java.io.IOException;
public class TestICal {
public static void main(String[] args) throws IOException {
String content = IOUtils.toString(new FileInputStream("/tmp/taskA.ics"));
Calendar task = ICalUtil.parse(content);
Component vtodo = task.getComponent(Component.VTODO);
Property prop = vtodo.getProperty(Property.STATUS);
prop.getParameters().add(new XParameter("X-TEST-PARAM", "TEST-VALUE")); // java.lang.UnsupportedOperationException
}
}
but following exception is thrown during its execution
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Collections.java:1016)
at net.fortuna.ical4j.model.ParameterList.add(ParameterList.java:157)
at TestICal.main(TestICal.java:18)
In a debugger I can see that inside ical4j package add() method is called on java.util.Collections$UnmodifiableRandomAccessList which, actually I can't find in API doc for some reason, and which implements java.util.List
The property can't be deleted or replaced and I can't see a method which would allow to replace or add another parameter list.
So now I think the field can't have parameters, at least if using ical4j.
Any idea?
Answering myself: it can be done by searching required property index and calling set() method of ArrayList which PropertyList extends
import net.fortuna.ical4j.model.*;
import net.fortuna.ical4j.model.parameter.XParameter;
import org.apache.commons.io.IOUtils;
import com.example.common.util.ical.ICalUtil;
import java.io.FileInputStream;
import java.util.Iterator;
public class TestICal {
public static void main(String[] args) throws Exception {
// reading and parsing ICS
String content = IOUtils.toString(new FileInputStream("/tmp/taskA.ics"));
Calendar task = ICalUtil.parse(content);
Component vtodo = task.getComponent(Component.VTODO);
Property prop = vtodo.getProperty(Property.STATUS);
// checking the prop before
System.out.println(prop);
// preparing new param list and adding it to new created prop
ParameterList paramList = new ParameterList();
paramList.add(new XParameter("X-TEST-PARAM", "TEST-VALUE"));
PropertyFactoryImpl propFactory = PropertyFactoryImpl.getInstance();
Property myprop = propFactory.createProperty(Property.STATUS, paramList, "COMPLETED");
// and finally
PropertyList propList = vtodo.getProperties();
int index = propList.indexOf(prop);
propList.set(index, myprop);
// checking
System.out.println(vtodo.getProperties().getProperty(Property.STATUS));
}
}
result
STATUS:IN-PROCESS
STATUS;X-TEST-PARAM=TEST-VALUE:COMPLETED
I'm learning Java and sometimes I have some problem to retrieve the information I need from objects...
When I debug my code I can see in targetFile, a path property but I don't know how to get it in my code.
This is a screenshot:
(source: toile-libre.org)
This is my complete code:
package com.example.helloworld;
import com.github.axet.wget.WGet;
import com.github.axet.wget.info.DownloadInfo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class HelloWorld {
public static void main(String[] args) throws IOException {
nodejs();
}
public static void nodejs() throws IOException {
// Scrap the download url.
Document doc = Jsoup.connect("http://nodejs.org/download").get();
Element link = doc.select("div.interior:nth-child(2) > table:nth-child(2) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(3) > a:nth-child(1)").first();
String url = link.attr("abs:href");
// Print the download url.
System.out.println(url);
// Download file via the scraped url.
URL download = new URL(url);
File target = new File("/home/lan/Desktop/");
WGet w = new WGet(download, target);
w.download();
// Get the targetFile property
// ???
}
}
How can I get this value?
I do not know your code but the field you are interested in may be encapsulated and thus not accessible in your code, but the debugger can see it at runtime :)
Update:
https://github.com/axet/wget/blob/master/src/main/java/com/github/axet/wget/WGet.java
The field is default package, you can only access it from within the package.
This can be frustrating at times, but you should ask yourself why the designers of this class decided to hide this field.
I've tried directly linking using the entire path but that hasn't solved it either.
package eliza;
import java.io.*;
public class Eliza {
public static void main(String[] args) throws IOException {
String inputDatabase = "src/eliza/inputDataBase.txt";
String outputDatabase = "src/eliza/outputDataBase.txt";
Reader database = new Reader();
String[][] inputDB = database.Reader(inputDatabase);
String[][] outputDB = database.Reader(outputDatabase);
}
}
Here is the reader class:
package eliza;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class Reader {
public String[][] Reader(String name) throws IOException {
int length = 0;
String sizeLine;
FileReader sizeReader = new FileReader(name);
BufferedReader sizeBuffer = new BufferedReader(sizeReader);
while((sizeLine = sizeBuffer.readLine()) != null) {
length++;
}
String[][] database = new String[length][1];
return (database);
}
}
Here's a photo of my directory. I even put these text files in the "eliza" root folder: here
Any ideas?
Since you are using an IDE, you need to give the complete canonical path. It should be
String inputDatabase = "C:\\Users\\Tommy\\Desktop\\Eliza\\src\\eliza\\inputDataBase.txt";
String outputDatabase = "C:\\Users\\Tommy\\Desktop\\Eliza\\src\\eliza\\outputDataBase.txt";
The IDE is probably executing the bytecode from its bin folder and cannot find the relative reference.
give the exact path like
String inputDatabase = "c:/java/src/eliza/inputDataBase.txt";
you have not given the correct path, Please re check
try
{BASE_PATH}+ "Eliza/src/inputDataBase.txt"
The source directory tree isn't generally present during execution, so files that are required at runtime shouldn't be put there ... unless you're going to use them as resources, in which case their pathname is relative to the package root, and does not begin with 'src', and the data is accessed by a getResourceXXX() method, not via a FileInputStream.
I use the JDOM library. When I write information into an xml file, Eclipse shows errors. The system cannot find the path specified. I try to create the file in the "language" folder. How can I create the folder automatically when I write info into this file? I think the error is in this line:
FileWriter writer = new FileWriter("language/variants.xml");
Here is my code:
package test;
import java.io.FileWriter;
import java.util.LinkedList;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
class Test {
private LinkedList<String> variants = new LinkedList<String>();
public Test() {
}
public void write() {
Element variantsElement = new Element("variants");
Document myDocument = new Document(variantsElement);
int counter = variants.size();
for(int i = 0;i < counter;i++) {
Element variant = new Element("variant");
variant.setAttribute(new Attribute("name",variants.pop()));
variantsElement.addContent(variant);
}
try {
FileWriter writer = new FileWriter("language/variants.xml");
XMLOutputter outputter = new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
outputter.output(myDocument,writer);
writer.close();
}
catch(java.io.IOException exception) {
exception.printStackTrace();
}
}
public LinkedList<String> getVariants() {
return variants;
}
}
public class MyApp {
public static void main(String[] args) {
Test choice = new Test();
choice.write();
}
}
Here is the error:
java.io.FileNotFoundException: language\variants.xml (The system cannot find the path specified)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
at java.io.FileOutputStream.<init>(FileOutputStream.java:104)
at java.io.FileWriter.<init>(FileWriter.java:63)
at test.Test.write(MyApp.java:31)
at test.MyApp.main(MyApp.java:49)`enter code here
As the name suggests FileWriter is for writing to file. You need to create the directory first if it doesnt already exist:
File theDir = new File("language");
if (!theDir.exists()) {
boolean result = theDir.mkdir();
// Use result...
}
FileWriter writer = ...
For creating directories you need to use mkdir() of File class.
Example:
File f = new File("/home/user/newFolder");
f.mkdir();
It returns a boolean: true if directory created and false if it failed.
mkdir() also throws Security Exception if security manager exists and it's checkWrite() method doesn't allow the named directory to be created.
PS: Before creating directory, you need to validate if this directory already exists or not by using exists() which also returns boolean.
Regards...
Mr.777