Cannot see print and println statements in Eclipse using JEP/Pydev - java

I'm learning JEP and PyDev plugin eclipse and new to Python.
I cannot see my python print and java println statements on Eclipse console tab.
As I'm just trying things out I create a simple python script by creating a new PyDev module and it just has one line (greetings.py):
print("Hello from python");
When I run this I see it in the console when I run it both the PyDev and Jave EE perspective.
Next as the intent of this exercise is to look into JEP to see if it's adequate for my project so I created another Java project with this code:
package my.sand.box;
import jep.Interpreter;
import jep.Jep;
import jep.JepException;
import jep.SharedInterpreter;
public class JepTest {
public static void main(String[] args) throws JepException {
// TODO Auto-generated method stub
System.out.println("hey");
try (Interpreter interp = new SharedInterpreter()) {
//interp.exec("import example_package");
// any of the following work, these are just pseudo-examples
interp.runScript("full/path/to/greetings.py");
interp.eval("import sys");
interp.eval("s = 'Hello World'");
interp.eval("print s");
String java_string = interp.getValue("s").toString();
System.out.println("Java String:" + java_string);
}
}
}
I don't see anyting on the console. Not even the java println statements.
I also recreated both projects in a new workspace and could see the output. What's different between both workspaces is that in the one that's not workign I have other java projects and pydev projects open.
Would appreciate any advice.

I've faced a similar issue working with Jep before, the trick is you need to redirect Python's output stream in your IDE by calling the correct method.
Take a look at https://github.com/ninia/jep/issues/298

As Klodovsky mentioned, you need to redirect Python's output to the stream used by the IDE. I've adapted your example to do this. The key line is the call to SharedInterpreter.setConfig:
package my.sand.box;
import jep.Interpreter;
import jep.JepConfig;
import jep.JepException;
import jep.SharedInterpreter;
public class JepTest {
public static void main(String[] args) throws JepException {
System.out.println("hey");
// Eclipse doesn't use stdout & stderr, so use the streams from Java.
SharedInterpreter.setConfig(new JepConfig()
.redirectStdErr(System.err)
.redirectStdout(System.out));
try (Interpreter interp = new SharedInterpreter()) {
// interp.exec("import example_package");
// any of the following work, these are just pseudo-examples
// Uncomment if you've created a greetings.py script.
// interp.runScript("full/path/to/greetings.py");
interp.eval("import sys");
interp.eval("s = 'Hello World'");
interp.eval("print(s)");
String java_string = interp.getValue("s").toString();
System.out.println("Java String:" + java_string);
}
}
}

Related

Issue with Py4j tutorial

Please note I do not have any previous experience with Java. I am having issues with the following tutorial for Py4j: https://www.py4j.org/getting_started.html
I installed Py4j in an Anaconda environment. I am working in Ubuntu. I set my classpath to include the .jar file for Py4j. When I try to compile the sample code on the above web-page I received an error saying the Stack symbol didn't exist. I tried to add a line of code to import it, but that did not help either (see images).
Error and Directory Structure (image)
Source code:
Stack.java
package py4j.examples;
import java.util.LinkedList;
import java.util.List;
public class Stack {
private List<String> internalList = new LinkedList<String>();
public void push(String element) {
internalList.add(0, element);
}
public String pop() {
return internalList.remove(0);
}
public List<String> getInternalList() {
return internalList;
}
public void pushAll(List<String> elements) {
for (String element : elements) {
this.push(element);
}
}
}
StackEntryPoint.java
package py4j.examples;
import py4j.GatewayServer;
import py4j.examples.Stack; // <-- I added this line but it does not solve the issue
public class StackEntryPoint {
private Stack stack;
public StackEntryPoint() {
stack = new Stack();
stack.push("Initial Item");
}
public Stack getStack() {
return stack;
}
public static void main(String[] args) {
GatewayServer gatewayServer = new GatewayServer(new StackEntryPoint());
gatewayServer.start();
System.out.println("Gateway Server Started");
}
}
I haven't used Java before, so I'm confused about how to link classes during compilation. I've tried looking extensively at Java documentation/resources online and questions related, but can't seem to solve this problem. Could someone point out what I'm doing incorrectly?
Thank you.
You are compiling class StackEntryPoint, but you have not compiled the Stack class yet. Do so first, otherwise it cannot use it to compile StackEntryPoint.
Normally your IDE would solve this for you, but you've got a special setup going here (with the Python integration) so I'm not sure how you'd integrate it.
Ideally, you'll build your Java library as a separate JAR using conventional Java tooling (e.g. Maven and IntelliJ IDEA), but it's not a bad exercise to learn to do it bare-bones first.

ProcessBuilder call another java file same package

