Saving a .jpg to byte[] android - java

This shouldn't be that hard, but I cannot figure this out. I need to save an image, on my end only, and build it dynamically so all my users will view these images. The tutorials on Parse.com are very helpful, but not in the case of images. I need detailed explanations or helpful links. Thanks for looking.
This is all I have so far as far as saving an image. I am properly getting the file in my Data Browser, but if I try to view it, it only shows my string "beatdown.jpg" not the actual jpg.
....
private void saveImage() {
// TODO Auto-generated method stub
InputStream header = new FileInputStream("beatdown.jpg");
byte[] head = IOUtils.toByteArray(header);
ParseFile file = new ParseFile(head);
try{
file.save();
} catch (ParseException e) {
e.printStackTrace();
}
ParseObject displayImage = new ParseObject("displayImage");
displayImage.put("header", file);
try{
displayImage.save();
} catch (ParseException e1){
e1.printStackTrace();
}
}
I understand I am trying to get the string of "beatdown.jpg" to bytes in the code above, and it is not handling it as a .jpg. But I don't know how to make it a .jpg.
EDIT: I added commons-io. But when I run the code (see the above updated code), it won't register on anything on parse.com. I am getting this in my logcat;
Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection#40cf2498 that was originally bound here

The key elements are:
File f = new File("pathToFile");
FileInputStream fis = new FileInputStream(f);
byte[] bytes = new byte[f.length()];
fis.read(bytes);
Of course there's exception handling and the like to do, but this should be enough to give you the general idea.

Related

Why do I get NullPointerException when trying to access resource file?

