(how) can I download an image using JSoup? - java

I already know where the image is, but for simplicity's sake I wanted to download the image using JSoup itself. (This is to simplify getting cookies, referrer, etc.)
This is what I have so far:
//Open a URL Stream
Response resultImageResponse = Jsoup.connect(imageLocation).cookies(cookies).ignoreContentType(true).execute();
// output here
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(new java.io.File(outputFolder + name));
//BufferedWriter out = new BufferedWriter(new FileWriter(outputFolder + name));
out.write(resultImageResponse.body()); // resultImageResponse.body() is where the image's contents are.
out.close();

I didn't even finish writing the question before I found the answer via JSoup and a little experimentation.
//Open a URL Stream
Response resultImageResponse = Jsoup.connect(imageLocation).cookies(cookies)
.ignoreContentType(true).execute();
// output here
FileOutputStream out = (new FileOutputStream(new java.io.File(outputFolder + name)));
out.write(resultImageResponse.bodyAsBytes()); // resultImageResponse.body() is where the image's contents are.
out.close();

Simply you can use these methods-
public static String storeImageIntoFS(String imageUrl, String fileName, String relativePath) {
String imagePath = null;
try {
byte[] bytes = Jsoup.connect(imageUrl).ignoreContentType(true).execute().bodyAsBytes();
ByteBuffer buffer = ByteBuffer.wrap(bytes);
String rootTargetDirectory = IMAGE_HOME + "/"+relativePath;
imagePath = rootTargetDirectory + "/"+fileName;
saveByteBufferImage(buffer, rootTargetDirectory, fileName);
} catch (IOException e) {
e.printStackTrace();
}
return imagePath;
}
public static void saveByteBufferImage(ByteBuffer imageDataBytes, String rootTargetDirectory, String savedFileName) {
String uploadInputFile = rootTargetDirectory + "/"+savedFileName;
File rootTargetDir = new File(rootTargetDirectory);
if (!rootTargetDir.exists()) {
boolean created = rootTargetDir.mkdirs();
if (!created) {
System.out.println("Error while creating directory for location- "+rootTargetDirectory);
}
}
String[] fileNameParts = savedFileName.split("\\.");
String format = fileNameParts[fileNameParts.length-1];
File file = new File(uploadInputFile);
BufferedImage bufferedImage;
InputStream in = new ByteArrayInputStream(imageDataBytes.array());
try {
bufferedImage = ImageIO.read(in);
ImageIO.write(bufferedImage, format, file);
} catch (IOException e) {
e.printStackTrace();
}
}

Related

Simplest way to read a file using jcifs

I am trying to read a file from a network share using the external jcifs library. Most sample codes I can find for reading files are quite complex, potentially unnecessarily so. I have found a simple way to write to a file as seen below. Is there a way to read a file using similar syntax?
SmbFile file= null;
try {
String url = "smb://"+serverAddress+"/"+sharename+"/TEST.txt";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null, username, password);
file = new SmbFile(url, auth);
SmbFileOutputStream out= new SmbFileOutputStream(file);
out.write("test string".getBytes());
out.flush();
out.close();
} catch(Exception e) {
JOptionPane.showMessageDialog(null, "ERROR: "+e);
}
SmbFile file = null;
byte[] buffer = new byte[1024];
try {
String url = "smb://"+serverAddress+"/"+sharename+"/TEST.txt";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null, username, password);
file = new SmbFile(url, auth);
try (SmbFileInputStream in = new SmbFileInputStream(file)) {
int bytesRead = 0;
do {
bytesRead = in.read(buffer)
// here you have "bytesRead" in buffer array
}
while (bytesRead > 0);
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null, "ERROR: "+e);
}
or even better, assuming that you're working with text files - using BufferedReader from Java SDK:
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new SmbFileInputStream(file)))) {
String line = reader.readLine();
while (line != null) {
line = reader.readLine();
}
}
And write with:
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new SmbFileOutputStream(file)))) {
String toWrite = "xxxxx";
writer.write(toWrite, 0, toWrite.length());
}
try {
String url = "smb://" + serverAddress + "/" + sharename + "/test.txt";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(DOMAIN, USER_NAME, PASSWORD);
String fileContent = IOUtils.toString(new SmbFileInputStream(new SmbFile(url, auth)), StandardCharsets.UTF_8.name());
System.out.println(fileContent);
} catch (Exception e) {
System.err.println("ERROR: " + e.getMessage());
}
I could read some pdf files using this:
private final Singleton<CIFSContext> contextoDdetran = new Singleton<>() {
#Override
public CIFSContext inicializar() {
NtlmPasswordAuthenticator autenticador = new NtlmPasswordAuthenticator(smbDomain, smbUser, smbPassword);
return SingletonContext.getInstance().withCredentials(autenticador);
}
};
public byte[] readSmbFile(String fileName) {
try {
SmbFile file = new SmbFile(fileName, this.contextoDdetran.get());
return file.getInputStream().readAllBytes();
} catch(Exception e) {
final String msgErro = String.format("Error reading file '%s': %s", fileName, e.getMessage());
logger.error(msgErro, e);
throw new IllegalStateException(msgErro);
}
}

