Getting java.lang.RuntimeException: java.lang.NullPointerException - java

public class TestScenario1 {
#Test (dataProvider = "test")
public void execute(String TestCol1,String TestCol2, String TestCol3,String TestCol4) throws Exception {
homePage hp = new homePage();
hp.perform(TestCol1, TestCol2, TestCol3, TestCol4);
}
#DataProvider(name= "test")
public Object[][] testcase(ITestContext context) {
String filepath = executionBase.CONFIG.getProperty("filepath");
// String filepath = "D://workspace//Project//data//testData.xlsx";
String sheetname = "Suite";
return executionBase.getTestData(filepath, sheetname);
}
}
If I execute above code it gives me following error:
SKIPPED: execute
java.lang.RuntimeException: java.lang.NullPointerException
at org.testng.internal.MethodInvocationHelper.invokeDataProvider(MethodInvocationHelper.java:162)
at org.testng.internal.Parameters.handleParameters(Parameters.java:430)
But if I comment this line
String filepath =executionBase.CONFIG.getProperty("filepath");
and execute following instead,
String filepath = "D://workspace//Project//data//testData.xlsx";
it works fine
executionBase.class referred constructor code looks like,
public executionBase() throws IOException, FileNotFoundException {
CONFIG = new Properties();
FileInputStream ip = new FileInputStream(System.getProperty("user.dir")+ "//config//config.properties");
CONFIG.load(ip);
}
config.properties file entry goes like this,
filepath=D:\workspace\Project\data\testData.xlsx
Function of executionBase.class works fine for other path variables provided in config.properties, but not sure why I am getting Null value for same under
#DataProvider(name= "test") annotation

Properties.load() will escape back slashes, Try using double backslashes in the config file, or changing to forward slash:
filepath=D:/workspace/Project/data/testData.xlsx
You can also try:
String content = IOUtils.toString(ip, Charset.defaultCharset());
content = content.replaceAll("\\","\\\\");
CONFIG.load(content);
Edit: From what I can see, seems like your executionBase isn't initialized when you run your TestScenario class. Check how is executionBase() is called, and verify its called before calling it in DataProvider.

I faced the exact same problem, Open you test data sheet and press "CTRL+END", if its not the cell(lastrow,lastcolumn), then manually right click on that row or column and DELETE it. Save the file and run it, worked for me !

Related

Not able to read resource files from src/test/resources in STS

I created folder src/test/resources/ in root project directory, and inside this I added a file in folder jsons as jsons/server_request.json.
Now I am trying to read this file by calling a the static function in CommonTestUtilityclass given as:
public class CommonTestUtility {
public static String getFileAsString(String fileName) throws IOException {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
String content = new String(Files.readAllBytes(file.toPath()));
return content;
}
}
Now while calling this function as
class ServerTest {
#Test
void test_loadResource() {
String content = CommonTestUtility.getFileAsString("jsons/server_request.json");
}
}
, It's giving me the error as:
CommonTestUtility - Cannot invoke "java.net.URL.getFile()" because the return value of "java.lang.ClassLoader.getResource(String)" is null.
I tried to include the src/test/resources/ in the run configuration
of Junit ServerTest.java, but still it's not able to find out the
resource
How to resolve this issue?
https://mkyong.com/java/java-read-a-file-from-resources-folder/
This above link might be helpful.
The getResource() method return an URI you need to change
.getFile() function to. toURI().
Simple code
private File getFileFromResource(String fileName) throws URISyntaxException{
ClassLoader classLoader = getClass().getClassLoader();
URL resource = classLoader.getResource(fileName);
if (resource == null) {
throw new IllegalArgumentException("file not found! " + fileName);
} else {
// failed if files have whitespaces or special characters
//return new File(resource.getFile());
return new File(resource.toURI());
}
}
I recreated the same scenario you describe and your code works for me.
Could you double-check that your project looks like mine below? If so, I suspect it might be something with your environment.

Finding batch file using parameter in java

I have a batch file (test.bat) which has the command copy NUL test.txt. I have a java program, when i run it and when i enter a URL in the web browser e.g http://localhost:8080/runbatchfileparam, i get a result as either {"result":true} or {"result":false}. True means the java application has executed the batch file correctly (test.txt is created under the directory).
What i want to do now is, i want the java program to be able to take in parameters. E.g. User should be able to enter http://localhost:8080/runbatchfileparam/testabc.bat as the URL in web browser and the result should be {"result":true} if testabc.bat file is found and is executed (under desktop) and {"result":false} if the testabc.bat file is not found and not executed . (Note: All batch files are created under desktop filepath: C:/Users/attsuap1/Desktop)
I have edited my controller to take in a parameter and done the #PathVariable. In my codes, the fileName variable refers to the batch file name that i have created (test.bat, test123.bat) Command in test.bat: copy NUL test.txt Command in test123.bat: copy NUL test123.txt. However, i keep getting the result as {"result": false}. Which means the java program is not able to find the batch file and execute it.
Here are my codes:
RunBatchFile.java
public ResultFormat runBatch(String fileName) {
String var = fileName;
String filePath = "C:/Users/attsuap1/Desktop" + var;
try {
Process p = Runtime.getRuntime().exec(filePath);
int exitVal = p.waitFor();
return new ResultFormat(exitVal == 0);
} catch (Exception e) {
e.printStackTrace();
return new ResultFormat(false);
}
}
ResultFormat.java
private boolean result;
public ResultFormat(boolean result) {
this.result = result;
}
public boolean getResult() {
return result;
}
BatchFileController
private static final String template = "Sum, %s!";
#RequestMapping("/runbatchfileparam/{param}")
public ResultFormat runbatchFile(#PathVariable("param") String fileName ) {
RunBatchFile rbf = new RunBatchFile();
return rbf.runBatch(fileName);
}
Application.java
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
What do i have to edit or what should i add to the codes to achieve what i want?
After this line:
String filePath = "C:/Users/attsuap1/Desktop" + var;
Try to print the contents of filePath, i suspect that you come up with something like this:
C:/Users/attsuap1/Desktoptestabc.bat

