I use wicket in my webapplication. I save the Strings in some .properties files as follows:
foo.properties
page.label=dummy
In the html-file, I can acces the String page.label as follows:
index.html
<wicket:message key="page.label">Default label</wicket:message>
Now I wrote some junit test cases for my Application and would like to access the Strings saved in the properties file. My Question is, how to read the String from the properties file?
Try this
import java.io.FileInputStream;
import java.util.Properties;
public class MainClass {
public static void main(String args[]) throws IOException {
Properties p = new Properties();
p.load(new FileInputStream("foo.properties"));
Object label = p.get("page.label");
System.out.println(label);
}
}
This section allow you to read all properties files from wherever you want and load them in the Properties
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class MainClass {
private static String PROPERTIES_FILES_PATHNAME = "file:///Users/ftam/Downloads/test/";// for mac
public static void main(String args[]) throws Exception {
Properties p = new Properties();
List<File> files = getFiles();
for(File file : files) {
FileInputStream input = new FileInputStream(file);
p.load(input);
}
String label = (String) p.get("page.label");
System.out.println(label);
}
private static List<File> getFiles() throws IOException, URISyntaxException {
List<File> filesList = new ArrayList<File>();
URL[] url = { new URL(PROPERTIES_FILES_PATHNAME) };
URLClassLoader loader = new URLClassLoader(url);
URL[] urls = loader.getURLs();
File fileMetaInf = new File(urls[0].toURI());
File[] files = fileMetaInf.listFiles();
for(File file : files) {
if(!file.isDirectory() && file.getName().endsWith(".properties")) {
filesList.add(file);
}
}
return filesList;
}
}
Wicket has its own way of localizing the resource, taking into account the component tree. See the javadoc for the StringResourceLoader.
One way of loading the Resource would be:
WicketTester tester = new WicketTester(new MyApplication());
tester.startPage(MyPage.class);
Localizer localizer = tester.getApplication().getResourceSettings()
.getLocalizer();
String foo = localizer.getString("page.label",tester.getLastRenderedPage(), "")
Using Apache Commons Configuration is a pretty good choice!
You can use load and then get("page.label")
Have this field inside your class:
import java.util.ResourceBundle;
private static ResourceBundle settings = ResourceBundle.getBundle("test",Locale.getDefault());
then a test.properties file like this:
com.some.name=someValueHere
Finally you can access the property values this way:
private String fieldName = settings.getString("com.some.name");
Related
It is possible to update individual files in a JAR file using the jar command as follows:
jar uf TicTacToe.jar images/new.gif
Is there a way to do this programmatically?
I have to rewrite the entire jar file if I use JarOutputStream, so I was wondering if there was a similar "random access" way to do this. Given that it can be done using the jar tool, I had expected there to be a similar way to do it programmatically.
It is possible to update just parts of the JAR file using Zip File System Provider available in Java 7:
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
public class ZipFSPUser {
public static void main(String [] args) throws Throwable {
Map<String, String> env = new HashMap<>();
env.put("create", "true");
// locate file system by using the syntax
// defined in java.net.JarURLConnection
URI uri = URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip");
try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
Path externalTxtFile = Paths.get("/codeSamples/zipfs/SomeTextFile.txt");
Path pathInZipfile = zipfs.getPath("/SomeTextFile.txt");
// copy a file into the zip file
Files.copy( externalTxtFile,pathInZipfile,
StandardCopyOption.REPLACE_EXISTING );
}
}
}
Yes, if you use this opensource library you can modify it in this way as well.
https://truevfs.java.net
public static void main(String args[]) throws IOException{
File entry = new TFile("c:/tru6413/server/lib/nxps.jar/dir/second.txt");
Writer writer = new TFileWriter(entry);
try {
writer.write(" this is writing into a file inside an archive");
} finally {
writer.close();
}
}
I have to move files from one directory to other directory.
Am using property file. So the source and destination path is stored in property file.
Am haivng property reader class also.
In my source directory am having lots of files. One file should move to other directory if its complete the operation.
File size is more than 500MB.
import java.io.File;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import static java.nio.file.StandardCopyOption.*;
public class Main1
{
public static String primarydir="";
public static String secondarydir="";
public static void main(String[] argv)
throws Exception
{
primarydir=PropertyReader.getProperty("primarydir");
System.out.println(primarydir);
secondarydir=PropertyReader.getProperty("secondarydir");
File dir = new File(primarydir);
secondarydir=PropertyReader.getProperty("secondarydir");
String[] children = dir.list();
if (children == null)
{
System.out.println("does not exist or is not a directory");
}
else
{
for (int i = 0; i < children.length; i++)
{
String filename = children[i];
System.out.println(filename);
try
{
File oldFile = new File(primarydir,children[i]);
System.out.println( "Before Moving"+oldFile.getName());
if (oldFile.renameTo(new File(secondarydir+oldFile.getName())))
{
System.out.println("The file was moved successfully to the new folder");
}
else
{
System.out.println("The File was not moved.");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
System.out.println("ok");
}
}
}
My code is not moving the file into the correct path.
This is my property file
primarydir=C:/Desktop/A
secondarydir=D:/B
enter code here
Files should be in B drive. How to do? Any one can help me..!!
Change this:
oldFile.renameTo(new File(secondarydir+oldFile.getName()))
To this:
oldFile.renameTo(new File(secondarydir, oldFile.getName()))
It's best not to use string concatenation to join path segments, as the proper way to do it may be platform-dependent.
Edit: If you can use JDK 1.7 APIs, you can use Files.move() instead of File.renameTo()
Code - a java method:
/**
* copy by transfer, use this for cross partition copy,
* #param sFile source file,
* #param tFile target file,
* #throws IOException
*/
public static void copyByTransfer(File sFile, File tFile) throws IOException {
FileInputStream fInput = new FileInputStream(sFile);
FileOutputStream fOutput = new FileOutputStream(tFile);
FileChannel fReadChannel = fInput.getChannel();
FileChannel fWriteChannel = fOutput.getChannel();
fReadChannel.transferTo(0, fReadChannel.size(), fWriteChannel);
fReadChannel.close();
fWriteChannel.close();
fInput.close();
fOutput.close();
}
The method use nio, it make use os underling operation to improve performance.
Here is the import code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
If you are in eclipse, just use ctrl + shift + o.
Am using a YaHP-Converter to convert HTML File to Pdf. Here is the code example i have used for converting. The code works me fine. But i want open Pdf file after this conversion.
Any idea please.
CYaHPConverter converter = new CYaHPConverter();
FileOutputStream out = new FileOutputStream(pdfOut);
Map properties = new HashMap();
List headerFooterList = new ArrayList();
properties.put(IHtmlToPdfTransformer.PDF_RENDERER_CLASS,IHtmlToPdfTransformer.FLYINGSAUCER_PDF_RENDERER);
converter.convertToPdf(htmlContents,
IHtmlToPdfTransformer.LEGALL,
headerFooterList,
"file:///D:/temp/",
out,
properties);
Thanks in advance
I think this helps:
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
// http://www.allcolor.org/YaHPConverter/
import org.allcolor.yahp.converter.CYaHPConverter;
import org.allcolor.yahp.converter.IHtmlToPdfTransformer;
public class HtmlToPdf_yahp_2 {
public static void main(String ... args ) throws Exception {
String root = "c:/temp/html";
String input = "file_1659686.htm"; // need to be charset utf-8
htmlToPdfFile(new File(root, input),
new File(root, input + ".pdf"));
System.out.println("Done");
}
public static void htmlToPdfFile(File htmlIn, File pdfOut) throws Exception {
Scanner scanner =
new Scanner(htmlIn).useDelimiter("\\Z");
String htmlContents = scanner.next();
CYaHPConverter converter = new CYaHPConverter();
FileOutputStream out = new FileOutputStream(pdfOut);
Map properties = new HashMap();
List headerFooterList = new ArrayList();
properties.put(IHtmlToPdfTransformer.PDF_RENDERER_CLASS,
IHtmlToPdfTransformer.FLYINGSAUCER_PDF_RENDERER);
//properties.put(IHtmlToPdfTransformer.FOP_TTF_FONT_PATH, fontPath);
converter.convertToPdf(htmlContents,
IHtmlToPdfTransformer.A4P,
headerFooterList,
"file:///temp/html/",
out,
properties);
out.flush();
out.close();
}
}
See this for futher info:
http://www.rgagnon.com/javadetails/java-convert-html-to-pdf-using-yahp.html
I use the JDOM library. When I write information into an xml file, Eclipse shows errors. The system cannot find the path specified. I try to create the file in the "language" folder. How can I create the folder automatically when I write info into this file? I think the error is in this line:
FileWriter writer = new FileWriter("language/variants.xml");
Here is my code:
package test;
import java.io.FileWriter;
import java.util.LinkedList;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
class Test {
private LinkedList<String> variants = new LinkedList<String>();
public Test() {
}
public void write() {
Element variantsElement = new Element("variants");
Document myDocument = new Document(variantsElement);
int counter = variants.size();
for(int i = 0;i < counter;i++) {
Element variant = new Element("variant");
variant.setAttribute(new Attribute("name",variants.pop()));
variantsElement.addContent(variant);
}
try {
FileWriter writer = new FileWriter("language/variants.xml");
XMLOutputter outputter = new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
outputter.output(myDocument,writer);
writer.close();
}
catch(java.io.IOException exception) {
exception.printStackTrace();
}
}
public LinkedList<String> getVariants() {
return variants;
}
}
public class MyApp {
public static void main(String[] args) {
Test choice = new Test();
choice.write();
}
}
Here is the error:
java.io.FileNotFoundException: language\variants.xml (The system cannot find the path specified)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
at java.io.FileOutputStream.<init>(FileOutputStream.java:104)
at java.io.FileWriter.<init>(FileWriter.java:63)
at test.Test.write(MyApp.java:31)
at test.MyApp.main(MyApp.java:49)`enter code here
As the name suggests FileWriter is for writing to file. You need to create the directory first if it doesnt already exist:
File theDir = new File("language");
if (!theDir.exists()) {
boolean result = theDir.mkdir();
// Use result...
}
FileWriter writer = ...
For creating directories you need to use mkdir() of File class.
Example:
File f = new File("/home/user/newFolder");
f.mkdir();
It returns a boolean: true if directory created and false if it failed.
mkdir() also throws Security Exception if security manager exists and it's checkWrite() method doesn't allow the named directory to be created.
PS: Before creating directory, you need to validate if this directory already exists or not by using exists() which also returns boolean.
Regards...
Mr.777
Something is wrong and it is very frustrating. I read on velocity's homepage that when I run a webapp then some properties should be set. And I've done that but no matter what I do I keep getting the same error.
This is where I set the props and use velocity
public class ConfirmationMailGenerator implements MailGenerator {
private BasicUser user;
private String htmlTemplate = "HTMLConfirmationMailTemplate.vsl";
private String plainTemplate = "PlainConfirmationMailTemplate.vsl";
public ConfirmationMailGenerator(BasicUser user) {
this.user = user;
}
public StringWriter generateHTML() throws Exception {
Properties props = new Properties();
props.setProperty("resource.loader", "wepapp");
props.setProperty("webapp.resource.loader.class", "org.apache.velocity.tools.view.WebappResourceLoader");
props.setProperty("webapp.resource.loader.path", "/WEB-INF/mailtemplates/");
VelocityEngine engine = new VelocityEngine(props);
VelocityContext context = new VelocityContext();
engine.init();
Map map = createDataModel();
context.put("user", map);
Template template = engine.getTemplate(htmlTemplate);
StringWriter writer = new StringWriter();
template.merge(context, writer);
return writer;
}
...
}
The files is of course saved in /WEB-INF/mailtemplates/.
If I use this I get this error:
SEVERE: ResourceManager : unable to find resource 'HTMLConfirmationMailTemplate.vsl' in any resource loader.
SEVERE: The log message is null.
Thank you for your time:)
You are using the Webapp resourceloader, which is intended for pages served by the Velocity Tools servlet. (It requires some special initialization to find the root of the servlet context).
I recommend you use the ClasspathResourceLoader, then put the files into WEB-INF/classes, or elsewhere in your classpath. This is really the most straight forward approach.
resource.loader = class
class.resource.loader.class = org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
More info is here:
https://velocity.apache.org/engine/1.7/apidocs/org/apache/velocity/runtime/resource/loader/ClasspathResourceLoader.html
Will Glass answer is correct, but the configuration should be:
resource.loader = class
class.resource.loader.class = org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
Note the class at the beginning of the second line. See the links provided by him for more details!.
Note: Making an answer instead of a comment due to privileges.
Velocity is probably using the class loader to find those files. I'd recommend putting them in WEB-INF/classes, which is in the CLASSPATH by default.
I am fine it as follow,
In velocity.properties file
resource.loader=class, file
class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
file.resource.loader.class=org.apache.velocity.runtime.resource.loader.FileResourceLoader
file.resource.loader.path=vm_template
runtime.log.logsystem.class=org.apache.velocity.runtime.log.SimpleLog4JLogSystem
runtime.log.logsystem.log4j.category=velocity
input.encoding=UTF-8
output.encoding=UTF-8
And at my java class
import java.io.StringWriter;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.tools.generic.DateTool;
import org.apache.velocity.tools.generic.EscapeTool;
import org.apache.velocity.tools.generic.LoopTool;
import org.apache.velocity.tools.generic.MathTool;
import org.apache.velocity.tools.generic.NumberTool;
import org.apache.velocity.tools.generic.SortTool;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class VelocitySupport implements InitializingBean {
private static Logger log = Logger.getLogger(VelocitySupport.class);
#Autowired private Properties properties;
public final void afterPropertiesSet() throws Exception {
location = location.replace("classpath:", "");
Resource res = new ClassPathResource(location);
Properties prop = new Properties();
prop.load(res.getInputStream());
String staticDir = System.getProperty("staticDir");
String tempPath = prop.getProperty("file.resource.loader.path");
tempPath = staticDir + "/" + tempPath;
prop.setProperty("file.resource.loader.path", tempPath);
Velocity.init(prop);
}
public static String merge(final String template, final VelocityContext vc) throws Exception {
try {
vc.put("date", new DateTool());
vc.put("escape", new EscapeTool());
vc.put("math", new MathTool());
vc.put("number", new NumberTool());
vc.put("iterate", new LoopTool());
vc.put("sort", new SortTool());
Template temp = Velocity.getTemplate(template);
StringWriter sw = new StringWriter();
temp.merge(vc, sw);
sw.flush();
return sw.toString();
}
catch (ResourceNotFoundException e) {
log.error("", e);
throw e;
}
catch (ParseErrorException e) {
log.error("", e);
throw e;
}
}
private String location;
public final void setLocation(final String location) {
this.location = location;
}
}
And insert VM arguments of project as follow..
-DstaticDir= "your directory for template path"
That may be helpful for you...
For resolving this error
--WEB-INF/classes and all the JARs in WEB-INF/lib are in the CLASSPATH. Try moving your folder with the .vm files under WEB-INF/classes
--dont put the abolute path eg. if abc.vm file is in /public_html/WEB-INF folder then put path = "/public_html/WEB-INF/abc.vm" for velocity template path.