Get .js file value using Java - java

I have one config.js file:
sOptions = {
enabled: true,
vtest: assign,
stest: remove
}
I want to get value of 'vtest' using Java. I tried below code
ScriptEngine ee = new ScriptEngineManager().getEngineByName("nashorn");
ee.eval(new FileReader("config.js"));
System.out.println("ee: "+ee);
I am not seeing anything is write in log file.

First thing you need valid javascript. When I ran your original js I got exception messsages.
In the fix below I quoted both of your 'assign' and 'remove' values. Also, you need to print out the value that you want.
import javax.script.*;
public class NashornTest{
public static void main(String[] args) throws Exception{
String js = "sOptions = {\n" +
" enabled: true,\n" +
" vtest: 'assign',\n" +
" stest: 'remove'\n" +
"}";
ScriptEngine ee = new ScriptEngineManager().getEngineByName("nashorn");
ee.eval(js);
System.out.println("ee:" + ee);
System.out.println("sOptions: "+ee.get("sOptions"));
}
}
Which shows.
ee:jdk.nashorn.api.scripting.NashornScriptEngine#b3ca52e
sOptions: [object Object]
The next step is to get what you want from the data. Also, if you're just using JSON, you might want to use a JSON library instead of javascript.

Related

Zendesk Java client API updating CustomFieldValue

I am having trouble figuring out how to correctly update a custom field using Zendesk Java client API, and I the problem is I am unsure of the syntax of the command.
I'm able to update comments using the zendesk.createComment(), tags, and other fields but just cannot figure out the syntax for custom fields.
Example:
public static void main(String[] args) {
Zendesk zd = new Zendesk.Builder(url)
.setUsername(uid)
.setPassword(pwd)
.build();
}
private static void setComment(Zendesk zd, long inTicket, String inComment) {
Comment cmt = new Comment();
cmt.setBody(inComment);
cmt.setPublic(pubPriv);
zd.createComment(inTicket, cmt);
}
The custom field update can be accomplished using the following example:
/*
When a customer ftps a file to TCS we need to update the ZenDesk ticket
with the file information. The file name is stored in the AddAttachment List
custom field. This is a destructive field so it must be read first and the
new data concatenated after a line feed then re-written.
1) Read current field data
2) Concatenate line feed and new data onto old data
3) Write new field data
*/
long fieldNum = 25326406;
showDebug("In addAttachmentList");
Ticket ticket = zd.getTicket(inTicket);
List<CustomFieldValue> cfvl = ticket.getCustomFields();
for (int i = 0; i < cfvl.size(); i++) {
if (cfvl.get(i).getId() == fieldNum) {
showDebug("Original value: " + cfvl.get(i).getValue());
cfvl.get(i).setValue(cfvl.get(i).getValue() + "\n" + inComment);
cfvl.get(i).setId(fieldNum);
ticket.setCustomFields(cfvl);
showDebug("After Update value: " + cfvl.get(i).getValue());
zd.updateTicket(ticket);
}
}

How to get the API Endpoint of a SoapUI TestStep using Java

I would like to know how to get the API end point of a TestStep in SoapUI Xml using Java.
I have used the following,
for (int i=0; i<numberOfTestSteps; i++) {
WsdlTestStep testStep = testCase.getTestStepAt(i);
WsdlTestCaseRunner runner = new WsdlTestCaseRunner(testCase, new StringToObjectMap());
runner.runTestStep(testStep);
List<TestStepResult> resultList = runner.getResults();
for (TestStepResult result : resultList) {
String endPoint = ((MessageExchange)result).getEndpoint();
System.out.println("End Point = " + endPoint);
}
}
It only gives "www.test.com:8080". But I need the API end point as in the image.
Please someone help me to solve this.
Below should give you what you are looking for:
String resourcePath = ((MessageExchange)result).getResource().getFullPath();
System.out.println("Resource Path = " + resourcePath);
You may look at respective SoapUI's API
There is very simply way too if you wish to show that value from with SoapUI Project itself.
In the test case, there might be a REST Request Test step type. Add a Script Assertion as shown below:
log.info messageExchange.endpoint

Gwt update TextArea from Server

