Primefaces graphicImage + Download img from URL - java

I would like to present an image that comes from an internal image server of the company. I can access it by an internal http address. Must present it without showing this internal address in the source code, using a p.graphicImage .
The View is here:
<p:fieldset legend="Dados pessoais">
<br/>
<p:graphicImage value="#{funcionarioEditMB.graphicText}" id="foto" cache="false">
<f:param name="id" value="#{funcionarioEditMB.bean.matricula}" />
</p:graphicImage>
<br/>
//--*-
MB related part:
//no init chamo esta função passando a matricula (this.getImagem(funcionario.getMatricula());)
public void getImagem(Integer matricula){
ByteArrayOutputStream os = null;
byte[] bytes = null;
FacesContext context = FacesContext.getCurrentInstance();
String id = context.getExternalContext().getRequestParameterMap().get("id");
try{
URL url = new URL(funcionarioBC.getImage(Integer.parseInt(id)));
BufferedImage image = ImageIO.read(url);
os = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", os);
bytes = os.toByteArray();
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
// So, we're rendering the view. Return a stub StreamedContent so that it will generate right URL.
graphicText = new DefaultStreamedContent();
} else {
// So, browser is requesting the image. Get ID value from actual request param.
graphicText = new DefaultStreamedContent(new ByteArrayInputStream(bytes));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private StreamedContent graphicText;
public StreamedContent getGraphicText() {
return graphicText;
}
But the image does not appear in the view. The following link is displayed:
http://localhost:8080/eSGRH/javax.faces.resource/dynamiccontent.properties.jsf?ln=primefaces&pfdrid=aiHZO8v7zFQ6p%2bPffO1S1vWT2KGBHKr%2bR3guIqtplAUT4IpnxJZmHw==&id=479488&pfdrid_c=false&uid=4e51fb92-b0bc-4530-8e3c-3d28fa750563
Could someone help me to understand what is wrong?

Related

Spring MVC Safe way to Upload, generate and download a file

I´m working on a WebApp with Spring MVC and Maven. I have the following process: First of all the User has to upload a file. Afterwards the uploaded file will be edited. Last but not least I want to create a download which contains the edited file.
The first step "Upload File" works well. I have a controller which contains the following POST method:
#RequestMapping(value = "/CircleUp", method = RequestMethod.POST)
public String circleUpPost(HttpServletRequest request, Model model, //
#ModelAttribute("circleUpForm") CircleUpForm circleUpForm) {
return this.doUpload(request, model, circleUpForm);
}
private String doUpload(HttpServletRequest request, Model model, //
CircleUpForm circleUpForm) {
File file = circleUpForm.getFile();
if (file != null) {
try {
//Some edit stuff
serialize(file, SerializationModeEnum.Standard);
} catch (Exception e) {
e.printStackTrace();
}
}
model.addAttribute("uploadedFiles", file);
return "uploadResult";
}
protected static String serialize(File file, SerializationModeEnum serializationMode) {
java.io.File test = null;
try {
test = java.io.File.createTempFile("Test", ".pdf");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
file.save(test, serializationMode);
} catch (Exception e) {
e.printStackTrace();
}
// test.deleteOnExit();
return test.getPath();
}
In the "serialize" Method my PDFClown File will be saved to a temp folder.
Afterwards the "uploadResult" page will be appear which contains the folloing code:
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<meta charset="UTF-8">
<title>Download</title>
</head>
<body>
<h3>Download Files:</h3>
CircleUp
</body>
</html>
When the User clicks on the link another Controller will be called which handles the download. I dont know how to design the controller so that it can works with the edited file which I saved in my temp folder. I think it should look like that :
#RequestMapping(value = "/Download")
public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
final String temperotyFilePath = ???
String fileName = "Test.pdf";
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos = convertPDFToByteArrayOutputStream(temperotyFilePath + "\\" + fileName);
OutputStream os = response.getOutputStream();
baos.writeTo(os);
os.flush();
} catch (Exception e1) {
e1.printStackTrace();
}
}
private ByteArrayOutputStream convertPDFToByteArrayOutputStream(String fileName) {
InputStream inputStream = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
inputStream = new FileInputStream(fileName);
byte [] buffer = new byte [1024];
baos = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return baos;
}
I have two questions now:
How can the DownloadController attain the temp path to the file?
Is this process of Uploading,Generating and Downloading a File safe? Or is there a better way to handle this process?
I´m new to Spring MVC and WebApp Development and I´m thankful for every suggestion :)
You can use the same approach you use in the upload
test = java.io.File.createTempFile("Test", ".pdf");
All you need is to point to the same file and then read it.
If you need a custom dir for the files saving you can either define a property - my.file.path=some path here or
use system temp dir
public class Main {
public static void main(String[] args) {
String property = "java.io.tmpdir";
String tempDir = System.getProperty(property);
System.out.println("OS current temporary directory is " + tempDir);
}
}
Got the code from the link
Actually the approach is not safe. What to do if 2 different users upload files with the same name& What if one is uploaded and another user tries to download it? What is amount of files is millions? etc. etc.
It's better to use independent file storage but for test project it's fine

