I am trying to use XmlTool to parse an XML file to be able to use the data in a Velocity template.
However, the documentation on it is all pretty poor and doesn't really give the information I need.
The documentation is at: https://velocity.apache.org/tools/devel/apidocs/org/apache/velocity/tools/generic/XmlTool.html
And I have tried:
VelocityContext context = new VelocityContext(page);
EasyFactoryConfiguration config = new EasyFactoryConfiguration();
config.toolbox("application")
.tool("org.apache.velocity.tools.generic.XmlTool")
.property("safeMode", false)
.property("key", "foo")
.property("file", xmlFilePath);
ToolboxFactory factory = config.createFactory();
template = Velocity.getTemplate(page.get("template-file"));
template.merge(context, write);
return write.toString();
But this is not working.
How do I make the data actually make it's way to my template? I feel like I am missing so many steps, but just can't find the information I need!
Well my co-worker who is the smarter one who should have been doing this in the first place figured it out.
XmlTool tool = new XmlTool();
tool = tool.read(dataFile.getAbsolutePath());
context.put("foo", tool);
Related
in a Scala research application, i load a hocon file using PureConfig's ConfigSource.file() method, which represents the default configuration for a research experiment. i use this to build a batch of variations dynamically. after making a few modifications related to a specific experimental variation, i then parse the config into a case class structure using pureconfig's auto parser.
at this point, i would like to save the modified Config to my experiment directory as a hocon file, so i can easily re-create this experiment in the future.
i have been looking around the typesafe config README.md and haven't seen anything on this. clearly, i could write a function to pretty-print the config tree to a hocon format, but, is there a way to do this hidden somewhere in the typesafe config API?
Here a solution I came up with that only depends on the Typesafe Config library:
val config = ConfigFactory.parseResources("application.conf")
val otherConfig = ConfigFactory.parseResources("other.conf")
val mergedConf = config.withFallback(otherConfig)
val options = ConfigRenderOptions
.defaults()
.setJson(false) // false: HOCON, true: JSON
.setOriginComments(false) // true: add comment showing the origin of a value
.setComments(true) // true: keep original comment
.setFormatted(true) // true: pretty-print result
val result = mergedConf.root().render(options)
println(result)
This is straight forward:
import pureconfig._
import pureconfig.generic.auto._
val configValue = ConfigWriter[YourCaseClass].to(component)
val configString = configValue.render()
This will create a String of your configuration.
There is one big limitation: It renders JSON.
Here is the according documentation: config-writer
EDIT: I changed my mind. I would find a way to generate the Java class and load the JSON as an object of that class.
I just discovered that exists a variant of JSON called JSON-LD.
It seems to me a more structured way of defining JSON, that reminds me XML with an associated schema, like XSD.
Can I create a Java class from JSON-LD, load it at runtime and use it to convert JSON-LD to an instantiation of that class?
I read the documentation of both the implementations but I found nothing about it. Maybe I read them bad?
Doing a Google search brought me to a library that will decode the JSON-LD into an "undefined" Object.
// Open a valid json(-ld) input file
InputStream inputStream = new FileInputStream("input.json");
// Read the file into an Object (The type of this object will be a List, Map, String, Boolean,
// Number or null depending on the root object in the file).
Object jsonObject = JsonUtils.fromInputStream(inputStream);
// Create a context JSON map containing prefixes and definitions
Map context = new HashMap();
// Customise context...
// Create an instance of JsonLdOptions with the standard JSON-LD options
JsonLdOptions options = new JsonLdOptions();
// Customise options...
// Call whichever JSONLD function you want! (e.g. compact)
Object compact = JsonLdProcessor.compact(jsonObject, context, options);
// Print out the result (or don't, it's your call!)
System.out.println(JsonUtils.toPrettyString(compact));
https://github.com/jsonld-java/jsonld-java
Apparently, it can take it from just a string as well, as if reading it from a file or some other source. How you access the contents of the object, I can't tell. The documentation seems to be moderately decent, though.
It seems to be an active project, as the last commit was only 4 days ago and has 30 contributors. The license is BSD 3-Clause, if that makes any difference to you.
I'm not in any way associate with this project. I'm not an author nor have I made any pull requests. It's just something I found.
Good luck and I hope this helped!
see this page: JSON-LD Module for Jackson
I really wonder how this would be done properly(*):
FileHandle file = Gdx.files.local("test.json");
Json json = new Json(JsonWriter.OutputType.json);
JsonWriter writer = new JsonWriter(new StringWriter());
json.setWriter(writer);
json.writeObjectStart();
json.writeValue("name", "Testing");
json.writeObjectEnd();
file.writeString(..., false); // Here I am stuck
As you can see I want to manually (!) create a json object and write just one string in there. I do not want to use a serializer or anything the like for this matter.
In https://github.com/libgdx/libgdx/wiki/Reading-&-writing-JSON there is a passage: Serialization Methods
In there the same is done. But how can I translate my Json to a String that can be written to a file? toString() is doing no good here.
(*) Once again, I want to emphasize I do NOT want to use a serializer in that case but build my own json-file from scratch. I'm totally aware of the problems and unmanagable-code this could lead to. Thank you!
The following is an example of what I want to do.
I have a bunch of files such as test1.vm:
Welcome ${name}. This is test1.
Then I have a file called defaults.vm:
#set($name = "nmore")
I want render test1.vm (and the other test files) with the variable(s) in defaults.vm without using #parse as I would have to modify all the test files.
Is there a way to do this from within the accompanying java file?
I'm not sure if you have any constraints or any other specific requirements, but if you don't have you tried to use Velocity API? Something like this:
Context context = new VelocityContext();
Template template = Velocity.getTemplate("src/main/resources/defaults.vm");
template.merge(context, NullWriter.NULL_WRITER);
StringWriter writer = new StringWriter();
Template toBeParsedTemplate = Velocity.getTemplate("src/main/resources/test1.vm");
toBeParsedTemplate.merge(context, writer);
String renderedContent = writer.getBuffer().toString();
System.out.println(renderedContent);
The idea is that you fill in the Context object with the variables generated from defaults.vm and use the same context to evaluate test1.vm.
I've tried this using Velocity 1.7 and commons-io 2.4 (for the NullWriter) seems to be working fine, but I'm not sure if this can fit into your requirement or you're looking into other alternatvies (not using Velocity API).
More info on the Context object here:
http://velocity.apache.org/engine/devel/developer-guide.html#The_Context
Hope that helps.
I have about 3200 URLs to small XML files which have some data in the form of strings(obviously).The XML files are displayed(not downloaded) when I go to the URLs. So I need to extract some data from all those XMLs and save it in a single .txt file or XML file or whatever. How can I automate this process?
*Note: This is what the files look like. I need to copy the 'location' and 'title' from all of them and put them in one single file. Using what methodology can this be achieved?
<?xml version="1.0"?>
-<playlist xmlns="http://xspf.org/ns/0/" version="1">
-<tracklist>
<location>http://radiotool.com/fransn.mp3</location>
<title>France, Paris radio 104.5</title>
</tracklist>
</playlist>
*edit: Fixed XML.
It's easy enough with XQuery or XSLT, though the details will depend on how the URLs are held. If they're in a Java List, then (with Saxon at least) you can supply this list as a parameter to the following query:
declare variable urls as xs:string* external;
<data>{
for $u in $urls return doc($u)//*:tracklist
}</data>
The Java code would be something like:
Processor proc = new Processor();
XQueryCompiler c = proc.newXQueryCompiler();
XQueryEvaluator q = c.compile($query).load();
List<XdmItem> urls = new ArrayList();
for (url : inputUrls) {
urls.append(new XdmAtomicValue(url);
}
q.setExternalVariable(new QName("urls"), new XdmValue(urls));
q.setDestination(...)
run();
Have a look at the JSoup library here: http://jsoup.org/
It has facilities for pulling and fixing the contents of a URL, it is intended for HTML though, so I'm not sure it will be good for XML, but it is worth a look.