I am getting the error
URI scheme is not “file”
after I run the plugin that I am trying to create. The error is thrown from the following method :
protected File getFile(String fileName) throws URISyntaxException {
System.out.println(fileName);
URI binUri = EpsilonStandaloneExample.class.getResource(fileName).toURI();
URI uri = null;
System.out.println(uri);
if (binUri.toString().indexOf("bin") > -1) {
uri = new URI(binUri.toString().replaceAll("bin", "src"));
}
else {
uri = binUri;
}
System.out.println(uri);
return new File(uri);
}
When I run my class as a java application everything is working and i am getting the right path which is:
file:/E:/epsilon-eclipse/workspace/Test2/src/org/eclipse/epsilon/examples/standalone/egl/oxfordDriver.egl
Now that i am implementing a plugin and run this code the URI returned is:
bundleresource://652.fwk1463565218/org/eclipse/epsilon/examples/standalone/egl/oxfordDriver.egl
This URI is not correct and thats why the error is thrown.
Any suggestions of how to solve this problem?
I assume you want to load a file which is part of the resources in your plugin. This is not possible using a file path, as all resources in a plugin are resolved using a bundle relative URL (and the bundle itself might be deployed as jar file, so there even isn't a normal file). Have a look at reading resources from a plugin.
Also make sure that you add those files to your build.properties (see section "Binary build"). It is not enough to have the files lying around in the plugin project.
Related
I'm trying to get a load a mp4 file from the android file browser. However the path from the following code does not work. It throws an exception
Uri currFileURI = data.getData();
String path=currFileURI.getPath();
MediaExtractor extractor = new MediaExtractor();
try {
extractor.setDataSource(path);
} catch( IOException e) {
e.printStackTrace();
return;
}
Data I have:
data = {Intent#9869} "Intent { dat=content://com.android.providers.downloads.documents/document/44 flg=0x1 }"
currFileURI = {Uri$HierarchicalUri#9870} "content://com.android.providers.downloads.documents/document/44"
path = "/document/44"
I see this code in stackoverflow:
How to get the Full file path from URI
This looks like an overkill
I can see the method takes in a file path.
https://developer.android.com/reference/android/media/MediaExtractor#setDataSource(java.lang.String)
So it looks the path from the android file browser is different from what the method wants. I also see that the path from the file browser is different than the file name. Anybody have an insight into what the path should look like?
So it looks the path from the android file browser is different from what the method wants
It is not a filesystem path, because a Uri is not a file.
I can see the method takes in a file path
There are many forms of setDataSource() on MediaExtractor, including one that takes a Uri. Try using that method with your Uri.
I've recently inherited a Java API and am having trouble with file uploads. Unfortunately, Java isn't a language I have much experience in so I'm a bit stumped by this.
The MultiPartFile is being received ok, and I can find the file in the temp directory, but when I try to use File.transferTo() to create the final file I just get the below error;
java.nio.file.NoSuchFileException: C:\Users\myUser\AppData\Local\Temp\undertow3706399294849267898upload -> S:\Dev\PolicyData\Temp.xlsx
As I mentioned the temp undertow file exists, and the directory on the S drive also exist, (but there's no Temp.xlsx as my understanding is this should be created by transferTo()). Any solutions I've found to this problem so far are resolved using absolute file paths.
This is a simplified version of the code but the error remains the same.
SpringBoot framework is "1.5.3.RELEASE", running Java 1.8.0_131
ResponseEntity handleFileUpload(#RequestPart(name = "file") MultipartFile file, #PathVariable Long stageFileTypeId) {
if (!file.isEmpty()) {
try {
String filePath = "S:\\Dev\\PolicyData\\Temp.xlsx";
log.info("Upload Path = {}", filePath);
File dest = new File(filePath);
file.transferTo(dest);
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(filePath));
}
catch (Exception ex) {
log.error("An error has occurred uploading the file", ex);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
else {
log.error("An error has occurred, no file was received");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
If you need any more information please let me know.
Thanks,
Neil
The API for MultipartFile is a bit tricky. The transferTo(File) method javadoc states that (bold are mine):
This may either move the file in the filesystem, copy the file in the
filesystem, or save memory-held contents to the destination file. If
the destination file already exists, it will be deleted first.
If the target file has been moved in the filesystem, this operation
cannot be invoked again afterwards. Therefore, call this method just
once in order to work with any storage mechanism.
It seems that the Undertow implementantion already called it to move the in-memory uploaded file to "C:\Users\myUser\AppData\Loca\Temp\undertow3706399294849267898upload" so another transferTo is failing.
I came across the same problem using javax.servlet.http.Part in a Wildfly containter with Undertow.
If you are using Spring framework >= 5.1, you could try the Multipart.transferTo(Path) method, using dest.toPath()
Or you can copy from the inputStream, with something like this:
try (InputStream is = multipartFile.getInputStream()) {
Files.copy(is, dest.toPath());
}
I have a maven project with this structure:
parent
-----module1
--------src
------------main
-----------------java
----------------------Loader.java
-----------------resources
-------------------------file1.txt
-----module2
--------src
------------main
-----------------java
-------------------------CallLoader.java
So Loader.java, loads files1.txt. I call this class from CallLoader.java from module2. This is the code I used
In Loader.java,
private static File getResourceFile(String fileName){
try {
URL resource = GraphUtil.class.getClassLoader().getResource(fileName);
return new File(resource.getPath());
} catch (Throwable e) {
throw new RuntimeException("Couldn't load resource: "+fileName, e);
}
}
where fileName="file1.txt".
I get an error because the file absolute path looks like this:
file:/home/moha/.m2/repository/my/package/name/%7Bproject.version%7D/base-%7Bproject.version%7D.jar!/file1.txt
What exactly am I doing wrong?
Get the content of your file as a stream instead in order to be able to read your resource from a jar file which is the root cause of your issue. In other words use getResourceAsStream instead of getResource.
You can also return the URL instead of File then call openStream() later to read it if needed.
NB1: the URL will be of type jar:file/... which cannot be managed by the class File
NB2: To convert a URL into a File, the correct code is new File(resource.toURI())
I'm asking this here because googling this error only gives me hits on writing a zip file, while I'm only trying to read it.
I have a unit test where I'm trying to test the following production code:
Map<String, String> zipProps = new HashMap<>();
URI zipUri = URI.create("jar:file:" + itemZipPath.toString());
try (FileSystem zipfiles = FileSystems.newFileSystem(zipUri, zipProps)) {
// do stuff...
} catch (IOException e) {
// log an error
}
However this fails on the line containing the try:
java.util.zip.ZipError: zip END header not found
at com.sun.nio.zipfs.ZipFileSystem.zerror(ZipFileSystem.java:1605)
at com.sun.nio.zipfs.ZipFileSystem.findEND(ZipFileSystem.java:1021)
at com.sun.nio.zipfs.ZipFileSystem.initCEN(ZipFileSystem.java:1030)
at com.sun.nio.zipfs.ZipFileSystem.<init>(ZipFileSystem.java:130)
at com.sun.nio.zipfs.ZipFileSystemProvider.newFileSystem(ZipFileSystemProvider.java:117)
at java.nio.file.FileSystems.newFileSystem(FileSystems.java:326)
at java.nio.file.FileSystems.newFileSystem(FileSystems.java:276)
at com.company.PageCommandHandler$ProvisioningSteps.getItemModel(PageCommandHandler.java:105)
I've tried creating the zipfile using both OSX's zip utility and using jar cvf but both fail (the output of file <filename> differs slightly however).
All the information about this error I can find relates to creating a zipfile using Java NIO, but as you can see I'm only doing a read (verifying the presence of a certain file inside the ZIP for now).
Any thoughts on what is going wrong here?
I've met exactly the same error. Java 8. The reason was, by mistake I created an empty file, not only object:
File zipFile = new File(path);
zipFile.createNewFile();
An then passed this path to
URI uri = URI.create("jar:file:" + zipFile.getAbsolutePath());
To fix it, I did not create file itself, only created a File object:
File zipFile = new File(path);
URI uri = URI.create("jar:file:" + zipFile.getAbsolutePath());
To make it more reliable I would offer to delete file first if it exists:
File zipFile = new File(path);
//Caused by: java.util.zip.ZipError: zip END header not found
if (zipFile.exists()){
try {
Files.delete(Paths.get(zipFile.getAbsolutePath()));
} catch (IOException e) {
throw new IllegalStateException(
"Could not delete file.", e);
}
}
...
URI uri = URI.create("jar:file:" + zipFile.getAbsolutePath());
Probably in some case the solution with deletion of the file is not acceptable. For instance, if you add to the same zip file several entries. But in my use case it is OK.
I tried using the normal ZipInputStream and related classes, but kept having issues, so the problem did not seem related to NIO.
A colleague of mine found this question on SO: Extracting zipped file from ResourceStream throws error "Invalid stored block lengths"
So I tried adding this snippet to my pom.xml as well:
<properties>
<project.build.sourceEncoding>ISO-8859-1</project.build.sourceEncoding>
</properties>
After this, all problems disappeared and all my tests turned green. I did not revert back to NIO as I was happy enough getting to a working solution, but I'm pretty sure this would solve the problem on NIO as well.
Posted here in hopes that it helps somebody having the same issue some day.
Sometimes it's Gradle issue
Go to YOUR_PROJECT_DIRECTORY\android\gradle\wrapper
Open the file
gradle-wrapper.properties
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-all.zip
Last line update with Gradle
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-all.zip
Then it will work
Other options you can check now
\android\build.gradle
dependencies {
classpath 'com.android.tools.build:gradle:3.5.4'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.3.5'
}
to
dependencies {
classpath 'com.android.tools.build:gradle:4.2.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.3.5'
}
I am using Spring Framework's MultipartFile to allow a user to upload a picture to a profile. I've configured DispatcherServlet in a servlet initializer class that extends AbstractAnnotationConfigDispatcherServletInitializer. In that class, I've overridden the customizeRegistration() method as follows:
#Override
protected void customizeRegistration(Dynamic registration) {
registration.setMultipartConfig(new MultipartConfigElement("/tmp/practicewellness/uploads", 2097152, 4194304, 0));
}
The MultipartFile's transferTo() method calls for a file location in the filesystem where the uploaded file will be written temporarily. Can this location be anywhere? When I used the following location in the method:
profilePicture.transferTo(new File("tmp/practicewellness/" + employee.getUsername() + ".jpg"));
... I get the following error:
Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.io.IOException: The temporary upload location [C:\Users\kyle\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\work\Catalina\localhost\practicewellness\tmp\practicewellness\uploads] is not valid
So I can see that it's looking for this file location deep inside one of my Eclipse plugins. I don't understand why it looks there. When I look there, the "tmp" directory is not there. But regardless, is it okay for me to go into that plugin and create the directory there? Or is there a better way to smooth this out?
I've uploaded files using Spring mvc, but never used transferTo(), I just assume that your problem is due to "No existence of specified path" because there wont be a path ending with .jpg. Try it like this.
String path = "/tmp/practicewellness/";
File dirPath = new File(path);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
And then execute the transferTo() code.
Also do not set the path directly like you've done. Since you're doing it in spring, so I assume you want the folder to be in your Project path not the eclipse's metadata path. So change your path to this.
String path = request.getSession().getServletContext().getRealPath("/tmp/practicewellness/");
It will create a folder inside your Project's Webapp folder using mkdir. If you want to save differentiate the files for each user, you can create a folder for each user by using this below path.
String path = request.getSession().getServletContext().getRealPath("/tmp/practicewellness")+"/"+employee.getUsername()+"/";