Rserve with java. Eval fail error 127 - java

I got this error and i dont know what to do and couldnt find any other solution on this site. I run Rserve in the background on my computer and i connect to the local host. But i cant get the frame to popup.
Here is my code:
package rservedemo;
/**
*
* #author Carl
*/
import java.awt.*;
import java.awt.event.*;
import org.rosuda.REngine.*;
import org.rosuda.REngine.Rserve.*;
public class PlotDemo extends Canvas {
public static void main(String[] args) {
try
{
String device = "jpeg";
RConnection c = new RConnection ((args.length>0)?args[0]:"127.0.0.1");
if
(c.parseAndEval("supressWarnings(require('Cairo',quietly=TRUE))").asInteger()>0) device="CarioJPEG";
else
System.out.println("(Consider installing Cairo package for better bitmap output)");
REXP xp = c.parseAndEval("Try("+device+"('test.jpg,quality=90))");
if (xp.inherits("Try error"))
{
System.err.println("Can't open "+device+" graphics device:\n" +xp.asString());
REXP w = c.eval("If (exists('last.warning') && length(last.warning)>0)names(last.warning) [1] else 0");
if (w.isString()) System.err.println(w.asString());
return;
}
c.parseAndEval("data(iris); plot(iris$Sepal.Length, iris$Petal.Length); dev.off()");
xp = c.parseAndEval("r=readBin('test.jpg','raw',1024*1024); unlink('test.jpg');r");
Image img = Toolkit.getDefaultToolkit().createImage(xp.asBytes());
Frame f = new Frame("Test image");
f.add(new PlotDemo (img));
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){System.exit(0);}
});
f.pack();
f.setVisible(true);
c.close();
}
catch (RserveException rse)
{
System.out.println(rse);
}
catch (REXPMismatchException mme)
{
System.out.println(mme);
mme.printStackTrace();
}
catch (Exception e)
{
System.out.println("Seomthing went wrong, but it's not Rserve: " +e.getMessage());
e.printStackTrace();
}
}
Image img;
public PlotDemo(Image img)
{
this.img=img;
MediaTracker mediaTracker = new MediaTracker(this);
mediaTracker.addImage(img, 0);
try
{
mediaTracker.waitForID(0);
}
catch (InterruptedException ie)
{
System.err.println(ie);
System.exit(1);
}
setSize(img.getWidth(null), img.getHeight(null));
}
public void paint (Graphics g)
{
g.drawImage(img, 0, 0, null);
}
}
And here is the error, i have tried to change the line at 27 but couldnt do anything useful. When i run the
c.parseAndEval("data(iris); plot(iris$Sepal.Length, iris$Petal.Length); dev.off()");
in r and there it works. So that dosent seem to be the problem.
Seomthing went wrong, but it's not Rserve: eval failed, request status: error code: 127
org.rosuda.REngine.REngineException: eval failed, request status: error code: 127
at org.rosuda.REngine.Rserve.RConnection.parseAndEval(RConnection.java:454)
at org.rosuda.REngine.REngine.parseAndEval(REngine.java:108)
at rservedemo.PlotDemo.main(PlotDemo.java:27)
Thankful for help

Usually process exit code 127 means File not found.
In you case problematic can be line:
REXP xp = c.parseAndEval("Try("+device+"('test.jpg,quality=90))");
because you could have mistake (typo) in line:
(c.parseAndEval("supressWarnings(require('Cairo',quietly=TRUE))").asInteger()>0) device="CarioJPEG";
Note: CarioJPEG instead of CairoJPEG

Related

Is there a way to load (with new File()) image that had been imported into the Project Folder?

I can't load image into BufferedImage Object with new File() without full path of the image.
When i'm trying to load an image.png into BufferedImage Object with new File() I face to results:
Success - when I write the whole path (C://Users//benja//Desktop/...) it works fine
Fail - when i write the path of the image that i have imported into my project. Is there a way to make it work even if i'm using new File(...)?
public class PicturePanel extends JPanel {
BufferedImage image=null;
public PicturePanel() {
try {
image = ImageIO.read(new
/*Works fine with full path: */
File("C://Users//benjamin//Desktop//Pictures//whiteFish.png"));
/*fail - throw an exception: */
//image = ImageIO.read(new
File("//RandomThingsInGui/whiteFish.png"));
} catch (IOException e) { e.printStackTrace(); }
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0,0,500,250,null);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.add(new PicturePanel());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setSize(600,400);
f.setVisible(true);
}
What i need is to know if there is a way (and how) to load the image from an imported path (I mean from inside eclipse) or when I use new File(...) I must use full path.
thanks for helpers :)
Copy the 'whiteFish.png' file to the 'RandomThingsInGui' directory.
Can you try this?
try {
// AS-IS
//image = ImageIO.read(new File("//RandomThingsInGui/whiteFish.png"));
// TO-BE (replace '//' to '/')
image = ImageIO.read(new File("/RandomThingsInGui/whiteFish.png"));
} catch (IOException e) {
e.printStackTrace();
}