I want to make so a file in the program is packaged in the jar file because it is needed in my program. It is the firebase credentials file. I read that I need to add it to the resource folder but now I cannot access it because I get NullPointerException. I think the path is valid and everything seems okay but I get null every time. Here is the code:
ClassLoader classLoader = EmailSender.class.getClassLoader();
File file = new File(Objects.requireNonNull(classLoader.getResource("/parkingsystem-cf164-firebase-adminsdk-5jjuk-2be72bfcce.json")).getFile());
And here is the code structure:
code structure
If there is another method to add file to jar I am open to hear it, it is just what I found on the Internet but it does not work for me. Any help is appreciated!
Edit: So apparently it works when the / is removed but then I need to convert it to FileInputStream and there I get FileNotFoundExcpetion. The rest of the code:
FileInputStream serviceAccount = null;
try {
serviceAccount = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
FirebaseOptions options = null;
try {
options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.build();
} catch (IOException e) {
e.printStackTrace();
}

Can static content on spring-boot-web application be dynamic (refreshed)?

I am still searching around this subject, but I cannot find a simple solution, and I don't sure it doesn't exist.
Part 1
I have a service on my application that's generating an excel doc, by the dynamic DB data.
public static void
notiSubscribersToExcel(List<NotificationsSubscriber>
data) {
//generating the file dynamically from DB's data
String prefix = "./src/main/resources/static";
String directoryName = prefix + "/documents/";
String fileName = directoryName + "subscribers_list.xlsx";
File directory = new File(directoryName);
if (! directory.exists()){
directory.mkdir();
// If you require it to make the entire directory path including parents,
// use directory.mkdirs(); here instead.
}
try (OutputStream fileOut = new FileOutputStream(fileName)) {
wb.write(fileOut);
fileOut.close();
wb.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Part 2
I want to access it from the browser, so when I call it will get downloaded.
I know that for the static content, all I need to do is to call to the file, from the browser like that:
http://localhost:8080/documents/myfile.xlsx
After I would be able to do it, all I need is to create link to this url from my client app.
The problem -
Currently if I call to the file as above, it will download only the file which have been there in the compiling stage, but if I am generating a new files after the app is running the content won't be available.
It seems that the content is (as it's called) "static" and cannot be changed after startup.
So my question is
is there is a way to define a folder on the app structure that will be dynamic? I just want to access the new generated file.
BTW I found this answer and others which doing configuration methods, or web services, but I don't want all this. And I have tried some of them, but the result is the same.
FYI I don't bundle my client app with the server app, I run them from different hosts
The problem is to download the file with the dynamic content from a Spring app.
This can be solved with Spring BOOT. Here is the solution as shown in this illustration - when i click Download report, my app generates a dynamic Excel report and its downloaded to the browser:
From a JS, make a get request to a Spring Controller:
function DownloadReport(e){
//Post the values to the controller
window.location="../report" ;
}
Here is the Spring Controller GET Method with /report:
#RequestMapping(value = ["/report"], method = [RequestMethod.GET])
#ResponseBody
fun report(request: HttpServletRequest, response: HttpServletResponse) {
// Call exportExcel to generate an EXCEL doc with data using jxl.Workbook
val excelData = excel.exportExcel(myList)
try {
// Download the report.
val reportName = "ExcelReport.xls"
response.contentType = "application/vnd.ms-excel"
response.setHeader("Content-disposition", "attachment; filename=$reportName")
org.apache.commons.io.IOUtils.copy(excelData, response.outputStream)
response.flushBuffer()
} catch (e: Exception) {
e.printStackTrace()
}
}
This code is implemented in Kotlin - but you can implement it as easily in Java too.

Saving a JSON file to internal storage - Android

I've been trying to save a JSON (currently, it's simply a generic file) to my device's internal storage. I've looked at tons of examples that look exactly like what I've written, but I can never find the file on my device.
Code to save file
public void saveJSONStringToFile(String json) {
FileOutputStream outfile = null;
String filename = "json_test.json";
try {
outfile = openFileOutput(filename, this.MODE_PRIVATE);
outfile.write(json.getBytes());
outfile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I know that it's not working because I've also implemented code to retrieve that file and the app just hangs when I try that, implying that it's looking for something that isn't there.

GeoTools WebMapServer GetMapRequest issue

I'm using GeoTools 12.2 for developing java class library project.
Firstly, I'm working on GeoTools WMS module with this guide.
The point that I was failed is doing get map request so that I could get capabilities document and layers etc.
My wms url http://sampleserver1.arcgisonline.com/ArcGIS/services/Specialty/ESRI_StatesCitiesRivers_USA/MapServer/WMSServer
It contains 3 layers (States,Rivers,Cities)
I'm using structure to get map operation like below.
GetMapRequest getMapRequest = wms.createGetMapRequest();//wms is my WebMapServer object
getMapRequest.addLayer(tempLayer);//tempLayer contains states layer
GetMapResponse response = (GetMapResponse) wms.issueRequest(getMapRequest);
BufferedImage image = ImageIO.read(response.getInputStream());
I also tried other methods in guide to do GetMapRequest but I can't succeed, always getting NullPointerException to BufferedImage object.
What is your suggestions? Thanks in advance.
You need to set some more parameters for your request, the WMS getMapResponse doesn't provide any defaults for several of them (as they are unique to your request/map). So you need at least the following:
private BufferedImage getLayer(Layer l) {
GetMapRequest getMapRequest = wms.createGetMapRequest();
getMapRequest.addLayer(l);
getMapRequest.setBBox(l.getEnvelope(DefaultGeographicCRS.WGS84));
getMapRequest.setDimensions(200, 400);
getMapRequest.setFormat("image/png");
getMapRequest.setSRS("CRS:84");
System.out.println(getMapRequest.getFinalURL());
try {
GetMapResponse response = wms.issueRequest(getMapRequest);
BufferedImage image = ImageIO.read(response.getInputStream());
return image;
} catch (ServiceException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
In general to avoid getting an empty image you can do some error checking on the response:
if (response.getContentType().equalsIgnoreCase("image/png")) {
BufferedImage image = ImageIO.read(response.getInputStream());
return image;
} else {
StringWriter writer = new StringWriter();
IOUtils.copy(response.getInputStream(), writer);
String error = writer.toString();
System.out.println(error);
return null;
}
which will give you an XML encoded error to tell you what went wrong:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<ServiceExceptionReport version="1.3.0"
xmlns="http://www.opengis.net/ogc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.opengis.net/ogc http://schemas.opengis.net/wms/1.3.0/exceptions_1_3_0.xsd">
<ServiceException code="InvalidFormat">
Parameter 'bbox' can not be empty.
</ServiceException>
</ServiceExceptionReport>

Android - Unhandled java.net.MalformedURLException

I'm getting a MalformedURLException some code in my Android Studio project. My aim is to get and display an image from a web page, and the URL seems to be fine, but it's giving me this error.
I have already put the code in a try,catch, but that is still giving me the error.
Here is the code to grab the image and display it:
try
{
url = new URL(items.get(position).getLink());
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
}
catch (IOException e)
{
throw new RuntimeException("Url Exception" + e);
}
holder.itemTitle.setText(items.get(position).getTitle());;
holder.itemHolder.setBackgroundDrawable(new BitmapDrawable(bmp));
items.get(position).getLink() is meant to get the link that is being displayed in a ListView, but even something like URL url = new URL("https://www.google.com") doesn't work.
Thanks.
your url is formatted without the protocol at the beginning try
url = new URL("http://"+items.get(position).getLink());
sometimes the url string may have special characters, in which case you need to encode it properly please see this.
And also, the url you posted in the comment is not an image.
it is exception beacuse of url class
add antoher catch like
catch (MalformedURLException e) {
e.printStackTrace();
}
Just click alt+enter and then import try catch section... this helped me...

Categories