I am learning how to use ProcessBuilder, I created a package called socketspractice, inside I have 2 classes, I am trying to create a new process where 'Program.java' calls 'test1.java' so it prints 'test1'.
When I use command prompt: "java socketspractice.test1" 'test1' prints, but using Netbeans it doesn't.
The question is, how can I set the path so it works the same way or what else am I missing? I am using Netbeans for this.
Program.java
package socketspractice;
import java.io.File;
import java.io.IOException;
import java.lang.ProcessBuilder;
public class Program {
public static void main(String[] args) throws IOException, InterruptedException {
ProcessBuilder builderExecute = new ProcessBuilder("java", "socketspractice.test1");
builderExecute.start();
}
}
AND
test1.java
package socketspractice;
public class test1 {
public static void main(String[] args) {
// TODO code application logic here
System.out.println("test1");
}
}
The main issue with ur approach is that when you are starting ProcessBuilder it doesnt know where ur project lies on your machine, because its running as a seperate JVM process.
So please create you project as a maven project and then try to put the compiled jar in classpath and then start the process builder.
ProcessBuilder pb = new ProcessBuilder("java","-classpath",
"<complete location of your jar containing test1>", "socketspractice.test1")

Post data from Matlab to Pachube (Cosm) using Java Methods

I am using JPachube.jar and Matlab in order to send data to my datastream. This java code works on my machine:
package smartclassroom;
import Pachube.Data;
import Pachube.Feed;
//import Pachube.FeedFactory;
import Pachube.Pachube;
import Pachube.PachubeException;
public class SendFeed {
public static void main(String arsg[]) throws InterruptedException{
SendFeed s = new SendFeed(0.0);
s.setZainteresovanost(0.3);
double output = s.getZainteresovanost();
System.out.println("zainteresovanost " + output);
try {
Pachube p = new Pachube("MYAPIKEY");
Feed f = p.getFeed(MYFEED);
f.updateDatastream(0, output);
} catch (PachubeException e) {
System.out.println(e.errorMessage);
}
}
private double zainteresovanost;
public SendFeed(double vrednost) {
zainteresovanost = vrednost;
}
public void setZainteresovanost(double vrednost) {
zainteresovanost = vrednost;
}
public double getZainteresovanost() {
return zainteresovanost;
}
}
but I need to do this from Matlab. I have tried rewriting example (example from link is working on my machine): I have compile java class with javac and added JPachube.jar and SendFeed.class into path and then utilize this code in Matlab:
javaaddpath('C:\work')
javaMethod('main','SendFeed','');
pachubeValue = SendFeed(0.42);
I get an error:
??? Error using ==> javaMethod
No class SendFeed can be located on Java class path
Error in ==> post_to_pachube2 at 6
javaMethod('main','SendFeed','');
This is strange because, as I said example from the link is working.
Afterwards, I decided to include JPachube directly in Matlab code and to write equivalent code in Matlab:
javaaddpath('c:\work\JPachube.jar')
import Pachube.Data.*
import Pachube.Feed.*
import Pachube.Pachube.*
import Pachube.PachubeException.*
pachube = Pachube.Pachube('MYAPIKEY');
feed = pachube.getFeed(MYFEED);
feed.updateDatastream(0, 0.54);
And I get this error:
??? No method 'updateDatastream' with matching signature found for class 'Pachube.Feed'.
Error in ==> post_to_pachube2 at 12
feed.updateDatastream(0, 0.54);
So I have tried almost everything and nothing! Any method making this work will be fine for me. Thanks for help in advance!
This done trick for me (answer from here)
javaaddpath('c:\work\httpcore-4.2.2.jar');
javaaddpath('c:\work\httpclient-4.2.3.jar');
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
httpclient = DefaultHttpClient();
httppost = HttpPost('http://api.cosm.com/v2/feeds/FEEDID/datastreams/0.csv?_method=put');
httppost.addHeader('Content-Type','text/plain');
httppost.addHeader('X-ApiKey','APIKEY');
params = StringEntity('0.7');
httppost.setEntity(params);
response = httpclient.execute(httppost);
I would rather use built-in methods. Matlab hasurlread/urlwrite, which could work if all you wish to do is request some CSV data from Cosm API. If you do need to use JSON, it can be handled in Matlab via a plugin.
Passissing the Cosm API key, that can be done via key parameter like so:
cosm_feed_url = "https://api.cosm.com/v2/feeds/61916.csv?key=<API_KEY>"
cosm_feed_csv = urlread(cosm_feed_url)
However, the standard library methods urlread/urlwrite are rather limited. In fact, the urlwrite function is only designed for file input, and I cannot even see any official example of how one could use a formatted string instead. Creating a temporary file would reasonable, unless it's only a few lines of CSV.
You will probably need to use urlread2 for anything more serious.
UPDATE: it appears that urlread2 can be problematic.