Image URL to ParseFile?

I have a Parse Android app for which I am implementing Facebook sign up. Currently I am stuck on grabbing images to set as profile pictures of new ParseUser's. I have successfully used the Facebook Graph API to retrieve the correct URL (I have checked this by plugging it into a browser, where I am shown the right profile picture), but I now need a way to turn that URL into a byte array (byte[]) so that I can save the ParseFile field of our ParseUser's profile picture. I have already looked at all these SO questions:
• java.net.URL read stream to byte[]
• Efficiently read file from URL into byte[] in Java
• Get image with given url and convert it to byte array
None of these have worked. I am currently trying to use the Apache IOutils, like in the solution from the second link. Here is my current code for the AsyncTask:
private class SetProfPicWithURL extends AsyncTask<URL, Integer, byte[]> {
#Override
protected byte[] doInBackground(URL... imageURL) {
Log.i("SetProfPicWithURL", "invocation, URL: " + imageURL[0]);
InputStream is = null;
byte[] bytes = null;
try {
is = imageURL[0].openStream();
bytes = IOUtils.toByteArray(is);
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (is != null) try {
is.close();
if(bytes == null){Log.e("LoginActivity", "bytes is null int SetProfPicWithURL");}
final ParseFile imageFile = new ParseFile("image.jpg", bytes);
imageFile.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Log.i("LoginActivity", "getCurrentUser.put");
ParseUser.getCurrentUser().put(ParseUtils.PARSE_PROFILE_IMAGE, imageFile);
ParseUser.getCurrentUser().saveInBackground();
} else {
e.printStackTrace();
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
return bytes;
}
}
Now when this code executes, I get no error logs, and a ParseFile is created. However, no profile pictures load within the app, and when I click to examine the file in the dashboard, I get this error message:
The file “tfss-0280f98d-7180-4528-9d24-3ec47d3b25d4-image.jpg” could
not be opened because it is empty.
Honestly, I'm at a loss. I've spent significantly more time on this one photo issue than any other part of implementing the Facebook login. And the way our database is set up, it is really not ideal to create another field to save the URL and load with Picasso. Any help with this issue is truly appreciated!
Directly save your imagefile as profile picture like this :
final ParseFile imageFile = new ParseFile("image.jpg", bytes);
ParseUser.getCurrentUser().put(ParseUtils.PARSE_PROFILE_IMAGE, imageFile);
ParseUser.getCurrentUser().saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Log.i("LoginActivity", "Profile saved succesfully");
} else {
e.printStackTrace();
}
}
});
EDIT :
Use this to get image byte array from url.
try {
java.net.URL img_value = new java.net.URL(imageURL);
Bitmap mIcon = BitmapFactory
.decodeStream(img_value.openConnection()
.getInputStream());
if (mIcon != null)
imgByteArray = encodeToByteArray(mIcon);
} catch (Exception e) {
e.printStackTrace();
}
public byte[] encodeToByteArray(Bitmap image) {
Log.d(TAG, "encodeToByteArray");
Bitmap b= image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imgByteArray = baos.toByteArray();
return imgByteArray ;
}