Read pdf files placed at one server from another server

I have two node on production environment. I have placed pdf files at one server and want to read it from both server. when am calling 'file' method directly pdf get displayed in browser but when i call 'pdfFiles' nothing is displayed in browser.
public Resolution file(){
try {
final HttpServletRequest request = getContext().getRequest();
String fileName = (String) request.getParameter("file");
File file = new File("pdf file directory ex /root/pdffiles/" + fileName);
getContext().getResponse().setContentType("application/pdf");
getContext().getResponse().addHeader("Content-Disposition",
"inline; filename=" + fileName);
FileInputStream streamIn = new FileInputStream(file);
BufferedInputStream buf = new BufferedInputStream(streamIn);
int readBytes = 0;
ServletOutputStream stream = getContext().getResponse().getOutputStream();
// read from the file; write to the ServletOutputStream
while ((readBytes = buf.read()) != -1)
stream.write(readBytes);
} catch (Exception exc) {
LOGGER.logError("reports", exc);
}
return null;
}
public Resolution pdfFile() {
final HttpServletRequest request = getContext().getRequest();
final HttpClient client = new HttpClient();
try {
String fileName = (String) request.getParameter("file");
final String url = "http://" + serverNameNode1 //having pdf files
+ "/test/sm.action?reports&file=" + fileName;
final PostMethod method = new PostMethod(url);
try {
client.executeMethod(method);
} finally {
method.releaseConnection();
}
} catch (final Exception e) {
LOGGER.logError("pdfReports", "error occured2 " + e.getMessage());
}
return null;
}
Included below part of code after 'client.executeMethod(method);' in 'pdfFile()' method and it works for me.
buf = new BufferedInputStream(method.getResponseBodyAsStream());
int readBytes = 0;
stream = getContext().getResponse().getOutputStream();
// write to the ServletOutputStream
while ((readBytes = buf.read()) != -1)
stream.write(readBytes);

NoOutputStreamException during image upload in vaadin

Trying to upload only images. The problem is that I don't know how to handle this situation.
#Override
public OutputStream receiveUpload(String filename, String mimeType) {
FileOutputStream fos = null;
if(mimeType.startsWith("image")) {
picture = new Picture();
picture.filename = filename;
picture.mimeType = mimeType;
picture = HibernateUtils.save(picture);
product.pictures.add(picture);
File dirs = new File(IMAGE_LOCATION);
File file = new File(IMAGE_LOCATION + picture.id);
if (!dirs.exists()) {
dirs.mkdirs();
}
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
} else {
Notification.show("", Notification.Type.ERROR_MESSAGE);
}
return fos;
}
The problem is that the fos variable will be null if I try to upload different type of files than image. The question is that, how should I handle it?
I'd do something like this:
...
} else {
Notification.show("", Notification.Type.ERROR_MESSAGE);
return new ByteArrayOutputStream();
}
...

