I am generating JavaScript code using velocity in java.
For example: I generated JavaScript and got below string:
importClass(java.util.ArrayList); function fun(arg) { if (true){ return true;} else{ return true;}}
Is there any java API that takes this String and formats this JavaScript in below manner:
importClass(java.util.ArrayList);
function fun(arg) {
if (true){
return true;
}
else{
return true;
}
}
Closure Compiler
You can use Google's Closure Compiler.
It formats, compresses, optimizes, and looks for mistakes in JavaScript code.
For a quick look what it can do, you can try the web service.
Example
For your example string,
importClass(java.util.ArrayList); function fun(arg) { if (true){ return true;} else{ return true;}}
if you just want to format it, use the compile options "Whitespace only" and "Pretty print", which returns:
importClass(java.util.ArrayList);
function fun(arg) {
if(true) {
return true
}else {
return true
}
}
;
Anyway, with Closure compiler, you have several options to optimize and/or format your input code (either given as string or file URI) and to either return the optimized/formatted JS as string or save it to a file.
I can really recommend to use the "Simple" optimization mode. For longer Javascripts, it really saves you lots of unneeded bytes. Plus, it speeds up script execution!
For your example string, compile options "Simple" (instead of "Whitespace only") and "Pretty print" return
importClass(java.util.ArrayList);
function fun() {
return!0
}
;
As you can see, the result of both fun() functions is the same (Boolean true).
However, the second has removed all useless code (by remaining validity!) and will be executed faster.
Download & Reference
Now, the actual compiler is written in Java and is available as a command-line utility to download (Update 2014-07-10: New Downloadlink).
As a second option, you could implement your own wrapper class to communicate with the REST API (as I did for PHP). Doesn't require too much effort/code.
More info is available here:
Google Code Project Page
Getting Started
FAQ: How do I call Closure Compiler from the Java API?
REST API Reference
Hope that helps.
Related
From java doc 1.8, seems Condition only has await(), await(long, TimeUnit), awaitNanos(), etc.
It doesn't have a function that looks like Condition.await(()->xxxxx) to wait until a condition is met. c++11 condition_variable supports to have cv.wait(mutex, predicate_function) so we can use a lambda function as a parameter to control when condition_variable should return from wait/await.
Does java support this?
From the docs, the C++ condition_variable::wait overload is just checking the predicate when a notification comes through and is equivalent to
while (!stop_waiting()) {
wait(lock);
}
So we can simply do the same thing in Java.
while (!someCondition()) {
conditionVariable.await();
}
i want to send from java some paths to C.
For example i have a folder that have 4 subfoldes... From java i read the length of them from the code below and it returns me 4.
public static int GetLength(){File file = new File("C:\\Registrations");
File[] files = file.listFiles(new FileFilter(){
public boolean accept(File f) {
return f.isDirectory(); }});
return files.length;} }
Now with a thread i start to call the function that connect with C
public Start(){ Thread listeningThread = new Thread(new Runnable(){
public void run(){
new Match(GetDBNumber()); } });
listeningThread.start();}
So far all good. Now from MATCH(int x) class i want to call a C code and every time give the path of the Main folder each time
*PSEUDOCODE* public class Match {
public Match( int len){
System.out.println("subfolders : "+len);
for (i=0; i<len; i++)
{ //Some way call C programm (like an exe)
//with the first,second,third,fourth path
}
.... }
The C code that will recieve the path will be look like that...
int main() {
FILE *fp = fopen(FilePATH, "r");
......
......
return 0; }
I try with ProcessBuilder but i cant send the path every time with this way...
ProcessBuilder p = new ProcessBuilder();
//receive.exe is the exe that Codeblocks create after built the C code
p.command("C:\\Users\\PC\\Documents\\NetBeansProjects\\TEST\\C\\recieve.exe");
try {
p.start();
} catch (Exception e) {System.out.println("Error");
}
As stated by Eric Fitzsimmons,
you will need to use JNI to pass a String value from Java to C.
The C part will need to be in a dll that is available to the Java program.
Wikipedia has a JNI article
Oracle has an in-depth JNI write-up
Edit Concerning JNI.
If you want to send a value between Java and C,
there are only a few ways to do it.
JNI. As stated, Java Native Interface is built for this. This seems to be the best solution.
Use an external Data store. Write something to a data store (maybe a file or a database) on one side and read it on the other side (sides being Java and C).
Write a stand-alone C program that writes to standard out. Launch that program from within Java. Read what was written in java. This is not a great idea.
Depends on a lot of variables. I'll assume that you are building the C code and can change how things are passed, so...
Easiest to hardest:
Pass it in as a command line parameter (only works once per C file execution)
Write/update a text file on your hard drive that the C program can watch
Use TCP/IP and send messages over a pre-designated socket
Build as a shared library or DLL and Use JNI to call the C functions
If you were doing this professionally and this was just the beginning of a larger development effort you'd be wise to look into more professional tooling:
a message bus (Apache has one called ActiveMQ) is designed to do exactly what you are trying to do (and so much more)
a shared cache (Hazlecast can connect Java to C++ and nearly everything else and share data freely)
A shared table in a database that both languages can access.
These are much higher initial investment in time (otherwise free) but they have innumerable features that you could continue to take advantage of as your system grows.
Use jni (Java native interfaces) Make a c++ .dll file and you can easily pass information between both languages.
Good example/explanation for using jni:
https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html
In Java, if Apache Commons Lang jar is in the classpath, we can do one line Validates, like
Validate.isTrue(someBoolean, "This should be true");
In effect the above is the same as:
if (! someBoolean) {
throw new RuntimeException("This should be true");
}
Is there something in the .net world that will do the same?
I know I have seen code somewhere that did something similar but I can't remember where or the systax.
Any help is much appreciated.
You can, of course, write your own:
public static class Validate
{
public static void IsTrue(bool value)
{
if (!value) throw new InvalidOperationException(message)
}
}
Also, in C# or VB you can use code contracts:
Contract.Requires(someBoolean, "This should be true")
This requires downloading the code contracts extension from the Visual Studio extensions site. You can turn on code contracts and have them verified at compile time, and it allows specifying fairly arbitrary contract conditions.
From java code i am able to run the vbscript by using this code
Runtime.getRuntime().exec("wscript C:\\ppt\\test1.vbs ");
But want to know how to call the method of vbscript from java..for example in test1.vbs
Set objPPT = CreateObject("PowerPoint.Application")
objPPT.Visible = True
Set objPresentation = objPPT.Presentations.Open("C:\ppt\Labo.ppt")
Set objSlideShow = objPresentation.SlideShowSettings.Run.View
sub ssn1()
objPPT.Run "C:\ppt\Labo.ppt!.SSN"
End sub
how to call only ssn1() method from java.Otherwise can we run the macro of a power point from java code..kindly help!!
This should make you happy :) Go to the WScript section : http://technet.microsoft.com/library/ee156618.aspx
Here's my idea... in your vbscript file, make your script listen to a command line parameter that would specify which method to call. Then, in Java, you could only have to use this parameter whenever you want to call a specific method in the file.
Otherwise, if you want to access powerpoint in java, you will need to access its API like you did in vbscript, which is possible if vbscript can do it but the approach / syntax may change.
I'm not so much into the visual basic script side, but if you can expose your visual basic script as a COM object, the you can access the methods of it from java by usage of frameworks such as for example com4j:
http://com4j.java.net/
The PowerPoint application object's .Run method lets you call any public subroutine or function in any open presentation or loaded add-in
This post answers the OP's question:
Otherwise can we run the macro of a power point from java code..kindly help!!
(but does not address the original vbscript question)
There's the JACOB library, which stands for Java COM Bridge, you can find here: http://sourceforge.net/projects/jacob-project/?source=directory
With it you can invoke Excel, Word, Outlook, PowerPoint application object model methods.
I've tried this with Excel but not PowerPoint. (This is just some sample code, one might want to make it more object oriented.)
public class Excel {
private static ActiveXComponent xl = null;
public static Init() {
try {
ComThread.InitSTA();
xl = ActiveXComponent.connectToActiveInstance("Excel.Application.14");
// 14 is Office 2010, if you don't know what version you can do "Excel.Application"
if (xl==null) {
// code to launch Excel if not running:
xl = new ActiveXComponent("Excel.Application");
Dispatch.put(xl, "Visible", Constants.kTrue);
}
}
catch (Exception e) {
ComThread.Release();
}
}
public static String Run(String vbName) {
// Variant v = Dispatch.call(xl, "Run", vbName); // using string name lookup
Variant v = Dispatch.call(xl, 0x103, vbName); // using COM offset
// return Dispatch.get(this, "Name").getString();
return v.getString();
}
public static Variant Run1p(String vbName, Object param) {
// Variant v = Dispatch.call(xl, "Run", vbName, param);
return Dispatch.call(xl, 0x103, vbName, param);
// return Dispatch.get(this, "Name").getString();
}
public static Worksheet GetActiveWorksheet () {
// Dispatch d = xl.getProperty("ActiveSheet").toDispatch();
Dispatch d = Dispatch.get(xl, 0x133).toDispatch ();
return d; // you may want to put a wrapper around this...
}
}
Notes:
For Excel, at least, to get Run to invoke a VBA macro/subroutine several things have to be true:
The Excel workbook containing the macro must be "Active" (i.e. must
be the ActiveWorkbook) otherwise Run will not find the VBA subroutine. (However the workbook does not have to be
screen visible!! This means you can call a VBA Macro that is in an add-in!).
You can then pass the name of the macro using the following syntax as a string literal:
VBAProjectName.VBAModuleName.SubroutineName
For COM object invocations, you can use the name lookup version or the id number version. The id numbers come from the published COM interfaces (which you can find in C++ header files, or possibly have JACOB look them up for you).
If you successfully did the connection to Excel, be sure to call ComThread.Release() when you're done. Put it in some appropriately surrounding finally. If the process of your Java code terminates without calling it, the COM reference count on Excel will be wrong, and the Excel process will never terminate, even after you exit the Excel application. Once that happens, needless to say, Excel starts to behave screwy then (when you try to use it next, it runs but will fail to load any plug-ins/add-ons). If that happens (as it can during debugging esp. if you are bypassing finally's for better debugging) you have to use the task manager to kill the Excel process.
Can anybody show an example of how to use heap.heapForEachClass in a select statement?
It would be great if you could provide some links with different examples of queries (other than those in the oqlhelp page of course :) )
I don't believe heap.forEachClass() is meant to be used in a select statement, at least not directly. Consider the fact that it doesn't return anything:
var result=heap.forEachClass(function(it){return it;});
typeof result
//returns undefined
The OQL used in jhat and VisualVM does support plain ol' JavaScript, just like the "query" I use above. I believe that the heap.forEachClass() finds more use in either JavaScript-style queries or in JavaScript functions within select-type queries.
That said, I don't know why this function exists since the heap.classes() enumeration is much easier to use, both with with select-style queries and plain JavaScript ones.
You could even even recreate the same functionality as heap.forEachClass() with the following JavaScript function:
function heapForEachClass(func){
map(heap.classes(),func)
return undefined;
}
Any sample queries that I could provide you would likely be easier written with heap.classes(). For example, you could use heap.forEachClass() to get list of all classes:
var list=[];
heap.forEachClass(function(it){
list.push(it);
});
list
but this is more complicated than how you'd do it with heap.classes():
select heap.classes()
or just
heap.classes()
I've used this function before to look for classes that are loaded multiple times (usually, this happens when two different class loaders load the same lib taking more memory for no reason, and making the JVM serialize and deserialize objects passed from one class instance to the other -because it doesn't know that they are actually the same class-)
This is my OQL script that selects (and count) classes that has the same name:
var classes = {};
var multipleLoadedClasses = {};
heap.forEachClass(function(it) {
if (classes[it.name] != null) {
if (multipleLoadedClasses[it.name] != null) {
multipleLoadedClasses[it.name] = multipleLoadedClasses[it.name] + 1;
} else {
multipleLoadedClasses[it.name] = 1;
}
} else {
classes[it.name] = it;
}
});
multipleLoadedClasses;
hopes that this will help further visitors ;)