I have created a Textarea in my app. And I have one method in my server i.e, in
GreetingServiceImpl class
The sample code of my method in GreetingServiceImpl class is:
public String greetServer(String input) throws IllegalArgumentException {
System.out.println("input===>>" + input);
String serverInfo = getServletContext().getServerInfo();
System.out.println("serverinfo===>>" + serverInfo);
String userAgent = getThreadLocalRequest().getHeader("User-Agent");
System.out.println("User agent===" + userAgent);
input = escapeHtml(input);
System.out.println("2....input===>>" + input);
userAgent = escapeHtml(userAgent);
return "Hello, " + input + "!<br><br>I am running " + serverInfo
+ ".<br><br>It looks like you are using:<br>" + userAgent;
}
Now in my client I will call this method, after calling this method I want to setText to my textarea. The text should come from the server.
i.e, I have 4 sysout statements in this method.
System.out.println("input===>>" + input);
System.out.println("serverinfo===>>" + serverInfo);
System.out.println("User agent===" + userAgent);
System.out.println("2....input===>>" + input);
When these statements prints into eclipse console , at the same time I want to print this in order(one by one according to their execution)in my UI i.e, into my textarea. I have no Idea how to achieve this. Please tel me is this possible to do, if so how I can achieve?
PS: I'm looking for a logger type functionality which can update my textarea when ever any server side mathods executed.
It's possible to push data from server to client using Atmosphere which supports WebSockets and GWT.
Why don't you use RPC calls? It is straightforward and easy.
You just create an Example.java and ExampleAsync class at client, and the implementation at server. You can then call the implementation with an AsyncCallback.
For example:
callback = new AsyncCallback() {
public void onSuccess(Void result) {
// Make what ever you want! For example, set the textarea
}
On the other hand, if you want server to notify and update client, you can use Server-Push
You can also use gwt-comet , which also streams messages over http.

Eclipse AST variable binding on standalone java application

I'm trying to use Eclipse ASTParser in order to analyse and, if possible, add some code to some classes. One of the information I need requires to have bindings, but because this is a standalone project (the final goal it's a command line tool, independent from eclipse) I can't have them (requireBinding() returns null).
After reading a lot of posts, the far that I can go is using this examples in order to use FileASTRequestor but that's not the way to go since it seems to me that we have to give the KEY to bind before generating the AST tree.
I've found somewhere that we can use ASTParser.setEnvironment method in order to use the bindings in a standalone java application, but I don't think I'm doing it correctly. What's wrong with the code below?
private static final String rootDir = "D:\\workspace\\stateless\\";
private static final String[] classpath = java.lang.System.getProperty( "java.class.path" ).split(";");
private static final String source =
"package de.siemens.tools.stateless.test.examples; " +
"public class ClassWithFinalMemberVariables {" +
"private final int _memberIntVariable = 0;" +
"public void method() {" +
"int localVariable = 0;" +
"System.out.println(_memberIntVariable + localVariable);" +
"}" +
"}";
public static void main(String[] args) throws CoreException {
Document document = new Document(source);
ASTParser parser = ASTParser.newParser(AST.JLS4);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setEnvironment(classpath, new String[] { rootDir },
new String[] { "UTF8" }, true);
parser.setSource(document.get().toCharArray());
parser.setResolveBindings(true);
parser.setBindingsRecovery(true);
CompilationUnit unit = (CompilationUnit)parser.createAST(null);
unit.recordModifications();
unit.accept(new ASTVisitor() {
#Override
public void endVisit(VariableDeclarationFragment node) {
IVariableBinding bind = node.resolveBinding();
if(bind == null)
System.out.println("ERROR: bind is null");
super.endVisit(node);
}
Output is always "ERROR: bind is null".
I've already solved it, the code is here:
http://pasteit.com/19433
Even though I prefer the ASTVisitor model, this one gives me every binding available.
And here is the discussion about the problem, for those of you who are curious: https://bugs.eclipse.org/bugs/show_bug.cgi?id=206391
EDIT: I don't have any idea if this is the best solution or not, if you have any suggestion please let me know

Trouble accessing Java classes from Firefox extension's Javascript

I'm going to develop a Firefox extension which uses some Java classes.
The extension gets the value of <input type="file"> fields, using Javascript.
The Java class I'm going to create is the following:
public class Firefox {
public static String inFileName;
public static void main(String[] args) throws IOException {
inFileName = "";
try {
inFileName = args[0];
} catch (Exception ex) {}
}
On Javascript, I have to use Java reflection in order to access Java classes.
In this manner I can create my Java object:
var fileInput = e.explicitOriginalTarget; // is an object HTMLInputElement, I get this when a file is selected
strArray = java.lang.reflect.Array.newInstance(java.lang.Class.forName("java.net.URL"),3);
classLoader = java.net.URLClassLoader.newInstance(strArray);
parameters = java.lang.reflect.Array.newInstance(java.lang.Class.forName("java.lang.String"),1);
parameters[0]= fileInput.value;
var aClass = java.lang.Class.forName("Firefox", true, classLoader);
var aStaticMethod = aClass.getMethod("main", [parameters.getClass()]); //gets the main(String[] args) method, here I get the exception*
var myJava = aStaticMethod.invoke(null, [parameters]); //invokes the main method
I've been trying this extension on Firefox-3.5b4 and everything goes fine, but when I try it on Firefox-3.0.10 I get the following exception*:
`InternalError: Unable to convert JavaScript value class [Ljava.lang.String; to Java value of type java.lang.Class[]`
For example, putting the following line before the main method invokation:
alert(parameters + " - " + parameters[0]);
on both Firefox-3.0.10 and 3.5b4 I get an alert window which says:
`[Ljava.lang.String;#194ca6c - /root/demo.pdf` //demo.pdf is the selected file
But only on 3.0.10 I get the exception, ONLY on my GNU/Linux machine. On Windows XP instead I have no problems on both Firefox versions!
Note that on both Windows and Linux the Java plugin version is 6 update 13.
Where am I wrong? Is it a possible bug on Firefox-3.0.10 Javascript engine or must I do any other thing before getting the main(...) method?
assuming your complete class name is "your.package.Firefox" you could do:
importPackage("your.package");
args = java.lang.reflect.Array.newInstance(java.lang.String.TYPE, 1);
Firefox.main(args)
you are incorrectly invoiking the method using;
[parameters.getClass()]
which is passing an argument of type java.lang.Class[] into the signature that is expecting a String object. simply pass the parameters object in as it is.

Categories