Writing/Reading gif internal storage

I'm trying to load a gif from a url to be displayed in an Imageview, store it in the internal storage and then later read it again. But it refuses to either store the image or reading it, not sure which one because I get no exceptions. Loading the image to the imageview works. The first method below (loadImage())
public Bitmap loadImage(String url){
Bitmap bm = null;
URL request;
try {
if(url!=null){
request = new URL(url);
InputStream is = request.openStream();
bm = BitmapFactory.decodeStream(is);
is.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bm;
}
public String writeGifToInternalStorage (Bitmap outputImage) {
try {
String fileName = String.valueOf(Calendar.getInstance().getTimeInMillis());
ByteBuffer byteBuffer = ByteBuffer.allocate(outputImage.getByteCount());
outputImage.copyPixelsToBuffer(byteBuffer);
byteBuffer.flip();
byte[] data = new byte[byteBuffer.limit()];
byteBuffer.get(data);
FileOutputStream fos = ctx.openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(data);
fos.close();
return fileName;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public Bitmap readFileFromInternalStorage(String filename) {
if (filename == null) return null;
FileInputStream fis;
try {
fis = ctx.openFileInput(filename);
return BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
Any ideas of whats wrong?
Your method readFileFromInternalStorage read an encoded image from the file system. This image file should be what you receive from the server.
For that, you need to save the image when you receive it from the server, for example like so:
InputStream is = new BufferedInputStream(request.openStream());
String fileName = String.valueOf(Calendar.getInstance().getTimeInMillis());
FileOutputStream fos = ctx.openFileOutput(fileName, Context.MODE_PRIVATE);
byte[] buffer = new byte[1024];
int red = 0;
while ((red = is.read(buffer)) != -1) {
fos.write(buffer,0, red);
}
fos.close();
is.close();
Then, your image is saved to the disk, and you can open it using your readFileFromInternalStorage method.
Also, if you use HttpClient instead of URL, I wrote a one-liner for downloading a file: Android download binary file problems

Resolving the issue: Illegal characters in path

I am developing an application that takes an XML file and an attachment to be sent to the following path. This path is for a fax appliance.
I keep getting this error message:
Problem processing drop file "\co1-aux01prd01.tampa.healthe\Fax_Drop\Outbox\FaxDropSample1.xml": Illegal characters in path.
The XML file and the attachment are both being created but not processed.
public class TestSender {
public static void main(String[] args) {
String outBox = "\\\\faxaux\\Fax_Drop\\Outbox";
String filename = "FaxDrop" + ".xml";
String filepath = outBox + "\\" + filename;
Writer writer = null;
try {
BufferedImage image;
URL url = new URL("http://colsolgrp.com/phone/jpg/fax8.jpg");
image = ImageIO.read(url);
//File newImage = new File("\\\\faxaux\\Fax_Drop\\Outbox\\AttachmentFolder\\attachment.jpg");
File newImage = new File("\\\\faxaux\\Fax_Drop\\Outbox\\FaxDrop\\FaxDropImage.jpg");
newImage.mkdirs();
newImage.createNewFile();
ImageIO.write(image, "jpg",newImage);
System.out.println("File has been written");
}
catch(Exception e) {
System.out.println("Could not create file");
}
try {
File f = new File(filepath);
f.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(f);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
writer = new BufferedWriter(outputStreamWriter);
// Create XML file here
}
catch (Throwable ex) {
ex.printStackTrace();
}
finally {
try {
writer.close();
}
catch (Exception ex) {
// Do nothing.
}
}
System.out.println("Success");
Try this:
URI u = new URI(URLEncoder.encode("\\co1-aux01prd01.tampa.healthe\Fax_Drop\Outbox\FaxDropSample1.xml"));

Categories

Resources