Graphics2D drawImage won't send correctly to printer

My issue is, i'm trying to print using Java and it seems to give a random result each time(Look at the pictures and you will understand). The first time I run it the Image prints fine, but the second time there is a black box covering half of the screen. Here is the First Run
and the Second run
Here is the code:
package test;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.ImageObserver;
import javax.swing.*;
import java.awt.print.*;
import java.net.URL;
public class HelloWorldPrinter implements Printable, ActionListener {
private Image ix = null;
public int print(Graphics g, PageFormat pf, int page) throws PrinterException {
if (page > 0) { /* We have only one page, and 'page' is zero-based */
return NO_SUCH_PAGE;
}
/*
* User (0,0) is typically outside the imageable area, so we must
* translate by the X and Y values in the PageFormat to avoid clipping
*/
Graphics2D g2d = (Graphics2D) g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
ix = getImage("Capture.JPG");
g.drawImage(ix, 1, 1, null);
return PAGE_EXISTS;
}
public void actionPerformed(ActionEvent e) {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
boolean ok = job.printDialog();
if (ok) {
try {
job.print();
} catch (PrinterException ex) {
/* The job did not successfully complete */
}
}
}
public static void main(String args[]) {
UIManager.put("swing.boldMetal", Boolean.FALSE);
JFrame f = new JFrame("Hello World Printer");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JButton printButton = new JButton("Print Hello World");
printButton.addActionListener(new HelloWorldPrinter());
f.add("Center", printButton);
f.pack();
f.setVisible(true);
}
public Image getImage(String path) {
Image tempImage = null;
try {
URL imageURL = HelloWorldPrinter.class.getResource(path);
imageURL = HelloWorldPrinter.class.getResource(path);
tempImage = Toolkit.getDefaultToolkit().getImage(imageURL);
} catch (Exception e) {
System.out.println(e);
}
return tempImage;
}
}
Thanks for taking the time to read this and I hope you have a solution.
EDIT: I'm using Microsoft Print To PDF so I can view the print. I don't know if it's relevant but I would add it anyways.
MadProgrammer's solution worked.
Don't use Toolkit#getImage, this could using a thread to load the image an or caching the results in unexpected ways, consider using ImageIO.read instead, it will block until the image is fully realised. It's also possible that your getImage method is triggering an exception and is returning a blank image, but since you ignore the exception result, it's hard to know – MadProgrammer

Bad operand types - Java

Project: HERE link to the project
I am trying to use this open source code but I get the following error:
error: bad operand type for binary operator '!='
In this context:
if (img != null) {
cvFlip(img, img, 1);// l-r = 90_degrees_steps_anti_clockwise
cvSaveImage((i++) + "-capture.jpg", img);
// show image on window
canvas.showImage(img);
}
Here is the entire class:
package pdlwebcam;
import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.FrameGrabber;
import com.googlecode.javacv.VideoInputFrameGrabber;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
public class PDLWebcam implements Runnable {
//final int INTERVAL=1000;///you may use interval
IplImage image;
CanvasFrame canvas = new CanvasFrame("Web Cam");
public PDLWebcam() {
canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
}
#Override
public void run() {
FrameGrabber grabber = new VideoInputFrameGrabber(0);
int i = 0;
try {
grabber.start();
IplImage img;
while (true) {
img = grabber.grab();
if (img != null) {
cvFlip(img, img, 1);// l-r = 90_degrees_steps_anti_clockwise
cvSaveImage((i++) + "-capture.jpg", img);
// show image on window
canvas.showImage(img);
}
//Thread.sleep(INTERVAL);
}
} catch (Exception e) {
}
}
}
I've created stub implementations for cvFlip and cvSaveImage methods and project compiled without any errors. Netbeans displays Bad operand error message anyway, though. It looks like a bug in IDE itself.
Workaround: I've noticed that IplImage class derives from com.googlecode.javacpp.Pointer which is not visible to Netbeans. Adding javacpp to project libraries helped to remove the error message.

System tray displayMessage() not showing

