How can I add an image to Restlet template? - java

I created a resource: /accounts/{accountId} which uses classes AccountServerResource.class, AccountPage.class and template accountPage.ftl.
Just for testing purpose I created a very simple template containing just one string:
<h1>Hello world</h1>
The page localhost:8111/accounts/21 is displayed correctly.
Now I want to go further and to add some more information to the resource. What I tried to do first, was adding an image to the template:
<h1>Hello, world</h1> <img src="img/user21.jpg">
But this time the image is not displayed. I have an error: the resource localhost:8111/accounts/21/img/user21.jpg is not found. The folder img is stored in the folder containing all *.class files and *.ftl files
How can I expose the image on my template page?

public class TestStaticFile {
public static void main(String[] args) {
Component component = new Component();
Application application = new Application() {
#Override
public Restlet createInboundRoot() {
Directory dir = new Directory(getContext(), "file:///d:/test");
dir.setListingAllowed(true);
return dir;
}
};
component.getServers().add(new Server(Protocol.HTTP, 8888));
component.getClients().add(Protocol.FILE);
component.getDefaultHost().attach(application);
try {
component.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
If the path of the image is D:/test/test.jpg, now you can access with the url:http://127.0.0.1:8888/test.jpg.
You can refer to the link of the image you want to display in img tag. Restlet supports static files. Save the image in the specified folder and then refer to it in your code.
The Static files setction in restlet user guide may help.

Related

Access public assets with Java in Play Framework

Is it possible to access Assets inside the Java code in Play Framework? How?
We access assets from the scala HTML templates this way:
<img src="#routes.Assets.versioned("images/myimage.png")" width="800" />
But I could not find any documentation nor code example to do it from inside the Java code. I just found a controllers.Assets class but it is unclear how to use it. If this is the class that has to be used, should it maybe be injected?
I finally found a way to access the public folder even from a production mode application.
In order to be accessible/copied in the distributed version, public folder need to be mapped that way in build.sbt:
import NativePackagerHelper._
mappings in Universal ++= directory("public")
The files are then accessible in the public folder in the distributed app in production form the Java code:
private static final String PUBLIC_IMAGE_DIRECTORY_RELATIVE_PATH = "public/images/";
static File getImageAsset(String relativePath) throws ResourceNotFoundException {
final String path = PUBLIC_IMAGE_DIRECTORY_RELATIVE_PATH + relativePath;
final File file = new File(path);
if (!file.exists()) {
throw new ResourceNotFoundException(String.format("Asset %s not found", path));
}
return file;
}
This post put me on the right way to find the solution: https://groups.google.com/forum/#!topic/play-framework/sVDoEtAzP-U
The assets normally are in the "public" folder, and I don't know how you want to use your image so I have used ImageIO .
File file = new File("./public/images/nice.png");
boolean exists = file.exists();
String absolutePath = file.getAbsolutePath();
try {
ImageInputStream input = ImageIO.read(file); //Use it
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("EX = "+exists+" - "+absolutePath);

Java code working fine when created as an independent static main class, but not when called from servlet

I am using Tess4j API for performing OCR and have created a dynamic web project in eclipse. If I create a new java class directly under the Java resources folder, the code is working fine.
public static void main(String[] args){
File image = new File("Scan0008.jpg");
ITesseract instance = new Tesseract();
try{
String result = instance.doOCR(image);
System.out.println(result);
}catch(TesseractException e){
System.err.println(e.getMessage());
}
}
However I am getting an exception when I am calling the same code from my Servlets doPost method.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Validate valObj = new Validate();
valObj.validate();
}
public void validate() {
File image = new File("Scan0008.jpg");
ITesseract instance = new Tesseract();
try {
String result = instance.doOCR(image);
System.out.println(result);
} catch (TesseractException e) {
System.err.println(e.getMessage());
}
}
I have included all the required jars under lib folder of WEB-INF. Have also added the jars in the projects build path. Could anyone please let me know what I am doing wrong.
Exception :
java.lang.IllegalStateException: Input not set
23:33:45.002 [http-bio-8080-exec-5] ERROR net.sourceforge.tess4j.Tesseract - Input not set
java.lang.IllegalStateException: Input not set
I think your current directory is different when you are calling from servlet. the current directory is you tomcat bin folder. so when you are calling like this:
File image = new File("Scan0008.jpg");
your scan0008.jpg must be put in bin folder of tomcat or you must use absolute path of your file.

Exporting image in runnable jar doesn't work

I'm having a weird problem in java. I want to create a runnable jar:
This is my only class:
public class Launcher {
public Launcher() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
String path = Launcher.class.getResource("/1.png").getFile();
File f = new File(path);
JOptionPane.showMessageDialog(null,Boolean.toString(f.exists()));
}
}
As you can see it just outputs if it can find the file or not. It works fine under eclipse (returns true). i've created a source folder resources with the image 1.png. (resource folder is added to source in build path)
As soon as I export the project to a runnable jar and launch it, it returns false.
I don't know why. Somebody has an idea?
Thanks in advance
edit: I followed example 2 to create the resources folder: Eclipse exported Runnable JAR not showing images
If you would like to load resources from your .jar file use getClass().getResource(). That returns a URL with correct path.
Image icon = ImageIO.read(getClass().getResource("imageĀ“s path"));
To access images in a jar, use Class.getResource().
I typically do something like this:
InputStream stream = MyClass.class.getResourceAsStream("Icon.png");
if(stream == null) {
throw new RuntimeException("Icon.png not found.");
}
try {
return ImageIO.read(stream);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
stream.close();
} catch(IOException e) { }
}
Still you're understand, Kindly go through this link.
Eclipse exported Runnable JAR not showing images
Because the image is not separate file but packed inside the .jar.
Use the code to create the image from stream
InputStream is=Launcher.class.getResourceAsStream("/1.png");
Image img=ImageIO.read(is);
try to use this to get image
InputStream input = getClass().getResourceAsStream("/your image path in jar");
Two Simple steps:
1 - Add the folder ( where the image is ) to Build Path;
2 - Use this:
InputStream url = this.getClass().getResourceAsStream("/load04.gif");
myImageView.setImage(new Image(url));

Loading and displaying local Images in Java Applet

When I run my program as a Java Application, everything works fine. However, when I run my program as a Java Applet, the images do not load, and I get this stack trace:
javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(Unknown Source)
at com.asgoodasthis.squares.Tile.<init>(Tile.java:42)
at com.asgoodasthis.squares.Component.start(Component.java:80)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I have a directory named res in my project directory, and I am loading my images like this:
public static BufferedImage tileset_terrain;
public loadImage() {
try {
//loading our images
tileset_terrain = ImageIO.read(new File("res/tileset_terrain.png"));
} catch(IOException e1) {
e1.printStackTrace();
}
}
So how do I get the images to load when I run my program as an applet? I am using Eclipse IDE.
It's likely the image can't be accessed from its current context, remember, applets normally run in a very tight security sandbox which prevents them from accessing files on the local/client file system.
You either need to load the images from the server the applet is been loaded from (using getDocument/CodeBase or a relative URL), or based on your example, as embedded an resource, for example
tileset_terrain = ImageIO.read(getClass().getResource("/res/tileset_terrain.png"));
This assumes that the image is included within the Jar file under the /res directory.
If the image resides on the server from which the applet is been load, you could also use
try {
URL url = new URL(getCodeBase(), "res/tileset_terrain.png");
img = ImageIO.read(url);
} catch (IOException e) {
e.printStackTrace();
}
Take a look at Reading/Loading images and What Applets Can and Cannot Do for more details.
Since it's an Applet and that runs in the browser hence you have to use Applet#getCodeBase() and Applet#getDocumentBase
Image image = getImage(getDocumentBase(), "tileset_terrain.png");
Find more samples Here and Here
The code You are using can induce many exception.
Image = getImage(getCodeBase(), "res/tileset_terrain.png");//can beused in your code
You can try this code.
import java.awt.*;
import java.applet.*;
public class DisplayImage extends Applet {
Image picture;
public void init() {
picture = getImage(getDocumentBase(),"res/tileset_terrain.png");
}
public void paint(Graphics g) {
g.drawImage(picture, 30,30, this);
}
}

Loading Image in Java Applet

When I try to run an applet in applet viewer it is not able to find resources (Image).
I try to load resource like this:
String cb= this.getCodeBase().toString();
String imgPath = cb+"com/blah/Images/a.png";
System.out.println("imgPath:"+imgPath);
java.net.URL imgURL = Applet.class.getResource(path);
but when i run it in appet viewer path is like this:
imgPath:file:D:/Work/app/build/classes/com/blah/Images/a.png
though image is there in this path,
is prefix file: causing problem, how can i test this code?
Will this code work when deployed in server and codebase returns a server URL?
Is your applet supposed to load images after it is loaded? Or would you be better served bundling necessary image resources in the jar with your applet?
I work daily on an applet-based application with plenty of graphics in the GUI.
They are bundled in the jar-file.
This si what we do:
// get the class of an object instance - any object.
// We just defined an empty one, and did everything as static.
class EmptyClass{}
Class loadClass = new EmptyClass().getClass();
// load the image and put it directly into an ImageIcon if it suits you
ImageIcon ii = new ImageIcon(loadClass.getResource("/com/blah/Images/a.png"));
// and add the ImageIcon to your JComponent or JPanel in a JLabel
aComponent.add(new JLabel(ii));
Make sure your image is actuallly in the jar where you think it is.
Use:
jar -tf <archive_file_name>
... to get a listing.
Just use /com/blah/Images/a.png as the path. getResource() is clever enough to find it.
The context classloader should work with jars.
ClassLoader cl = Thread.getContextClassLoader();
ImageIcon icon = new ImageIcon(cl.getResource("something.png"), "description");
Try this code it's only 2 methods out of the class I use to load images but it works fine for loading when using an applet.
private URL getURL(String filename) {
URL url = null;
try
{
url = this.getClass().getResource("" + extention + filename); //extention isn't needed if you are loading from the jar file normally. but I have it for loading from files deeper within my jar file like say. gameAssets/Images/
}
//catch (MalformedURLException e) { e.printStackTrace(); }
catch (Exception e) { }
return url;
}
//observerwin in this case would be an applet. Simply have the class have something like this: Applet observerwin
public void load(String filename) {
Toolkit tk = Toolkit.getDefaultToolkit();
image = tk.getImage(getURL(filename));
while(getImage().getWidth(observerwin) <= 0){loaded = false;}
double x = observerwin.getSize().width/2 - width()/2;
double y = observerwin.getSize().height/2 - height()/2;
at = AffineTransform.getTranslateInstance(x, y);
loaded = true;
}
I can post the rest of the class I use if needed

Categories