Java EE Application - Copy folder from war to file system with - java-ee-6

I have a Java EE application which is packaged as a war file.
Under WEB-INF/classes/ I have a config folder which should be copied at startup of the Java EE application into the file system.
String[] filesToCopy = {"foo", ...};
for (String fileName : filesToCopy) {
URL resource = classLoader.getResource(CONFIG_FOLDER_IN_WAR + fileName);
File targetFile = new File(configFolderPath, fileName);
org.apache.commons.io.FileUtils.copyURLToFile(resource, targetFile);
}
that was working so far. But now the config folder contains also subfolders and a lot of files so that I don't want to list them manually.
Is there a way to copy the whole folder incl. all subfolders?

Because I couldn't find a better solution I did it by myself and put it in my own FileUtils:
public static void copyFromWarToFolder(String folderInWar, File targetFolder) {
try {
URL resource = FileUtils.class.getClassLoader().getResource(folderInWar);
VirtualFile virtualFileOrFolder = VFS.getChild(resource.toURI());
copyFromWarToFolder(virtualFileOrFolder, targetFolder);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void copyFromWarToFolder(VirtualFile virtualFileOrFolder, File targetFolder) throws Exception {
if (virtualFileOrFolder.isDirectory()) {
File innerTargetFolder = new File(targetFolder, virtualFileOrFolder.getName());
innerTargetFolder.mkdir();
for (VirtualFile innerFileOrFolder : virtualFileOrFolder.getChildren()) {
copyFromWarToFolder(innerFileOrFolder, innerTargetFolder);
}
} else {
org.apache.commons.io.FileUtils.copyURLToFile(virtualFileOrFolder.asFileURL(), new File(targetFolder, virtualFileOrFolder.getName()));
}
}

Related

RCP plugin retrieving classpath of the runtime project

I want to develop an editor for eclipse which works with java projects.
The plugin needs to know the resources in the classpath of the project of the open file. Since the question is quite ambigious i always find threads about the classpath of the bundle/plugin not the project edited with. Can someone tell me the right buzzword(runtime project) or share some code/links for that topic?
To be clear. This editor and its auto-completion/validation has to behave different whenever a classpath entry is added/removed same as the standard java-file editor.
With helpful hint of #howgler i figured out how to get the classpath of the IJavaProject and scan it via google reflections. Hope that help somebody in the future.
#Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException {
INSTANCE = this;
super.init(site, input);
FileEditorInput fei = (FileEditorInput) input;
IFile file = fei.getFile();
IProject project = file.getProject();
try {
if (project.hasNature(JavaCore.NATURE_ID)) {
IJavaProject targetProject = JavaCore.create(project);
final IClasspathEntry[] resolvedClasspath = targetProject.getResolvedClasspath(true);
ArrayList<URL> urls = new ArrayList<>();
for (IClasspathEntry classpathEntry : resolvedClasspath) {
if (classpathEntry.getPath().toFile().isAbsolute()) {
urls.add(classpathEntry.getPath().toFile().toURI().toURL());
} else {
urls.add(new File(project.getWorkspace().getRoot().getLocation().toFile(),classpathEntry.getPath().toString()).toURI().toURL());
}
}
URLClassLoader urlCl = new URLClassLoader(urls.toArray(new URL[urls.size()]));
Reflections reflections = new Reflections(urlCl,new TypeAnnotationsScanner(),new SubTypesScanner(true));
Set<Class<?>> classes = reflections.getTypesAnnotatedWith(<???>.class);
System.out.println(classes);
}
} catch (CoreException | IOException e1) {
e1.printStackTrace();
}
}

Spring Batch how to read all json files from a folder and all its sub-folders using PathMatchingResourcePatternResolver

I'm using Spring Batch MultiResourceItemReader in order to read multipule files. these files are located at a parent directory and it's sub-directories.
Already tried:
Read the files by my own customized code and create the Resource array manually.
Use PathMatchingResourcePatternResolver as can be seen in the code example ( inspired by this Finding Resources with PathMatchingResourcePatternResolver and URLClassloader in JARs
#Bean
public MultiResourceItemReader<List<SingleJsonRowInput>>
multiResourceItemReader() {
PathMatchingResourcePatternResolver patternResolver = new
PathMatchingResourcePatternResolver();
Resource resources[] = null;;
try {
resources =
patternResolver.getResources("file:C:\\inputFolder\\**\\*.json");
} catch (IOException e) {
e.printStackTrace();
}
MultiResourceItemReader<List<SingleJsonRowInput>>
multiResourceItemReader = new MultiResourceItemReader<>();
multiResourceItemReader.setResources(resources);
multiResourceItemReader.setDelegate(new
ItemReaderForMulti(fileManager));
return multiResourceItemReader;
}
You can use the following snippet:
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("file:/root/folder/**/*.json");
The **/* will return the files recursively from the root/folder. Then you pass the resources array to the MultiResourceItemReader.
Instead of using windows backslashes - the solution is to use Unix\Linux like syntax:
Didn't work:
resources = patternResolver.getResources("file:C:\\inputFolder\\**\\*.json");
Works well:
resources = patternResolver.getResources("file:C:/inputFolder/**/*.json");

Java WatchService code works in Eclipse but same code fails in Tomcat in Docker

In Eclipse, a unit test fires up this code and when the watched file is altered, outputs the new text.
In Tomcat, it hangs where shown.
I've grovelled around online for quite some time trying to find anyone with a similar problem, but nothing showed up.
This is vanilla watcher code, and because it works fine in Eclipse, there must be a Tomcat-specific issue, but what?
The file is accessible to the code in Tomcat. It's not a permissions problem.
public class Foo extends Thread {
File watchedFile = <the watched file>;
WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = watchedFile.getParentFile().toPath();
dir.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
#Override
public void run() {
while (true) {
WatchKey key;
try {
key = watcher().take(); <<< HANGS HERE IN TOMCAT, DOESN'T HANG HERE IN ECLIPSE.
} catch (InterruptedException | ClosedWatchServiceException e) {
break;
}
try {
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
WatchEvent<Path> pathEvent = (WatchEvent<Path>)event;
if (pathEvent.context().toString().equals(watchedFile.getName()) {
// Do something.
}
}
}
} catch (Exception e) {
throw new RuntimeException("Trouble: " + e.getMessage(), e);
}
if (!key.reset()) {
break;
}
}
}
}
UPDATE: . The problem was that I was writing to the file from outside Docker, so the change event wasn’t seen.
It’s similar to Java WatchService not generating events while watching mapped drives.

Error in uploading a file using Jersey rest service

I am using jersey for building rest service which will upload a file. But I am facing problem in writing a file to required location. Java throws a system cannot find specified path error. Here is my Web service :
#POST
#Path("/fileupload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(#FormDataParam("file")InputStream fileUploadStream, #FormDataParam("file")FormDataContentDisposition fileDetails) throws IOException{
StringBuilder uploadFileLocation= new StringBuilder();
uploadFileLocation.append("c:/logparser/webfrontend/uploads");
uploadFileLocation.append("/"+dateFormat.format(Calendar.getInstance().getTime()));
uploadFileLocation.append("/"+fileDetails.getFileName());
writeToFile(fileUploadStream, uploadFileLocation.toString());
return Response.status(200).entity("File saved to " + uploadFileLocation).build();
}
private void writeToFile(InputStream uploadInputStream, String uploadFileLocation)
{
log.debug("UploadService , writeToFile method , start ()");
try{
int read = 0;
byte[] bytes = new byte[uploadInputStream.available()];
log.info("UploadService, writeToFile method , copying uploaded files.");
OutputStream out = new FileOutputStream(new File(uploadFileLocation));
while ((read = uploadInputStream.read(bytes)) != -1)
{
out.write(bytes, 0, read);
}
out.flush();
out.close();
}
catch(Exception e)
{
log.error("UploadService, writeToFile method, error in writing to file "+e.getMessage());
}
}
From looking at just the code (it's usually helpful to include the exception and stack trace), you're trying to write to a directory based on a timestamp which doesn't exist yet. Try adding a call to File.mkdir/mkdirs. See this question/answer: FileNotFoundException (The system cannot find the path specified)
Side note - Unless you have a reason not to, I'd consider using something like Apache commons-io(FileUtils.copyInputStreamToFile) to do the writing.

opennlp with netbeans is not giving output

How to use opennlp with netbeans. I made a small program as given in apache document but it is not working. I have set path to the opennlp bin as stated in the apache document but still i m not geting an output. it is not able to find .bin and hence SentenceModel model.
package sp;
public class Sp {
public static void main(String[] args) throws FileNotFoundException {
InputStream modelIn ;
modelIn = new FileInputStream("en-token.bin");
try {
SentenceModel model = new SentenceModel(modelIn);
}
finally {
if (modelIn != null) {
try {
modelIn.close();
}
catch (IOException e) {
}
}
}
}
}
The current working directory when you run in Netbeans is the base project directory (the one with build.xml in it). Place your .bin file there, and you should be able to open the file like that.