How do I use packages I created in java in javascript? - java

I've got a package login that has a few classes inside of it...I thought my code would look like this:
importPackage(login);
var password = document.form1.pword.value;
var hash = JPP7.toHash(password);
where JPP7 is the class of mine that does the hashing? I am using a colleagues javascript code, but I know next to nothing about javascript. Am I going to have to give an absolute path to the package folder?

(Converted from my comment above)
You cannot (at least not easily nor out-of-the-box) use Java code in Javascript. Despite the similarity in their names, they are very different and are incompatible with each other. See also What's the difference between Javascript and Java?.
There was once an implementation of the JVM in Javascript, but it seems to now be dead. I wouldn't have recommended using it in any sort of production code anyway.

Related

How to set a hostname in a jsonnet file?

I am trying to get the hang of jsonnet files. So far all I have is hard-coded values but what if I wanted to get the hostname for a Java application. For example in Java I would just do:
String hostName = System.getenv("HOSTNAME");
But obviously I can't just have a key-value pair like the following JSON in a jsonnet file.
{name: "hostname", value:System.getenv("HOSTNAME")}
I need a bit of help in understanding how I can do this.
I have looked up std.extvar(x) but the examples I look at just arent clear to me for whatever reason. Is this method relevant? Otherwise, I'm not really sure.
Jsonnet requires all parameters to be passed explicitly. To use a hostname in your Jsonnet code, you need to pass it to the interpreter. For example you can run it as follows:
❯ jsonnet --ext-str "HOSTNAME=$HOST" foo.jsonnet
foo.jsonnet:
std.extVar('HOSTNAME')
You can also use top-level-arguments mechanism to a similar effect (top-level-arguments are passed as function arguments to the evaluated script.
Please see: https://jsonnet.org/learning/tutorial.html#parameterize-entire-config for more in-depth explanation of these features.
FYI not being able to just grab any environment variable or access the system directly is very much by design. The result of Jsonnet evaluation depends only on the code and explicitly passed parameters. This has a lot of benefits, such as the following:
You can easily evaluate on another machine, even on a completely different platform and get exactly the same result.
You are never locked in to configuration on any particular machine – you can always pass any parameters on any machine (very useful for development and debugging).
Avoiding surprises – the evaluation won't break one day, because some random aspect of local configuration changed and some deep part of the code happens to depend on it – all parameters are accounted for.

Efficient java library for text templating?

I've got a simple string coming in from a UI component as The device id is %{test}. Assume %{test} is a dynamic variable and the values for it are being assigned from the backend code. The final string should look like:
The device id is some text
----------------------------^ should be replaced with %{test} and appended to the whole string
I've read a bit and tried out some of the libraries which were pointed out here, such as Velocity and FreeMarker. But I'm quite unaware in terms of efficiency and performance on using those libraries.
Hope I could get some insights on this since I'm pretty new to this. Any help could be appreciated.
I suggest you to take a look at Arco Template Engine: It compiles the template in compile-time, producing a .java (or .class) file. And so, at run-time, the expansion is done very fast.
The templates should be coded in JSP format. Thus, all variables references must be written ${variable} (not %{variable}).
The only thing to take in account is that templates must be staticly generated (in order to be processed at compile-time).
(Read the FAQ and the examples).

Best approach for automatically generating I18N key strings in Java

I've taken a look at the following post to grasp a basic idea of how to deal with I18N:
Where to place i18n key strings in Java
But more than that, I have an intention of automatically generating a Java class with constants storing key strings of I18n property files. I know it could be feasibly done using Java itself, however, I wonder which is the best approach (using Ant, Batch or something else...)?
The best approach is to give the identifiers yourself.
The ID can give hint to the translator what the string is about.
In fact, some consistency in naming convention is best:
dialog.print.title = Print
menu.file.print = Print
The two entries have to be translated differently in some languages (for instance in French it would be "Imprimer" for a button and "Impression" for a label / title).
Think it it this way: would you like to maintain some code where all variable names are machine generated?

JavaScript not being properly executed in HtmlUnit

I'm currently developing some tests with HtmlUnit. It's loading a page that contains braintree.js (their form encryption library). I have a bunch running, but I'm stuck where it calls crypto. The JS in question is:
(function() {
try {
var ab = new Uint32Array(32);
crypto.getRandomValues(ab);
sjcl.random.addEntropy(ab, 1024, "crypto.getRandomValues");
} catch (e) {}
})();
HtmlUnit is throwing:
EcmaError, ReferenceError, "'crypto' is not defined."
I suppose HtmlUnit doesn't include crypto. Would it be possible to include a crypto library myself?
Based on your comment, I have to tell you that HtmlUnit is a pain in the neck when it comes to JavaScript. It will complain a lot about variables not being defined and unknown functions and so on.
Real browsers are more flexible, eg: they accept syntactically incorrect pieces of JavaScript. HtmlUnit expects everything to be perfect without any kind of error. Furthermore, even if you didn't miss a semicolon, HtmlUnit might complain.
My advice:
Make sure your JavaScript is syntactically correct
Avoid the user of complex libraries (jQuery seems to be properly supported)
If you can use non-minimized versions of libraries it's worth giving it a try
Try to avoid complex jQuery methods (eg: adding events dynamically to elements)
And the most important one: Try switching between different BrowserVersions. Internet Explorer (ironically) has proven to provide the best results when it comes to interpreting JavaScript

java: using a variable's value as an object name (not the eval() way)

Ok, so coming from a background of mostly perl, and mostly writing dirty little apps to automate my tasks, I've read the pages about the evils of eval(), and I always use a hash (in perl). I'm currently working on a little project (mostly for me and a couple of other technical people at work), for creating "canned response" e-mails. To allow for additions, subtractions, edits, etc., I'd like to essentially describe the response form(s) in XML, and have my app parse the XML and create the response forms at runtime. I want to use Java (to integrate it into an existing Java tool that I created), and boiled down to a trivial example, what I'm trying to do is take some XML like:
<Form Name="first" Title="Title!">
<Label Name="before">Your Request:</Label>
<Textbox Name="input"/>
<Label Name="after">has been completed.</Label>
<Output>%before%%input%%after%</Output>
</Form>
<Form Name="second">
...
and from parsing that, I want to create a JFrame named first, which contains a JLabel named before with the obvious text, then a textbox, then another JLabel... you get the idea (I eventually want to use the output tag to control exactly how the response is formatted).
I can parse the XML, and get the element name and such, but I don't know how to instantiate the Objects with a name that is the value of a variable, effectively:
JFrame $(thisNode.getAttributes().getNamedItem("Name").getNodeValue()) = new JFrame(thisNode.getAttributes().getNamedItem("Title").getNodeValue());
I've read basically the whole first page of google results on java reflection, but I haven't come across anyone doing quite what I'm looking for (at least not that I could tell). Having basically zero experience with reflection, I'm curious if this is something that can be accomplished using it, or if I should take the same approach as I would in Perl, and create a HashMap or HashTable of Objects, and tie them to a entry in a Hash of JFrames. Or, I'm open to ideas that don't fall into those two categories. The Hash is sort of my stand-by answer, because I've done it in Perl plenty of times, and I'm sure I can make it work in Java, but if there's a feature (like reflection) that's made to do this task, then why not do it the way it was intended to be done?
What you're asking isn't possible in Java. It doesn't work that way and these sorts of tricks, which are common in dynamic languages, aren't the Java way. You can certainly do:
JFrame frame = JFrameBuilder.buildFromTemplate("frame.xml");
where you create a JFrameBuilder class that reads the XML and creates an object from it but the variable name can't be dynamic. You have to remember that there are two steps in Java.
Java source files are compiled into bytecode;
The bytecode is read by a Java interpreter (JVM) and executed.
What you want is essentially asking to execute code in step (1). Now annotations can do things in a compile step (like adding interfaces, implementing methods and so on) but local variable naming is not one of those things.
You could (not necessarily that you should) generate Java source based on your XML, compile the generated code, and finally, execute the compiled code. This could be more efficient if you saved the generated .class files and reused them instead of parsing the XML every time the program is run (it can check the timestamp on the XML and only generate and compile if it's been modified since the last code generation).

Categories

Resources