How do I reorient images when storing on S3? - java

I'm storing images on S3 for use in emails. When I view the image in an email, some of the images are rotated. I'm uploading using the AmazonS3Client, and uploading images using MultipartFormData in a Play2 app like this:
Http.MultipartFormData body = request().body().asMultipartFormData();
String[] pics = new String[]{"picture1", "picture2", "picture3"};
String[] fileNames = new String[3];
for(int i = 0; i < pics.length; i++) {
Http.MultipartFormData.FilePart picture = body.getFile(pics[i]);
if (picture != null) {
String fileName = picture.getFilename();
play.Logger.info("fileName: " + fileName);
File file = picture.getFile();
String existingBucketName = "yadayadayada";
String keyName = UUID.randomUUID().toString();
PutObjectRequest putObjectRequest = new PutObjectRequest(existingBucketName, keyName + "-" + fileName, file);
putObjectRequest.withCannedAcl(CannedAccessControlList.PublicRead); // public for all
s3Client.putObject(putObjectRequest);
fileNames[i] = "https://s3.amazonaws.com/yadayadayada/" + keyName + "-" + fileName;
}
}

Related

How download an installed app with nanohttpd

Hello i want to make a http server with nanohttpd that shows installed apps, and convert them to apk and download. I can list but how can i download the app i select
List<ApplicationInfo> packages = packageManager.getInstalledApplications(PackageManager.GET_META_DATA;
for (ApplicationInfo packageInfo : packages) {
String name = String.valueOf(packageManager.getApplicationLabel(packageInfo));
if (name.isEmpty()) {
name = packageInfo.packageName;
}
Drawable icon = packageManager.getApplicationIcon(packageInfo);
String apkPath = packageInfo.sourceDir;
apps.add(new App(name, apkPath, icon, packageInfo.packageName));
}
if (method.equals(Method.GET)) {
for (App file : apps) {
answer += "<a href=\"" + file.getAppName()
+ "\" alt = \"\">" + file.getAppName()
+ "</a><br>";
}
Ok, I basicly take the url after list the apps and check which appname equal to url after that i start to download it like that
if (method.equals(Method.GET)) {
if (a) {
answer = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; " +
"charset=utf-8\"><title> HTTP File Browser</title>";
for (App file : appShare) {
answer += "<a href=\"" + file.getAppName()
+ "\" alt = \"\">" + file.getAppName()
+ "</a><br>";
}
answer += "</head></html>";
if(blabla.equals(header.get("referer"))){
a=false;
}
} else {
for (int i = 0; i < appShare.size(); i++) {
if (appShare.get(i).getAppName().equals(appnames))
arrayC = i;
}
answer = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; " +
"charset=utf-8\"><title> Download " + appShare.get(arrayC).getAppName() + "</title>";
// serve file download
InputStream inputStream;
Response response = null;
if (mStatusUpdateListener != null) {
mStatusUpdateListener.onDownloadingFile(
new File(appShare.get(arrayC).getApkPath()), false);
}
try {
inputStream = new FileInputStream(
new File(appShare.get(arrayC).getApkPath()));
response = new DownloadResponse(
new File(appShare.get(arrayC).getApkPath()), inputStream);
} catch (Exception e) {
e.printStackTrace();
} response.addHeader(
"Content-Disposition", "attachment; filename=" + appShare.get(arrayC).getAppName()+".apk");
return response;
}

Image File Compression before download into path using Java

I am Downloading Image from Gmail, what the problem here is , Image file upto 6MB, So it will take some more time in order to complete its download process. So my Question is Shall i compress image while downloading(ie Before save into path)? I have looked some Image compression examples in java,but all are taking image from one path then compress and finally stores that compressed image into some other folder.
If you want code for download attachment from gmail, Please click here . Could you please help me out to find the solution?
/*Downloading EmailAttachment into localfolder*/
public void downloadEmailAttachments(String protocol, String host, String port, String userName, String password,
String tempDirectory,String saveDirectory,String MessageID,String HeaderID,String emailDate,String emailSubject, MessageContext context) {
logger.info("===Inside downloadEmailAttachments Process====");
Properties properties = getServerProperties(protocol, host, port);
Session session = Session.getDefaultInstance(properties);
int status = 0;
try {
Store store = session.getStore(protocol);
store.connect(userName, password);
Folder folderInbox = store.getFolder("INBOX");
folderInbox.open(Folder.READ_ONLY);
logger.info("No of Unread Messages : " + folderInbox.getUnreadMessageCount());
/* create a search term for all "unseen" messages*/
Flags seen = new Flags(Flags.Flag.SEEN);
FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
SearchTerm searchTerm = new AndTerm(new MessageIDTerm(HeaderID), new SubjectTerm(emailSubject));
Message[] arrayMessages = folderInbox.search(searchTerm);
if(arrayMessages != null && arrayMessages.length > 0){
Message message = arrayMessages[0];
Address[] fromAddress = message.getFrom();
String msgId=mimeMessage.getMessageID();*/
String from = fromAddress[0].toString();
String subject = message.getSubject();
String sentDate = message.getSentDate().toString();
String contentType = message.getContentType();
String messageContent = "";
String modifiedsubject=subject.toUpperCase().replaceAll("\\s+", "");
String attachmentname = "";
if(modifiedsubject.contains("SELLMYCAR")){
if (contentType.contains("multipart")) {
// content may contain attachments
Multipart multiPart = (Multipart) message.getContent();
int numberOfParts = multiPart.getCount();
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
// this part is attachment
//String fileName = part.getFileName();
// part.setFileName(ESBMessageID+":"+new Date());
// String fileName = part.getFileName()+":"+ESBMessageID+":"+new Date();
String fileName = part.getFileName();
fileName=fileName.substring(0, fileName.lastIndexOf(".")).concat(".jpg");
System.out.println("Modified FileName:" + fileName);
attachmentname = fileName;
/*part.saveFile(saveDirectory + File.separator + fileName);*/
part.saveFile(tempDirectory + File.separator + fileName);
logger.info("Files are downloaded into "+ tempDirectory+" successfully");
if (attachmentname.length() > 1) {
attachmentname = attachmentname.substring(0, attachmentname.length());
}
/*FileMove Process*/
moveFile(tempDirectory,fileName,saveDirectory,MessageID,context);
} else {
// this part may be the message content
messageContent = part.getContent().toString();
}
}
// print out details of each message
logger.info("Message # :");
logger.info("\t From: " + from);
//logger.info("\t UserName: " + name);
logger.info("\t Subject: " + subject);
logger.info("\t Sent Date: " + sentDate);
//logger.info("\t UserMailID: " + email);
logger.info("\t Attachments: " + attachmentname);
logger.info("\t LocalDownloadpath: " + saveDirectory);
} else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
Object content = message.getContent();
if (content != null) {
messageContent = content.toString();
}
}
}
}
// disconnect
folderInbox.close(false);
store.close();
} catch (MessagingException ex) {
logger.info("Could not connect to the message store");
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}````

How can I use the FileProvider to access Download folder?

I made an App that creates a *.csv file inside a folder (made by the same app) and at the same time is inside the Android's Download Folder.
The file can be shared with a ShareIntent, the problem is when the app runs in Android Oreo and the user tries to create the *.csv file, the apps crashes, the thrown exception is:
android.os.FileUriExposedException:
at android.os.StrictMode.onFileUriExposed (StrictMode.java:1958)
at android.net.Uri.checkFileUriExposed (Uri.java:2348)
at android.content.ClipData.prepareToLeaveProcess (ClipData.java:941)
at android.content.Intent.prepareToLeaveProcess (Intent.java:9735)
at android.content.Intent.prepareToLeaveProcess (Intent.java:9741)
at android.content.Intent.prepareToLeaveProcess (Intent.java:9720)
at android.app.Instrumentation.execStartActivity (Instrumentation.java:1795)
at android.app.Activity.startActivityForResult (Activity.java:4495)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult (BaseFragmentActivityJB.java:50)
at android.support.v4.app.FragmentActivity.startActivityForResult (FragmentActivity.java:79)
at android.app.Activity.startActivityForResult (Activity.java:4453)
at android.support.v4.app.FragmentActivity.startActivityForResult (FragmentActivity.java:859)
at android.app.Activity.startActivity (Activity.java:4814)
at android.app.Activity.startActivity (Activity.java:4782)
at com.bpl.spart.bloodpressurelogbook.MainActivity$createReportTask.onPostExecute (MainActivity.java:517)
at com.bpl.spart.bloodpressurelogbook.MainActivity$createReportTask.onPostExecute (MainActivity.java:420)
I know that I should use FileProvider to create Uri's, in API level > 24,but how Can I use the FileProvider to give access from a file inside the Downloads folder?
This is my current code:
Intent ShareIntent = new Intent(android.content.Intent.ACTION_SEND);
ShareIntent.setType("text/csv");
ShareIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {getString(R.string.reporteTomasDePresion)});
ShareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, nombreReporte);
ShareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
startActivity(Intent.createChooser(ShareIntent, getString(R.string.compartirReporte)));
Where "f" is the reference to the .csv file.
public File getDocumentsStorageDir(String directorio){
File file = new File(getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS),directorio);
if(!file.mkdir()){
Log.e("StatusArchivo","Directorio no creado");
}
return file;
}
File file = getDocumentsStorageDir(REPORTDIR);
Calendar cal = Calendar.getInstance();
//sdf = new SimpleDateFormat("dd-MM-yyyy-HH-mm");
nombreReporte = "BPReport"+sdf.format(cal.getTime())+".csv";
f = new File(file.getAbsolutePath(),nombreReporte);
String csvFIle = "";
String sistolicaS;
String diastolicaS;
String pulsoS;
String posicionS;
String extremidadS;
String notaS;
String fechaS;
if(params[0].getCount() > 0 ) {
try {
OutputStreamWriter fout = new OutputStreamWriter(new FileOutputStream(f), StandardCharsets.ISO_8859_1);
String nombre = getString(R.string.Nombre);
String nombreDeUsuario = sharedPref.getString("nombreDelUsuario","");
String edad = getString(R.string.Edad);
String edadUsuario = sharedPref.getString("edadDelUsuario","");
String peso = getString(R.string.Peso);
String pesoUsuario = sharedPref.getString("pesoDelUsuario","");
String UnidadDePeso = sharedPref.getString("unidadPeso",getString(R.string.kilos));
String enfermedades = getString(R.string.Enfermedad);
String enfermedadesUsuario = sharedPref.getString("enfermedadesDelUsuario","");
String linea1 = nombre+": ," + nombreDeUsuario + "\n";
fout.write(linea1);
String linea2 = edad+": ," + edadUsuario + "\n";
fout.write(linea2);
String linea3 = peso+": ," + pesoUsuario + UnidadDePeso + "\n";
fout.write(linea3);
String linea4 = enfermedades+": ," + enfermedadesUsuario + "\n";
fout.write(linea4);
String tituloColumnas = getString(R.string.presionsistolica) + "," + getString(R.string.presiondiastolica) + "," + getString(R.string.pulsotil) + "," + getString(R.string.posiciontil) + "," + getString(R.string.extremidadtil) + "," + getString(R.string.notatil) + "," + getString(R.string.fechatil) + "\n";
fout.write(tituloColumnas);
params[0].moveToFirst();
if (params[0].moveToFirst()) {
for (int j = 0; j < params[0].getCount(); j++) {
sistolicaS = params[0].getString(params[0].getColumnIndex(Contrato.Columnas.SISTOLICA));
diastolicaS = params[0].getString(params[0].getColumnIndex(Contrato.Columnas.DIASTOLICA));
pulsoS = params[0].getString(params[0].getColumnIndex(Contrato.Columnas.PULSO));
posicionS = params[0].getString(params[0].getColumnIndex(Contrato.Columnas.POSICION));
extremidadS = params[0].getString(params[0].getColumnIndex(Contrato.Columnas.EXTREMIDAD));
notaS = params[0].getString(params[0].getColumnIndex(Contrato.Columnas.NOTA));
fechaS = params[0].getString(params[0].getColumnIndex(Contrato.Columnas.FECHA));
Log.v("CSV1", csvFIle);
csvFIle = "\"" + sistolicaS + "\",\"" + diastolicaS + "\",\"" + pulsoS + "\",\"" + posicionS + "\",\"" + extremidadS + "\",\"" + notaS + "\",\"" + fechaS + "\"\n";
Log.v("CSV2", csvFIle);
fout.write(csvFIle);
params[0].moveToNext();
}
}
fout.close();
c.close();
I found the answer by my self, In my paths.xml file I added:
<?xml version="1.0" encoding="utf-8"?>
<paths
xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="Descarga"
path="Download/"/>
<files-path name="nombre"
path="reportes" />
</paths>
And in the Java:
I changed:
ShareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
startActivity(Intent.createChooser(ShareIntent,getString(R.string.compartirReporte)));
For:
Uri fileUri = FileProvider.getUriForFile(MainActivity.this,"com.bpl.spart.bloodpressurelogbook.fileprovider",f);
ShareIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
startActivity(Intent.createChooser(ShareIntent, getString(R.string.compartirReporte)));
Also the FileUriExposedException problem in Android Oreo is gone now.

Trying to copy file and getting 'file does not exist' error

I am trying to copy files from 1 directory to another after re-naming them but keep getting the error:
Exception in thread "main" java.nio.file.NoSuchFileException: C:\Users\talain\Desktop\marketingOriginal\FX Rates\FY17\Q11\Week_12___February_12_2016.xls -> C:\Users\talain\Desktop\fakeOnedrive\FX Rates\FY17\Q11\0
My code:
public class shortenFilenameClass
{
static String absolutePathLocal = "C:\\Users\\talain\\Desktop\\marketingOriginal".replace('\\', '/'); //path to original files
static String absolutePathOnedrive= "C:\\Users\\talain\\Desktop\\fakeOnedrive".replace('\\', '/'); //path to onedrive
public static void main(String[] args) throws IOException
{
System.out.println(absolutePathLocal.length());
File local = new File(absolutePathLocal);
File onedrive = new File(absolutePathOnedrive);
int fileCount = 0;
File[] filesInDir = local.listFiles();
manipulateFiles(filesInDir, fileCount);
}
public static void manipulateFiles(File[] filesInDirPassed, int fileCount) throws IOException
{
for(int i = 0; i < filesInDirPassed.length; i++)
{
File currentFile = filesInDirPassed[i];
if(currentFile.isDirectory())
{
String local = currentFile.getAbsolutePath();
//String onedrive = current
manipulateFiles(currentFile.listFiles(), fileCount);
}
String name = currentFile.getName();
System.out.println("old filename: " + name);
String newName = String.valueOf(fileCount);
fileCount++;
File oldPath = new File(currentFile.getAbsolutePath());
System.out.println("oldPath: " + oldPath);
//currentFile.renameTo(new File(oldPath.toString()));
System.out.println("currentFile: " + currentFile);
String pathExtension = new String(currentFile.getAbsolutePath().substring(42));
pathExtension = pathExtension.replaceAll(name, newName);
File newPath = new File(absolutePathOnedrive + "/" + pathExtension);
System.out.println("newPath: " + newPath);
copyFileUsingJava7Files(oldPath, newPath);
File finalPath = new File(absolutePathOnedrive + "" + name);
//newPath.renameTo(new File(finalPath.toString()));
//copyFileUsingJava7Files(newPath, finalPath);
System.out.println("renamed: " + name + "to: " + newName + ", copied to one drive, and changed back to original name");
}
}
private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
}
Java is being told that C:\Users\talain\Desktop\marketingOriginal\FX Rates\FY17\Q11\Week_12___February_12_2016.xls -> C:\Users\talain\Desktop\fakeOnedrive\FX Rates\FY17\Q11\0 is a file, which isn't true. Check the line where the error originates from and see if you are using a lambda expression anywhere.

java- resize image on ftp by thumbnailator library

I am uploading image from url on ftp by this code.
Image uploaded successful but when i try to resize uploaded image get error as the follows.
String imageUrl = "http://www.totaldesign.ir/wp-content/uploads/2014/11/hamayesh.jpg";
FTPClient ftpClient = new FTPClient();
ftpClient.connect(ftp_server, ftp_port);
ftpClient.login(ftp_user, ftp_pass);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
// APPROACH #2: uploads second file using an OutputStream
URL url = new URL(imageUrl);
//**************select new name for image***********/
//get file extention
File file = new File(imageUrl);
String ext = getFileExtension(file);
//get file name from url
String fileName = imageUrl.substring(imageUrl.lastIndexOf('/') + 1, imageUrl.length());
String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));
//create new image name for upload
String img_name = "simjin.com_" + fileNameWithoutExtn;
//get current year time for image upload dir
Date date = new Date();
DateFormat yeae = new SimpleDateFormat("yyyy");
String current_year = yeae.format(date);
//create dirs if not exist
ftpClient.changeWorkingDirectory(current_year);
int dirCode = ftpClient.getReplyCode();
if (dirCode == 550) {
//create dir
ftpClient.makeDirectory(current_year);
System.out.println("created folder: " + current_year);
}
//get current month time for image upload dir
DateFormat month = new SimpleDateFormat("MM");
String current_month = month.format(date);
//create dirs if not exist
ftpClient.changeWorkingDirectory("/" + current_year + "/" + current_month);
dirCode = ftpClient.getReplyCode();
if (dirCode == 550) {
//create dir
ftpClient.makeDirectory("/" + current_year + "/" + current_month);
System.out.println("created folder: " + "/" + current_year + "/" + current_month);
}
String uploadDir = "/" + current_year + "/" + current_month;
//rename image file if exist
boolean exists;
String filePath = uploadDir + "/" + img_name + "." + ext;
exists = checkFileExists(filePath);
System.out.println("old file path=> " + exists);
//Rename file if exist
int i = 0;
while (exists) {
i++;
img_name = "simjin.com_" + fileNameWithoutExtn + i;
filePath = uploadDir + "/" + img_name + "." + ext;
exists = checkFileExists(filePath);
//break loop if file dont exist
if (!exists) {
break;
}
}
System.out.println("new file path=> " + filePath);
//set image name in array for return
result[0] = img_name;
//*************end select new name for image**********/
System.out.println("ftpClinet Replay Code=> " + ftpClient.getStatus());
//Start uploading second file
InputStream inputStream = new BufferedInputStream(url.openStream());
OutputStream outputStream = ftpClient.storeFileStream(filePath);
System.out.println("outputStream Status=> " + outputStream);
byte[] bytesIn = new byte[10240];
int read = 0;
while ((read = inputStream.read(bytesIn)) != -1) {
outputStream.write(bytesIn, 0, read);
}
inputStream.close();
outputStream.close();
boolean completed = ftpClient.completePendingCommand();
after success upload. I want to resize image by thumbnailator:
if (completed) {
System.out.println("The file is uploaded successfully.");
String new_img_name = uploadDir + "/" + img_name + "-150x150" + "." + ext;
OutputStream os = ftpClient.storeFileStream(filePath);
Thumbnails.of(image_url).size(150, 150).toOutputStream(os);
}
in this section get this error:
OutputStream cannot be null
Where is my wrong? And how to fix it?

Categories