How to get an image using Jsoup and pass to an ImageView

Good day,
I'm trying to retrieve an image using Jsoup but I'm unsure as to what exactly I should be getting from the website. I've used the following code to read from the website and have been able to get the images particular title and the URL it links to but not the image.
I want to set this image to the ImageView that I have in the activity. Here's my code thus far:
// Get the required stuff from the webpage
Document document = null;
try {
document = Jsoup.connect(URL).get();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Element info = document.select("div.featurebox").first();
// Caption on image
docInfo = info.text();
// URL of image
imageURL = info.attr("data-url");
// Retrieve the actual image
Element featureImage = document.select("div.featurebox-image").first();
// Unsure what to get here
It should be noted that the image isn't stored as a normal img-src way. The particular div class I'm looking at is this:
<div class="featurebox-image" style="background:url(http://img.mangastream.com/cdn/feature/02.jpg) center center;">
<div class="featurebox-caption">
<strong>History's Strongest Disciple Kenichi <em>544</em></strong> - Witch </div>
</div>
So I'm after the actual image from that URL.
How do i go about this?
Thanks
Thanks to Hardip Patel for providing the start. Here is what I did:
I took Hardips code and changed it to the following:
Element featureImage = document.select("div.featurebox-image")
.first();
String temp = featureImage.getElementsByAttribute("style")
.toString();
// URL of image
imageStrg = temp
.substring(temp.indexOf("(") + 1, temp.indexOf(")"));
After that it took alittle looking about StackOverflow to find out how to set it. I initially tryed to set it using the URL using the setImageURI() method, but that was throwing an error. See here for why. Instead I used that SoH's answer to create a bitmap from the URL:
// Method to return a bitmap from an images URL
private Bitmap getImageBitmap(String url) {
Bitmap bm = null;
try {
// See what we are getting
Log.i(TAG, "" + url);
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e(TAG, "Error getting bitmap", e);
}
return bm;
}
After that I just had to set the Bitmap from earlier and update the image view using the ASyncTask's onPostExecute() method:
imageOne = getImageBitmap(imageStrg);
#Override
protected void onPostExecute(String result) {
// Write the result (document title) to the textview
super.onPostExecute(result);
// Update the textview with results
if (result == null) {
txtVwDocTitleValue.setText("Nothing to report...");
} else {
txtVwDocTitleValue.setText(result);
txtVwDocURLValue.setText(imageURL);
// Set the views image
imgVwManga1.setImageBitmap(imageOne);
}
// Destroy the progress bar
stopProgressDialog();
}
Cheers all!
See if this works :-
String temp = featureImage.getAttribute("style");
String url = temp.substring(temp.indexOf("(")+1,temp.indexOf(")"));
Try this
Document doc = Jsoup.connect("www.mywebsite.com").get();
Elements images = doc.select("img[src~=(?i)\.(png|jpe?g|gif)]");

Why Image file not found in android on server but open in browser

I am trying to download image from server. Few are downloading and few and creating problem. I don't know why.
I have downloaded and show image to user on the same location. Here is the file which is able to download.
http://www.mongreldog.co.nz/unilogo/Backgrounds_20399.png
When I am trying to download following image. This image is opening in browser but not downloading in android
http://www.mongreldog.co.nz/unilogo/Twitter-Ryan_Giggs_Imogen_Thomas_Guard-Footballer_Affair_UK_Manchester%20United_M_785.jpg
Its give exception
java.io.FileNotFoundException: http://www.mongreldog.co.nz/unilogo/Twitter-Ryan_Giggs_Imogen_Thomas_Guard-Footballer_Affair_UK_Manchester United_M_785.jpg
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:521)
at src.com.mongreldog.appsupport.Utils.downloadImage(Utils.java:77)
at src.com.mongreldog.ViewFullCompAndCommentActivity$3.performInBackground(ViewFullCompAndCommentActivity.java:607)
at src.com.mongreldog.appsupport.HeavyWorker.doInBackground(HeavyWorker.java:44)
at src.com.mongreldog.appsupport.HeavyWorker.doInBackground(HeavyWorker.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
Here is my code.
public static Bitmap downloadImage(String imageURLStr) {
Bitmap bitmap = null;
InputStream in = null;
try {
URL url = new URL(imageURLStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
in = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (SocketTimeoutException e) {
bitmap = null;
e.printStackTrace();
} catch (IOException e) {
bitmap = null;
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
bitmap = null;
} catch (OutOfMemoryError e) {
e.printStackTrace();
bitmap = null;
}
return bitmap;
}
Use URL Encoder to encode the image URL, as you can see the URL have white spaces in the log report.
public static Bitmap downloadImage(String imageURLStr) {
imageURLStr = URLEncoder.encode(imageURLStr, "utf-8");
//... rest of your code.
}
Edit: as you reported of issue '+' instead of %20
you can use
public static Bitmap downloadImage(String imageURLStr) {
imageURLStr = imageURLStr.replaceAll(" ", "%20");
//... rest of your code.
}
For source check here
I try to use URLEncoder.encode() to encode the URL. Its strange that it convert " " with "+".
Please try Uri.encode(imageURL). I just try it and its working perfectly.
I have tested that in android.
Looks like the file name is not being parsed correctly (the space between 'Manchester' and 'United').
Use URLEncoder.encode() to encode the URL.
Your second URL is very instable. It may return 404 in the most cases even in Chome. I have seen the picture only once.

Java Servlet Image Upload Corrupt (gray bottom)

We have a servlet that accepts image uploads. Sometimes when the uploads originate in our iPhone client (flaky connection) the saved image can end up being partly or completely gray. I suspect this is due to the connection being prematurely terminated and the servlet ending up processing an incomplete image.
Whats the best remedy for this? Is there a way to see if the whole image was uploaded before processing? Should I use HTTP Content-Length header and compare whats uploaded with this number?
Thanks!
Some code for context:
#Path("images/")
#POST
#Consumes("image/*")
#Produces({"application/xml", "application/json"})
public AbstractConverter postImage(byte[] imageData) {
BufferedImage bufferedImage = null;
try {
bufferedImage = ImageIO.read(new ByteArrayInputStream(imageData));
} catch (Exception e) {
}
if (bufferedImage == null) {
throw new PlacesException("Image data not provided or could not be parsed", Response.Status.BAD_REQUEST);
}
...
BufferedImage scaledImage = ImageTool.scale(bufferedImage, imageSize);
BufferedImage thumbnail = ImageTool.scale(bufferedImage, thumbnailSize);
//Save image and thumbnail
File outputfile = new File(path);
ImageTool.imageToJpegFile(scaledImage, outputfile, 0.9f);
File tnOutputfile = new File(thumbnailPath);
ImageTool.imageToJpegFile(thumbnail, tnOutputfile, 0.9f);
...
public static void imageToJpegFile(RenderedImage image, File outFile, float compressionQuality) throws IOException {
//Find a jpeg writer
ImageWriter writer = null;
Iterator<ImageWriter> iterator = ImageIO.getImageWritersByFormatName("jpeg");
if (iterator.hasNext()) {
writer = iterator.next();
} else {
throw new RuntimeException("No jpeg writer found");
}
//Set the compression quality
ImageWriteParam params = writer.getDefaultWriteParam();
params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
params.setCompressionQuality(compressionQuality);
//Write to the out file
ImageOutputStream ios = null;
try {
ios = ImageIO.createImageOutputStream(outFile);
writer.setOutput(ios);
writer.write(null, new IIOImage(image, null, null), params);
} finally {
writer.dispose();
if (ios != null) {
try {
ios.flush();
} catch (Exception e) {
}
try {
ios.close();
} catch (Exception e) {
}
}
}
}
Seems that the upload did not complete properly.
As you point out yourself, your best bet is to use the HTTP Content-Length header to check that all data has been received. If not, discard the image.

Categories