So what I want is when my program runs (It's a system tray) one of those small notification problems show up at the bottom right of the screen. I tried.
trayIcon = new TrayIcon(image, "Title", popup);
trayIcon.setImageAutoSize(true);
trayIcon.displayMessage("Title", "MESSAGE HERE", TrayIcon.MessageType.ERROR) //THIS IS THE LINE THAT SHOULD SHOW THE MESSAGE
Where should it be for it to run when the program runs and is that the correct method with the correct parameters?
Have you had a read on How to Use the System Tray?
However
Check this minimal example:
After tray.add(trayIcon); than show your message.
import java.awt.AWTException;
import java.awt.Graphics2D;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.SwingUtilities;
public class Test {
public Test() throws Exception {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new Test();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
private void initComponents() throws Exception {
createAndShowTray();
}
private void createAndShowTray() throws Exception {
//Check the SystemTray is supported
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
return;
}
//retieve icon form url and scale it to 32 x 32
final TrayIcon trayIcon = new TrayIcon(resizeImage(ImageIO.read(
new URL("http://www.optical-illusions.in/illusions/blue_rotation_optical_illusion.jpg")), BufferedImage.TYPE_INT_ARGB, 32, 32));
//get the system tray
final SystemTray tray = SystemTray.getSystemTray();
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added.");
}
trayIcon.displayMessage("Title", "MESSAGE HERE", TrayIcon.MessageType.ERROR); //THIS IS THE LINE THAT SHOULD SHOW THE MESSAGE
}
private static BufferedImage resizeImage(BufferedImage originalImage, int type, int IMG_WIDTH, int IMG_HEIGHT) {
BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
g.dispose();
return resizedImage;
}
}
Go to the little action center and click "manage notificaitons"
then scroll down in the settings until you get to the
It didn't work when I had it in a loop so I just tried putting an additional statement outside the loop and then it worked. Yay!

JOptionPane.showMessageDialog() shows but without any message?

In the following code, I call JOptionPane.showMessageDialog, inside a try/catch block. But when the error is caught, my JOptionPane is visible but without any message !!! Does someone knows why and how I can correct the problem ?
Regards
MyBoardJPannel.java
package experimentations.gui;
import java.awt.Graphics;
import java.awt.Image;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class MyBoardPannel extends JPanel {
#Override
public void paint(Graphics grahics) {
if (imageToShow == null)
imageToShow = loadImage("sampleImage");
}
/**
* In fact, there are not any image in project => will go to catch clause.
* #param imageName
*/
private void loadImage(String imageName) {
InputStream imageStream = getClass().getResourceAsStream("/"+imageName+".png");
try {
imageToShow = ImageIO.read(imageStream);
}
catch (Exception e) {
String errorMessage = "Failed to load image "+imageName;
System.err.println(errorMessage);
JOptionPane.showMessageDialog(this, errorMessage,
"Image loading error", JOptionPane.ERROR_MESSAGE);
imageToShow = null;
System.exit(1);
}
}
private Image imageToShow;
}
JOptionPaneErrorShowing.java
package experimentations.gui;
import javax.swing.JFrame;
public class JOptionPaneErrorShowing extends JFrame {
public JOptionPaneErrorShowing(){
setTitle("JOptionPane experimentation");
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
add(new MyBoardPannel());
}
/**
* #param args
*/
public static void main(String[] args) {
new JOptionPaneErrorShowing().setVisible(true);
}
}
It's likely a Swing concurrency issue. But more importantly, you should never load an image from within a paint or paintComponent method, ever. Read it in the constructor or elsewhere but paint/paintComponent need to be lean and blazingly fast.
To solve your issue, consider reading in the image in SwingWorker object. If you call a JOptionPane from within the SwingWorker's doInBackground method though, be sure to call it on the Swing event thread, the EDT, using SwingUtilities.invokeLater(Runnable).
Also, you will hardly ever want to draw in a JPanel's paint method unless you are taking care of painting borders and children. Instead paint in a paintComponent method, and don't forget to call the super.paintComponent(g) method in that paintComponent override. You'll want to read the Swing graphics tutorials as this is all spelled out there.
For example:
import java.awt.Graphics;
import java.awt.Image;
import java.io.InputStream;
import java.util.concurrent.ExecutionException;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class MyBoardPannel extends JPanel {
protected static final String SAMPLE_IMAGE = "sampleImage";
Image imageToShow = null;
public MyBoardPannel() {
SwingWorker<Image, Void> mySW = new SwingWorker<Image, Void>() {
#Override
protected Image doInBackground() throws Exception {
return loadImage(SAMPLE_IMAGE);
}
#Override
protected void done() {
try {
imageToShow = get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
};
mySW.execute();
}
#Override
public void paintComponent(Graphics grahics) {
super.paintComponent(grahics);
if (imageToShow != null) {
grahics.drawImage(imageToShow, 0, 0, null);
}
}
private Image loadImage(String imageName) {
InputStream imageStream = getClass().getResourceAsStream(
"/" + imageName + ".png");
try {
return ImageIO.read(imageStream);
} catch (Exception e) {
final String errorMessage = "Failed to load image " + imageName;
System.err.println(errorMessage);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(MyBoardPannel.this, errorMessage,
"Image loading error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
});
}
return null;
}
}
I don't really know, but maybe your panel you use as parent of the JOptionPane (by passing this) is invisible or there is something else wrong. Try adding pack(); at the end of your JOptionPaneErrorShowing constructor.
What I know is that I had this problem when I was using an old Ubuntu and old Nvidia driver for my GPU, when the desktop effects were turned on (the Compiz Fusion of today. I don't know if it was already called Compiz, that long ago).
Aha! I found it, you are displaying the error inside the repaint method. Never do that! Load your image inside the constructor of the MyBoardPanel class and show error messages over there.

Categories