IllegalStateException: Failed to load Application Context when using File functions in Java - java

I'm using a function like this to get the latest file present based on timestamp:
File file = getFile(path);
Where getFile () is like this:
private File getFile (String path) {
File directory = new File(path);
File[] files = directory.listFiles(File::isFile);
long latestVersion = Long.MIN_VALUE;
File latestFile = null;
if (files!= null) {
for (File file : files) {
if (file.lastModified() > latestVersion) {
latestFile = file;
latestVersion = file.lastModified();
}
}
}
return latestFile;
}
On running mvn clean install I get this error:
IllegalStateException: Failed to load Application Context in a totally different test class of the same module.
If I remove the file method, the build runs fine. Definitely something is wrong here in this code then?
Can anyone help here?
Thanks.

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.

How to get resources directory path using java

I am testing test in cucumber which i want to upload file from testData to S3 bucket:
String bucket = bucketname+ "/ADL";
String ActualFilesPathForComparison = Environment.getInstance().getValue(DATAINPUTPATH);
temp = ActualFilesPathForComparison+inputPath+ File.separator+ file;
s3.uploadFile(bucket, file, new File (temp));
public void uploadFile(String bucketName, String fileKeyName, File localFilePath) {
try {
this.s3.putObject((new PutObjectRequest(bucketName, fileKeyName, localFilePath)).withCannedAcl(CannedAccessControlList.PublicRead));
} catch (Exception var5) {
throw new RuntimeException("Upload file failed.", var5);
}
}
I have this file:
src\main\resources\testData\testInputsFile\testLZInputUnZippedFiles\Log.csv
when i run the test i am getting from the debug:
localFilePath = testData\testInputsFile\testLZInputUnZippedFiles\Log_WithHeader.csv
And getting excption:
com.amazonaws.SdkClientException: Unable to calculate MD5 hash: testData\testInputsFile\testLZInputUnZippedFiles\Log_WithHeader.csv (The system cannot find the path specified)
what should i fixed? i want to avoid to copy the file outside from the src.
To access a file named "my.properties" which is inside src/main/resources/, you just need to do:
File propertiesFile = new File(this.getClass().getClassLoader().getResource("my.properties").getFile());

Could not save file on disk in controller

I have following controller:
#PostMapping(value = "/load_attachment")
public DeferredResult uploadingPost(#RequestParam("attachment") MultipartFile[] uploadingFiles, #RequestParam("stoneId") String stoneId) throws IOException {
logger.info("Upload {} files for stone: {}", uploadingFiles.length, stoneId);
for (MultipartFile uploadedFile : uploadingFiles) {
File file = new File(uploadedFile.getOriginalFilename());
uploadedFile .transferTo(file);
logger.info("path:{}", file.getAbsolutePath()); // I expect to find files here
}
}
No exceptions happens but I could not find files on file system.
In your case, Application server doesn't application server inside folder path so you should specify it manually!...
for (MultipartFile uploadedFile : uploadingFiles) {
File file = new File("path/to/your/server/application/directory"+uploadedFil‌e.getOriginalFilenam‌e());
uploadedFile .transferTo(file);
logger.info("path:{}", file.getAbsolutePath()); // I expect to find files here
}
for further reference https://www.programcreek.com/java-api-examples/index.php?class=org.springframework.web.multipart.MultipartFile&method=transferTo

Can not load properties file from the web-inf folder in Websphere 8.5 server

I am trying to load a properties file from WEb-INF folder in my web application , which is running on Websphere 8.5 . I am using below code to load the file from the location
public class Init {
private final String WEB_INF_DIR_NAME="WEB-INF";
private String web_inf_path;
private final Properties APP_PROPERTIES =null;
InputStream inputStream = null;
public String getWebInfPath() throws IOException {
if (web_inf_path == null) {
web_inf_path = URLDecoder.decode(Init.class.getProtectionDomain().getCodeSource().getLocation().getPath(), "UTF8");
web_inf_path=web_inf_path.substring(0,web_inf_path.lastIndexOf(WEB_INF_DIR_NAME)+WEB_INF_DIR_NAME.length()).substring(1);
}
inputStream = Init.class.getResourceAsStream("/config/localhost/accountservice.properties");
// inputStream = this.getClass().getClassLoader().getResourceAsStream("/config/localhost/accountservice.properties");
if (inputStream != null) {
APP_PROPERTIES.load(inputStream);
}
System.out.println(APP_PROPERTIES.getProperty(AccountServiceDataAccessConstants.INET_LIBRARY_NAME)); // Here i am getting NULL
return web_inf_path;
}
}
I have also tried using servlet context , but its also giving me NULL. I have tried all possible ways to solve it but unfortunately i am not able to do it. I am also giving my folder structure.
Please excuse me if this is a silly question , but i am not really getting any idea about it.
Usually, everything in WebContent is placed in the root of your WAR file. So instead of
inputStream = Init.class.getResourceAsStream("/config/localhost/accountservice.properties");
It would be
inputStream = Init.class.getResourceAsStream("/WEB-INF/config/localhost/accountservice.properties");
The root of the WAR has WEB-INF in it, and then you can descend into your folder structure as normal.

How to get files from resources folder. Spring Framework

I'm trying to unmarshal my xml file:
public Object convertFromXMLToObject(String xmlfile) throws IOException {
FileInputStream is = null;
File file = new File(String.valueOf(this.getClass().getResource("xmlToParse/companies.xml")));
try {
is = new FileInputStream(file);
return getUnmarshaller().unmarshal(new StreamSource(is));
} finally {
if (is != null) {
is.close();
}
}
}
But I get this errors:
java.io.FileNotFoundException: null (No such file or directory)
Here is my structure:
Why I can't get files from resources folder? Thanks.
Update.
After refactoring,
URL url = this.getClass().getResource("/xmlToParse/companies.xml");
File file = new File(url.getPath());
I can see an error more clearly:
java.io.FileNotFoundException: /content/ROOT.war/WEB-INF/classes/xmlToParse/companies.xml (No such file or directory)
It tries to find WEB-INF/classes/
I have added folder there, but still get this error :(
I had the same problem trying to load some XML files into my test classes. If you use Spring, as one can suggest from your question, the easiest way is to use org.springframework.core.io.Resource - the one Raphael Roth already mentioned.
The code is really straight forward. Just declare a field of the type org.springframework.core.io.Resource and annotate it with org.springframework.beans.factory.annotation.Value - like that:
#Value(value = "classpath:xmlToParse/companies.xml")
private Resource companiesXml;
To obtain the needed InputStream, just call
companiesXml.getInputStream()
and you should be okay :)
But forgive me, I have to ask one thing: Why do you want to implement a XML parser with the help of Spring? There are plenty build in :) E.g. for web services there are very good solutions that marshall your XMLs into Java Objects and back...
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("fileName").getFile());
you are suppose to give an absolute path (so add a loading ´/´, where resource-folder is the root-folder):
public Object convertFromXMLToObject(String xmlfile) throws IOException {
FileInputStream is = null;
File file = new File(String.valueOf(this.getClass().getResource("/xmlToParse/companies.xml")));
try {
is = new FileInputStream(file);
return getUnmarshaller().unmarshal(new StreamSource(is));
} finally {
if (is != null) {
is.close();
}
}
}

Categories