What to do with getParameter() in the java code? - java

I am making a java applet which has to play video file. I have searched a code on the net but it gives an error at getParameter
Here is the code...
public void init() {
//$ System.out.println("Applet.init() is called");
setLayout(null);
setBackground(Color.white);
panel = new Panel();
panel.setLayout( null );
add(panel);
panel.setBounds(0, 0, 320, 240);
// input file name from html param
String mediaFile = null;
// URL for our media file
MediaLocator mrl = null;
URL url = null;
// Get the media filename info.
// The applet tag should contain the path to the
// source media file, relative to the html page.
// Error here: Invalid media file parameter
if ((mediaFile = getParameter("C:\\Users\\asim\\Documents\\JCreator LE\\MyProjects\\SimplePlayerApplet\\src\\Movie.avi")) == null)
Fatal("Invalid media file parameter");
try {
url = new URL(getDocumentBase(), mediaFile);
mediaFile = url.toExternalForm();
} catch (MalformedURLException mue) {
}
Here is the link to whole code :
http://docs.oracle.com/javase/1.4.2/docs/guide/plugin/developer_guide/SimplePlayerApplet.java.html

How are you 'invoking' your applet?
It seems you are trying to specify the 'parameter' as something that sits on the local file system yet you are building an 'applet' so you should really be invoking it via HTML and then pass the 'parameter in as such:
<applet code=SimplePlayerApplet.class width=320 height=300>
<param name="file" value="sun.avi">
</applet>
and thus your getParameter call should still be for "file". Just as in the code you were using before.

A couple of thoughts here:
You're using a file that reside in the local filesystem. Applets by default don't have an access to the filesystem. There is a comment above the method from the tutorial. And its clearly states the the file should be relative to html page and reside on server. Just read carefully comments there.
The example uses Applet (the class they provide extends the Applet) - its an old approach and now its deprecated. Basically what it does is uses AWT instead of newer Swing. So you should look for an example of using JApplet instead.
Hope this helps.

You should place the parameter in HTMLpart, this would make the applet independend from the content. You confused the parameter name with its value.
<HTML> <BODY>
<APPLET CODE="SimplePlayerApplet.class" WIDTH=320 HEIGHT=240>
<PARAM NAME="filename" VALUE="C:\\Users\\asim\\Documents\\JCreator LE\\MyProjects\\SimplePlayerApplet\\src\\Movie.avi">
</APPLET>
</BODY> </HTML>
if ((mediaFile = getParameter("filename")) == null)
...
In order to access the filesystem you need to sign the applet.
The Line:
URL(getDocumentBase(), mediaFile);
tries to open the mediaFile relative from DocumentBase. This means relative to the URL of the document in which this applet is embedded.
See alse Applet.
Thus the easiest way to get it run would be to copy your Movie.avi in the same folder where your HTML-File resides and use
URL(getDocumentBase(), "Movie.avi");
After that you should make it configurable by supplying the filename as a parameter.

Related

Error while displaying image in jsp

First of all, i read tons of posts regarding this but i can't manage to get this working.
I'm really new to jsp and web apps. All i wanna do is to display a simple image.
I have this code in the servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession sesion = request.getSession();
String filePath = getServletContext().getRealPath("image.jpg");
System.out.println(filePath);
sesion.setAttribute("image", filePath);
response.sendRedirect("products.jsp");
}
And this code in the jsp:
<img alt="logo" src="${image}"/>
And the folders in my web app are this:
folders image
And finally, when my page loads, this is what i get:
image does not display
I wonder what is the error here? Why it is so complicated (maybe it's not, but i really tried many ways and non of them worked) to display a simple image?
Thanks in advance for your help!
PS: the folder is correct, it prints without problem in the println()
getRealPath() gets you the real path in the file system.
When you reference any resource (image, js, css) inside a web it is supposed to be accesible via web.
If you click "view source code" in your browser you'll probably see the fil system path in the tag:
<img alt="logo" src="C:/whatever-your-path-is/image.jpg"/>
But what you need is the url path (full or relative) of the resource.
Try this instead:
sesion.setAttribute("image", "resources/images/image.jpg");

Need to hide the files which are being used from Assets folder

I am using an offline application which has html,css and js files in the assets folder.When i install the application on a device a can access those files from file:////storage/emulated/0/Android/data/myapp.name/files. I need a way to hide these files at it causes a security issue. I load my app from UI webview through one of the files in assets folder
I need a way to hide these files at it causes a security issue
First, they are not files. They are assets. They are stored in the APK file, not as files on the filesystem.
Second, you cannot "hide" assets. They are in your APK, and anyone can take your APK and retrieve those assets. It is unlikely that anyone will bother to do this.
You wont be able to hide assets.
As a workaround, you can do the following:
Copy the content of your HTML, CSS and JS files in a long text String.
When app is loaded for the first time, load the string content and create a Private file at runtime and save it in Internal Storage.
Files written in Internal storage by an app can not be accessed by any other apps, including a file explorer. so they are safe from misuse.
use this code to store private file in internal storage:
String filename = "yourfile.html";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
To protect assets folder information If the html file is either css or js, the easiest way is to:
Write your code in the html editor first, and then enter it in a Java class as follows :
public class Content{
public static final String myContent ="<!DOCTYPE html> ... </html> "
And then call through the loadDataWithBaseURL method
webView.loadDataWithBaseURL(null,Content.myContent, "text/html" , "UTF-8" ,null);
And you can call js and css in html code :
...
<head>
<link rel="stylesheet" type="text/css"
href="file:///android_asset/css/custom.css" />
<script src="file:///android_asset/js/code.jquery.js"></script>
</head>

Servlet in Eclipse - Where to put static content [duplicate]

This question already has answers here:
Simplest way to serve static data from outside the application server in a Java web application
(10 answers)
Closed 9 years ago.
When writing a servlet with Eclipse, where am I to put my static content (images, CSS, etc.), so that I can make my HTML link to it (e.g. <img src="http://localhost:8080/context/image.png>). I have tried putting it into the WebContent directory, but that didn't work (or I didn't know how to link to it, I tried <img src="image.png"> and also <img src="http://localhost:8080/context/image.png">).
I attached an image of my Project Explorer, so you can maybe sort it in.
To make it easier to find, here is everything I posted in comments or elsewhere:
The project's web.xml: http://pastebin.com/sTg4ugyw
My Servlet code: http://pastebin.com/az97bZAY
One of my HTML templates: http:pastebin.com/6KALf0Bw
Create a test.html file and place it at /Blog/WebContent/test.html in your Eclipse project.
<html>
<head>
<title>Test WebContent</title>
</head>
<body>
<img src="images/test.png" />
</body>
</html>
Also place a test.png image file inside the /Blog/WebContent/images folder.
Now, point your browser to http://localhost:8080/<your-web-app-name>/test.html and check if test.png gets rendered or not. If yes, then the problem lies in the way you're writing HTML output from your servlet.
For a sample ImgServlet configured as
<servlet>
<servlet-name>ImgServlet</servlet-name>
<servlet-class>pkg.path.to.ImgServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImgServlet</servlet-name>
<url-pattern>/ImgServlet</url-pattern>
</servlet-mapping>
your doGet() method should ouput HTML as
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Test WebContent</title></head>" +
"<body><img src=\"images/test.png\" /></body></html>");
EDIT: To print all the request parameters your servlet is receiving add the following just before your handleRequest() method call (which you can comment out also for testing)
PrintWriter out = response.getWriter();
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String param = (String) parameterNames.nextElement();
out.println(param + " = [" + request.getParameter(param) + "]");
}
Try
<img src="/context/image.png">
But it does depend on how you deploy your application. Anyways, files like images must be inside WebContent folder.
First of all, dont hard code your context in your link, it will make you hard to change the link later if your context path is changed. Instead, use EL to make the relative path:
<img src="${pageContext.request.contextPath}/img/abc.png" />
Secondly, I dont see any image in your WebContent, if you put the image manually into the window folder, you need to refresh eclipse project in order to let eclipse detects all the added files. Right click on your project in the Project Explorer and select Refresh

How I do get an image blob from JSP to JavaScript?

I retrieved a blob along with some other data from a table, say name and image:
name = varchar, image = blob
I set this to an object in my filter and pass it to the JSP file:
request.setAttribute("info", object);
In the JSP file I get that data:
request.getAttribute("info");
Now that I have the data from that object how do I go about passing that info to my JS file and render the image as a source for the JS file?
I'm trying:
<div>
<script type="text/javascript" src="jsFile.js></script>
</div>
var name = <%=info.name%>;
var image = <%=info.image%>
It just doesn't seem to be working. What is the correct method of doing this?
This isn't going to work. Leave the blob there in the server side. JavaScript on the client side can't do anything sensible with binary data. All it needs is an URL of the image so that it can reference it in the src attribute of a HTML <img> element, so that the webbrowser can in turn do its job of downloading and displaying the image. Best would be to include the image identifier in the URL. The name is unique for the image, right? Use that in the URL instead.
The first step is to let JS create a HTML <img> element with the proper src attribute which points to an URL which returns the image. Assuming that you're preparing the data like follows
String name = "foo.png";
String imageURL = "imageservlet/" + name;
request.setAttribute("imageURL", imageURL);
and are printing it in JSP(!) as if it are JS variables as follows
<script>
var imageURL = '${imageURL}';
// ...
</script>
(please note that those singlequotes are thus mandatory to represent them as a JS string variable)
so that they end up in the generated HTML source like follows (rightclick page in browser and do View Source to verify it)
<script>
var imageURL = 'imageservlet/foo.png';
// ...
</script>
then you can create the image as follows
var img = document.createElement("img"); // or getElementById("someId")?
img.src = imageURL;
// ... add to document?
(please note that this is just an example, I have no utter idea what the functional requirement is and what you would like to do with this image element, even more, perhaps JS code isn't needed at all for the concrete functional requirement)
so that it ends up like this in HTML:
<img src="imageservlet/foo.png" />
Now, the second step is to create a servlet which listens on an URL pattern of /imageservlet/*, retrieves the image as an InputStream from the database by the passed-in indentifier and writes it to the OutputStream of the response along a set of correct response headers. Long story short, I've posted several answers before as to how to do it, they contains kickoff code snippets:
How to retrieve and display images from a database in a JSP page?
Writing image to servlet response with best performance
You can access your data from the script if you set the variables in a script block before your jsFile.js. Ie:
<div>
<script type="text/javascript">
var name = <%=info.name%>;
var image = <%=info.image%>;
</script>
<script type="text/javascript" src="jsFile.js></script>
</div>
I'm not sure how you intend to handle the binary (BLOB) image data however? Typically this would be written to an image file on the server and referenced via an img tag:
<img src="/path/to/myimage.jpg" />
Instead of passing your blob data to the JSP file, I would suggest having the server (your servlet) pass a URL to the JSP which the browser can use to get the image via an img tag. You can either write the blob data to a URL or write a servlet that writes out Content-type: image/jpeg (or similar) data when passed an id, ie:
<img src="http://www.yourserver.com/GetImage?imageId=xxx" />

How to display a dynamically-generated image (barcode) on a web page?

I have a barcode that I am dynamically generating, and want to pass to a gsp that will later become a pdf. I do not need to persist the barcode for any of my own purposes, and would like to simply pass the image from the controller to the gsp.
Is there a way to render an image that is passed as a variable rather than specifying a src?
Thanks in advance.
EDIT:
Since I am generating the pdf from the gsp, I am flushing the output stream of the response then, and therefore cannot do it with the image also, or I get an error.
Furthermore, using javascript/jQuery does not work since the page is never rendered directly by the browser.
It may look like the only option I have is to persist the images temporarily somewhere, and then delete them...
I answered a similar question recently, perhaps its answer will work for you. I'll paste a portion of it here. It's basically Oded's "outside of this..." suggestion.
class BarcodeController {
def index = {
def img // byte array, set this to the binary contents of your image
response.setHeader('Content-length', img.length)
response.contentType = 'image/png' // or the appropriate image content type
response.outputStream << img
response.outputStream.flush()
}
}
You could then access your image in the src of an tag like this:
<img src="${g.link(controller: 'barcode', action: 'index')}"/>
This answer seems to fit the last comment you made on the question (about a similar solution using PHP).
You can use a data URI scheme for the src attribute.
The data URI scheme is a URI scheme that provides a way to include data in-line in web pages as if they were external resources.
Here is an example from the wikipeida article:
<img src="data:image/png;base64,
iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGP
C/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IA
AAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1J
REFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jq
ch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0
vr4MkhoXe0rZigAAAABJRU5ErkJggg==" alt="Red dot" />
Outside of this, if you are using a server side technology, you can stream the image data from a script (with the correct mime-type) and point the src attribute to it.
Here is a related SO question for grails.
Just want to contribute to this age-old question. I got this working by adding the following lines to BuildConfig.groovy:
In the plugins section:
plugins {
// other plugins here
// ...
compile ":barcode4j:0.3"
compile ":rendering:1.0.0"
}
In the dependencies section:
dependencies {
// other dependencies here
// ...
compile 'avalon-framework:avalon-framework:4.1.5'
}
Then I added a controller based on code examples I found on the net. I needed specifically a DataMatrix generator, but adding others should be easy just adding methods to the controller. Sorry for the bad quality code (I'm a Groovy newbie):
package myproject
import org.krysalis.barcode4j.impl.datamatrix.DataMatrix
import java.awt.Dimension
class BarcodeController {
// a valid PNG image, base64 encoded
static invalidBarcodeImgBase64 = """iVBORw0KGgoAA...=="""
// Needs index.gsp for testing
def index() {
['uuid': UUID.randomUUID(), 'fecha': new Date()]
}
def dataMatrix(String value) {
if ((null == value) || (value.length() < 1) || (value.length() > 2000)) {
def img = invalidBarcodeImgBase64.decodeBase64()
response.setHeader('Content-length', new Integer(img.length).toString())
response.contentType = 'image/png'
response.outputStream << img
response.outputStream.flush()
} else {
def generator = new DataMatrix()
generator.dataMatrixBean.setMinSize(new Dimension(16, 16))
renderBarcodePng(generator, value, [antiAlias: false])
}
}
def datamatrix(String value) {
dataMatrix(value)
}
}
Finally here's index.gsp in the barcode view for testing:
<%# page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<title>DataMatrix</title>
</head>
<body>
<g:img dir="barcode" file="dataMatrix?value=${uuid}"/>
<br />
<br />
<g:img dir="barcode" file="dataMatrix?value=${fecha}"/>
<br />
<br />
<g:img dir="barcode" file="dataMatrix?value=Nothing to see here"/>
</body>
</html>

Categories

Resources