Java Swing - How to double click a project file on Mac to open my application and load the file?

I have created a Mac Java Swing application, and i have set a file extension(*.pkkt) for it in the "Info.plist" file, so when double clicking that file it opens my application.
When i do that the program runs fine. Now i need to load the (*.pkkt) project in the program, but the file path is not passed as an argument to the main(...) method in Mac as happens in Windows Operating System.
After some search i found an Apple handling jar "MRJToolkitStubs" that has the MRJOpenDocumentHandler interface to handle such clicked files. I have tried using it to load that file by implementing that Interface in the main program class, but it is not working. The implemented method is never called at the program start-up.
How does this Interface run ?
------------------------------------------------- Edit: Add a Code Sample
Here is the code i am using :
public static void main( final String[] args ) {
.
.
.
MacOpenHandler macOpenHandler = new MacOpenHandler();
String projectFilePath = macOpenHandler.getProjectFilePath(); // Always Empty !!
}
class MacOpenHandler implements MRJOpenDocumentHandler {
private String projectFilePath = "";
public MacOpenHandler () {
com.apple.mrj.MRJApplicationUtils.registerOpenDocumentHandler(this) ;
}
#Override
public void handleOpenFile( File projectFile ) {
try {
if( projectFile != null ) {
projectFilePath = projectFile.getCanonicalPath();
System.out.println( projectFilePath ); // Prints the path fine.
}
} catch (IOException e) {}
}
public String getProjectFilePath() {
return projectFilePath;
}
}
As mentioned in the comment above "getProjectFilePath()" is always Empty !
On Java 9, use Desktop.setOpenFileHandler()
The proprietary com.apple.eawt packages have been removed from recent versions of Java and has been incorporated into various methods in the Desktop class. For your specific example:
import java.awt.desktop.OpenFilesHandler;
import java.awt.desktop.OpenFilesEvent;
import java.io.File;
import java.util.List;
public class MyOpenFileHandler implements OpenFilesHandler {
#Override
public void openFiles​(OpenFilesEvent e) {
for (File file: e.getFiles​()) {
// Do whatever
}
}
}
Then elsewhere, add this:
Desktop.getDesktop().setOpenFileHandler(new MyOpenFileHandler());
The OpenFilesEvent class also has a getSearchTerm() method. Say that a person used Spotlight on macOS to search for the word "StackOverflow", then decided to open up a document. With this method, can you determine that "StackOverflow" was the word they searched for, and choose to do something with that (perhaps highlight the first occurrence of the word).
You're going to want to use the Apple Java Extensions.
They should be included in any JDK that runs on Mac OS X, but the documentation is kind of hard to get. See this answer for more details.
Specifically, you'll want to make an OpenFilesHandeler.
This code snippet should work:
import com.apple.eawt.event.OpenFilesHandeler;
import com.apple.eawt.event.AppEvent;
import java.io.File;
import java.util.List;
class MacOpenHandler implements OpenFilesHandeler {
#Override
public void openFiles(AppEvent.OpenFilesEvent e) {
List<File> files = e.getFiles();
// do something
}
}
And somewhere:
import com.apple.eawt.Application;
...
MacOpenHandeler myOpenHandeler = new MacOpenHandeler();
Application.getApplication().setOpenFileHandler(myOpenHandeler);

Executing script inside method with BeanShell

I'm not really sure how I can explain this, but here goes:
I want to be able to "insert" some commands into parts of my code which will be loaded from external files. To parse and execute these commands, I presumably have to use some scripting like BeanShell's eval method. The problem is that it doesn't seem to recognize the instance/method it's inside of. As a very basic example, I want to do something like
public void somethingHappens()
{
Foo foo = new Foo();
Interpreter i = new Interpreter();
i.eval("print(foo.getName());");
}
Is this possible? Should I use other scripting tools?
If you're using 1.6, you can use the built in JavaScript support.
The Java Scripting Programmer's Guide explains how to import Java classes into your script.
Code example 9 in this article explains how to pass objects into the script's scope.
Using beanshell, this is something you can try
package beanshell;
import bsh.EvalError;
import bsh.Interpreter;
public class DemoExample {
public static void main( String [] args ) throws EvalError {
Interpreter i = new bsh.Interpreter();
String usrIp = "if(\"abc\".equals(\"abc\")){"
+ "demoExmp.printValue(\"Rohit\");"
+ "}";
i.eval(""
+ "import beanshell.DemoExample;"
+ "DemoExample demoExmp = new beanshell.DemoExample();"
+ ""+usrIp);
}
public static void printValue(String strVal){
System.out.println("Printing Value "+strVal);
}
}

Categories