How to read resource file from classpath in BlackBerry app? - blackberry

I need to read a resource file from classpath in my BlackBerry application. The directory structure of my project is pretty common: under src directory there are 2 child dirs, one represents source packages root, another - resources root.
When I try to read any resource from classpath Class.getResourceAsStream method retures null
InputStream rStream = null;
String path = "/res/default_config.xml";
try {
rStream = getClass().getResourceAsStream(path);
} finally {
try {
if (rStream != null) {
byte[] data = IOUtilities.streamToBytes(rStream);
System.out.println(new String(data));
rStream.close();
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
How should I read classpath resource properly?

And have you tried to put xml file directly into src folder and use getClass().getResourceAsStream("default_config.xml"); ?
Actually cannot reproduce.
Tested on simulator 8800 eJDE 4.2.1.
File was placed in src/res/ folder.

I think you specified the path as incorrect way. You just remove the / from the beginning of the path you specified. If you are specifying /. then it will check for you resource folder

Even though it's generated as a COD file for running on the device, the JAR file is also created each build. It might be worth checking to make sure your xml file is being put in the directory that you expect it to be in as you can definitely store resources in sub-directories in your application and retrieve them using getClass().getResourceArStream();

Related

Is there any way of loading local resource files in dart? (not flutter)

I want to load the bytes of a file into a variable while testing my flutter application.
I can't use the assets directory as those are bundled with the app and require WidgetsFlutterBinding.ensureInitialized();
I tried searching the file manually with the path package, but this did not seem to work and was rather hacky. That is why i'm searching for a more official approach.
I was thinking way to complicated ...
As Chuck Batson commented, you can just use the path from the projects root for passing it into the (dart:io) File:
File loadResource(String relativePath) {
final filePath = path.join("test", "resources", relativePath);
return File(filePath);
}
(Notice: The above code makes use of the path package for constructing a file path.)

Loading txt file as an asset for a dart package

In flutter it's easy to load a .txt asset at runtime by specifying it or its folder in the pubspec.yaml file and then loading it with rootBundle. However, i'm working on a pure dart package, and I'm struggling to work out how to get the package to load a .txt file relative to it's own directory structure.
When I use the package in a separate dart command line application i'm working on, the relative path that I specified in one of the package source code files causes an error to be thrown that the txt file doesn't exist. I understand why this error is being thrown, because the relative path is interpreted as being from the command line application's root directory instead of the package's root directory, but i'm unsure of how to solve this without specifying the absolute path for the .txt file. I'd rather not specify the absolute path as it makes the package less portable.
Is there anything similar to flutter's asset loading for a pure dart package?
I think you need the resolveSymbolicLinks or resolveSymbolicLinksSync methods to decode the relative path and then use the resolved path to read the txt file:
import 'dart:io';
void main() async {
String file = '../lib/main.dart';
var path = Uri.parse('.').resolveUri(Uri.file(file)).toFilePath();
print(path);
if (path == '') path = '.';
var resolved = await File(path).resolveSymbolicLinks();
print(resolved);
File(resolved).readAsString().then((String contents) {
print(contents);
});
}

Using Grails to store image but could not store outside CATALINA_HOME in production

I'm using Grails 2.5.6 to store uploaded images to folder on a server.
The following are my code to store the image
mpr.multiFileMap.file.each{fileData->
CommonsMultipartFile file = fileData
File convFile = new File(file.getOriginalFilename());
file.transferTo(convFile);
/** Processing File **/
File uploadedFile = new File("${directory}${generatedFileName}.${extension}")
convFile.renameTo(uploadedFile)
}
I have no problem running on development (MacOSX High Sierra)
But when i deployed on production (Ubuntu 14.04 server), i could not save the file outside CATALINA_HOME directory.
I have checked the permission and ownership of the destination directory, but still, the directory was created but the file was never stored.
For Example, i've tried to store the file on /home/tomcat/ directory (/home directory was in separate partition with tomcat which stored it /var), the directory was created, but the file was never stored.
When i put the destination directory within CATALINA_HOME folder, everything works fine. But this was not the scenario i want to do.
You say your destination directory is on another partition, so maybe another filesystem is used on this partition.
Or if you look on the javadoc of the renameTo method it is said :
Many aspects of the behavior of this method are inherently
platform-dependent: The rename operation might not be able to move a
file from one filesystem to another, it might not be atomic, and it
might not succeed if a file with the destination abstract pathname
already exists. The return value should always be checked to make
sure that the rename operation was successful.
...
#return true if and only if the renaming succeeded;
false otherwise
Thus I think the renameTo method is not able to move the file, don't know why but you can rewrite your code like this :
mpr.multiFileMap.file.each{fileData->
CommonsMultipartFile file = fileData
File uploadedFile = new File("${directory}${generatedFileName}.${extension}")
// String originalFilename = file.getOriginalFilename()
// you can store originalFilename in database for example
if(!uploadedFile.getParentFile().exists()) {
uploadedFile.getParentFile().mkdirs()
// You can set permissions on the target directory if you desired, using PosixFilePermission
}
file.transferTo(uploadedFile)
}

Error in loading XSL files and DTD files in XSLT transformation

I am trying to create HTML files using XSLT, I have used xml file and xsl files to create HTML file. Here some other xsl files which are located in same location are included in xsl file by using <xsl:include href="temp.xsl"/>.
Here Xsl files are located in "D:/XSL_Folder/" path.
I am running Main.java file which is located in D:/Workspace/Webapp_Project/ path.
When i try to create HTML files by using passing "D:/XSL_Folder/root.xsl" and "D:/XML_Folder/data.xml" files to Main.java as arguments, I am getting following error while creating Templates.
Templates lTemplates = TransformerFactory.newInstance().newTemplates(new StreamSource(new FileInputStream(lFileXSL)));
ERROR: 'D:\Workspace\Webapp_Project\temp.xsl (The system cannot find the file specified)'
FATAL ERROR: 'Could not compile stylesheet'
12:20:07 ERROR f.s.t.v.v2.dao.impl.DocUnitDaoImpl - Error while creating a new XslTransformerGetter. The path to the XSL may be wrong.
javax.xml.transform.TransformerConfigurationException: Could not compile stylesheet
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.newTemplates(TransformerFactoryImpl.java:885) ~[na:1.7.0_13]
In error report we can see that parser is checking included xsl file in project path (D:\Workspace\Webapp_Project), not in the path where root.xsl file is located (D:/XSL_Folder/).
Can anyone suggest me why parser searching xsl file in project folder in the path where root.xsl file is located and how to fix this problem?
Code I'm using to create HTML file by using XSL and XML file :
public static void simpleTransform(InputStream lXmlFileStream, File lXSLFile,
StreamResult lHtmlResult, Map<String, String> lArguments) {
TransformerFactory tFactory = TransformerFactory.newInstance();
try {
Transformer transformer =
tFactory.newTransformer(new StreamSource(lXSLFile));
for (Entry<String, String> lEntrie : lArguments.entrySet()) {
transformer.setParameter(lEntrie.getKey(), lEntrie.getValue());
}
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(new StreamSource(lXmlFileStream), lHtmlResult);
}
catch (Exception e) {
e.printStackTrace();
}
}
You have tagged the question "saxon", and you have said you are using XSLT 2.0, but the error messages show that you are using Xalan. If you specifically want to use Saxon then the best way is to avoid using the JAXP classpath search and instantiate Saxon directly - in place of TransformerFactory.newInstance(), use new net.sf.saxon.TransformerFactory().
Supplying a File as the argument to StreamSource ought to be OK; but I would like to see how the File lXSLFile object is created. My suspicion would be that you have done something like new File ("root.xsl") and it has been resolved relative to the current directory.
You may try to use <xsl:include href="resolve-uri('temp.xsl')"/> instead of <xsl:include href="temp.xsl"/> to avoid this problem.

read file from res folder blackberry

I want to read file from "res" folder on blackberry. The file that i used is a file javascript.
I used this code InputStream in = classs.getResourceAsStream("file.js");. But i get "could not find this path" and I use also
String srcFile = "/res/ressourcesWeb/file.js";
FileConnection srcConn = (FileConnection) Connector.open(srcFile, Connector.READ);
InputStream in = srcConn.openInputStream();
but i got an exception.
Can any one help me to read the file and give me the right path that should I use?
Your res folder has to be inside src folder to be accessed from your code.
src folder is the root folder of your project package. And all folders outside of src folder are invisible for the code at runtime.
Check this post for more details: Blackberry runtime error: FRIDG: could not find img/logo.png
There's file location principle described.
You actually do not need to put your resources under the src folder for them to be accessible from your code.
That is one way to do it, but I don't think it's the best way. Files under the src folder should really be source code, not images, or other resources. For JavaScript resources, it's debatable whether those should be under src or not. Most projects I've seen have used the src folder for only Java source code.
In any case, if you would like to keep your file (or other resources, like images) outside the src folder, you can do so. The BlackBerry plugin for Eclipse actually sets it up like this by default, when you create a new project. There is a res folder at the top level, next to (not under) src.
If you have
src\
src\com\mycompany\myapp\
res\
res\resourcesWeb\
res\resourcesWeb\file.js
Then, you can open the file like this:
String jsPath = "/resourcesWeb/file.js";
InputStream input = getClass().getResourceAsStream(jsPath);
byte [] content = IOUtilities.streamToBytes(input);
String contentAsString = new String(content);
P.S. You also can probably do this:
String jsPath = "/file.js";
InputStream input = getClass().getResourceAsStream(jsPath);
and not specify the path to the resource. Obviously, this will only work if there are no naming conflicts in your resource folders (e.g. you don't have /res/resourcesWeb/file.js and also /res/otherPath/file.js)

Resources