Spring boot - Grabbing a file from the file system in a Get Request

I am trying to grab a file (in this case an image) from the file system and display it. I can do it from a resources subdirectory just fine, but when I try to go to the file system it is giving me a FileNotFound exception.
java.io.FileNotFoundException: file:\Y:\Kevin\downloads\pic_mountain.jpg (The filename, directory name, or volume label syntax is incorrect)
All the rest of my code is vanilla spring boot that was generated from the Initialize. Thanks.
#RestController
public class ImageProducerController {
#GetMapping("/get-text")
public #ResponseBody String getText() {
return "Hello World";
}
#GetMapping(value = "/get-jpg", produces = MediaType.IMAGE_JPEG_VALUE)
public void getImage(HttpServletResponse response) throws IOException {
FileSystemResource imgFile = new FileSystemResource("file:///Y:/Kevin/downloads/pic_mountain.jpg");
// ClassPathResource imgFile = new ClassPathResource("images/pic_mountain.jpg");
System.out.println(imgFile.getURL());
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
StreamUtils.copy(imgFile.getInputStream(), response.getOutputStream());
}
}
from the docs:
public FileSystemResource(String path)
Create a new FileSystemResource from a file path
the constructor expects a path-part of the url, so in your case only Y:/Kevin/downloads/pic_mountain.jpg
so you should try to use it this way:
FileSystemResource imgFile = new FileSystemResource("Y:/Kevin/downloads/pic_mountain.jpg");
Btw. could it be, that you miss "Users" in your path? -> Y:/Users/Kevin/downloads/pic_mountain.jpg

FileInputStream look into root of Jar

I have a FileInputStream in a class in the package com.nishu.ld28.utilities, and I want to access sound files in the folder Sounds, which is not in the com.nishu.ld28 package. I specify the path for loading like so:
"sounds/merry_xmas.wav"
And then try to load it like this:
new BufferedInputStream(new FileInputStream(path))
When I export the jar, the command line prompt that I run it through says it can't find the file. I know how to access the files when I am running the program in Eclipse, but I can't figure out how to point the FileInputStream to the Sounds folder when I export it.
Edit: As requested, here's my code:
public void loadSound(String path) {
WaveData data = null;
data = WaveData.create(GameSound.class.getClassLoader().getResourceAsStream(path));
int buffer = alGenBuffers();
alBufferData(buffer, data.format, data.data, data.samplerate);
data.dispose();
source = alGenSources();
alSourcei(source, AL_BUFFER, buffer);
}
WaveData accepts an InputStream or other types of IO.
You don't need a FileInputStream, because you aren't reading from the filesystem. Use the InputStream returned by ClassLoader.getResourceAsStream(String res) or Class.getResourceAsStream(String res). So either
in = ClassLoader.getResourceAsStream("sounds/merry_xmas.wav");
or
in = getClass().getResourceAsStream("/sounds/merry_xmas.wav");
Note the leading slash in the second example.
I would put the com.nishu.ld28.utilities in the same package of your class , let's call it MyClass.
Your package:
Your code:
package com.nishu.ld28.utilities;
import java.io.InputStream;
public class MyClass {
public static void main(String[] args) {
InputStream is = MyClass.class.getResourceAsStream("sound/merry_xmas.wav");
System.out.format("is is null ? => %s", is==null);
}
}
Output
is is null ? => false

null pointer (java.io.File) exception dissappears while debugging

I have an application which throws this error (happens only with xlsx-files):
java.lang.NullPointerException
at java.io.File.<init>(File.java:222)
at de.mpicbg.tds.core.ExcelLayout.openWorkbook(ExcelLayout.java:75)
The method 'openWorkbook' looks like this:
private void openWorkbook() throws IOException {
File excelFile = new File(fileName);
timestamp = excelFile.lastModified();
// open excel file
if (fileName.endsWith(".xlsx")) {
InputStream excelStream = new BufferedInputStream(new FileInputStream(excelFile));
this.workbook = new XSSFWorkbook((excelStream));
} else {
this.workbook = new HSSFWorkbook(new POIFSFileSystem(new FileInputStream(excelFile)));
}
}
If I execute everything in debug mode, everything goes smoothly and the error message does not appear. I don't have any explanation for this behaviour nor any idea how to fix it.
Can anybody help?
The error message says your fileName is null
If you cannot reproduce this when debugging you can add a log message at the start of you method.
System.out.println("The fileName is `" + fileName+"`");
Instead of using a field which may or may not be set, I suggest you use a parameter.
private void openWorkbook(String fileName) throws IOException {
assert fileName != null;

Categories