How to get content from the gmail content provider - java

I have to retrieve the file path of the content from gmail app.
I get content uri similar to:
content://gmail-ls/messages/mymailid%40gmail.com/4/attachments/0.1/BEST/false
I tried queried for the contents but I get only two columns the title and the size. I want to get the file path.
Kindly help regarding this.

I think you cannot retrieve the file path directly, as the attachment is stored on Google servers. You can, however, access the file data using ContentResolver and InputStream, and copy the attachment's data to your storage.
Inspired by CarvingCode blog, I use this snippet:
if (intent.getScheme().compareTo("content")==0)
{
try
{
InputStream attachment = getContentResolver().openInputStream(data);
if (attachment == null)
Log.e("onCreate", "cannot access mail attachment");
else
{
FileOutputStream tmp = new FileOutputStream("/mnt/sdcard/attachment.pdf");
byte []buffer = new byte[1024];
while (attachment.read(buffer) > 0)
tmp.write(buffer);
tmp.close();
attachment.close();
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Related

how to confirm a file is a picture file with java language?

I want to know how can I use java to confirm a file is a picture file.
I have tried the following code:
public static void main(String[] args) {
// get image format in a file
File file = new File("C:/Users/dell、/Desktop/4.xlsx");
// create an image input stream from the specified fileDD
ImageInputStream iis = null;
try {
iis = ImageIO.createImageInputStream(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// get all currently registered readers that recognize the image format
Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {
System.out.println("Not a picture file");
throw new RuntimeException("No readers found! Unable to read the uploaded file");
}
// get the first reader
ImageReader reader = iter.next();
try {
System.out.println("Format: " + reader.getFormatName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// close stream
if (iis != null){
try {
iis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
iis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
But it doesn't work perfectly! It shows an exception once the file is not a picture file, so I want to find a better way.
There are too many image extensions. Maybe the best way to validate if a file is an image, is using Regular Expressions. Something like this...
([^\s]+(\.(?i)(jpg|png|gif|bmp|MORE|IMAGE|EXTENSIONS))$)
Here is a complete example of the implementation.
Use ImageIO#read.
public static boolean isPictureFile(File file){
try{
return ImageIO.read(file) != null;
}catch(Exception ex){
return false;
}
}
Basically, the method ImageIO.read(File) will return a BufferedImage object when it successfully read the image file, a null otherwise. All we have to do is to let ImageIO read the file and check if it returns a null or not, and if there it throws an exception for whatever reason, we can safely assume the file is not a picture file.

FTPClient showing empty folder when it has files

I am using Apache Commons net FTPClient to login and read files from an FTP Server. I manage to login and I can see it logs in successfully, because it shows the working directory path in the header string. However it shows no files when I use listFiles(). (I have also tried using listDirectories() and listNames() but with no success)
Below is a snippet:
try {
client.connect(ftpHost);
} /*catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/ catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
String header ="";
InputStream stream=null;
BufferedReader reader=null;
try{
client.login(ftpUser, ftpPass);
client.changeWorkingDirectory(targetWorkingDir);
header = client.printWorkingDirectory();
//client.setFileType(FTP.BINARY_FILE_TYPE);
for(int i=0; i<client.listFiles().length;i++){
header+=client.listFiles()[i].getName() +"\n";
}
}
catch (IOException ex){
ex.printStackTrace();
header="ERROR 1: " + ex.getMessage();
for(int i=0;i<ex.getStackTrace().length;i++){
header += "\n" + ex.getStackTrace()[i];
}
}
catch(NullPointerException e){
header = "ERROR 2: "+ e.getMessage()+"\n";
for(int i=0;i<e.getStackTrace().length;i++){
header+= e.getStackTrace()[i] + "\n";
}
}
finally{
if(reader!=null){
try{reader.close();}catch(IOException e){e.printStackTrace();}
try{stream.close();}catch(IOException e){e.printStackTrace();}
}
}
I have also tried using something like this to read a file:
try {
stream = ftpClient.retrieveFileStream("klasa.csv");
reader = new BufferedReader(new InputStreamReader(stream));
header = reader.readLine();
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore){}
}
In both cases I'm pretty sure I'm at the right directory, and I make sure that my file is there via FileZilla, but the client can't seem to read any file.
Try to avoid calling listFiles() in the loop. Every call will perform the entire FTP LIST command sequence, so eventually, you will add unnecessary traffic to every call.
You can try to simplify your program first like this:
private static void ftpTest() {
FTPClient f = new FTPClient();
try {
f.connect("{UOUR FTP SERVER}");
f.login("{USER}", "{PASSWORD}");
FTPFile[] files = f.listFiles(".");
for (FTPFile fi: files) {
System.out.printf("f%s\n", fi.getName());
}
} catch (IOException e) {
e.printStackTrace();
}
}
If this program will not give you the list of files in the root directory of your server, you can try to compare your FileZilla FTP options (PASSIVE/ACTIVE mode in particular): https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#enterLocalPassiveMode()
If it won't help you can try to sniff the network traffic using WireShark or tcpdump and compare the commands set to the FTP server.

JAVA Android , acces to a file with getRessourceAsStream

i would like to handle a a properties file in my android app. The Properties-File is in the main-Folder, in the folder with the other jar-files. I know, that´s not best.
Code:
InputStream propStream=MainActivity.class.getResourceAsStream("data.properties");
Log.d("propStreamOutput",propStream.toString());
File data = new File(propStream.toString());
Reader reader;
try {
reader = new FileReader(data);
dataProp = new Properties();
dataProp.load( reader );
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
so, the log at line 2 says:
libcore.net.url.JarURLConnectionImpl$JarURLConnectionInputStream#421302e8
in this form logcat calls a System.err :
java.io.FileNotFoundException/libcore.net.url.JarURLConnectionImpl$JarURLConnectionInputStream#42097218: open failed: ENOENT (No such file or directory)
but when I comment like this:
InputStream propStream=MainActivity.class.getResourceAsStream("data.properties");
Log.d("propStreamOutput",propStream.toString());
File data = new File(propStream.toString());
// Reader reader;
// try {
// reader = new FileReader(data);
// dataProp = new Properties();
// dataProp.load( reader );
// } catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
then there is no system.err ! Of course the log call at line 2 says the same.
If you really wanna use the getResourceAsStream() then you have to put the file on the "src" folder, together with your .java files.
This is usually the way for standard Java applications, but on Android the most usual way to perform such things is to put the file in the 'assets' folder, via AssetsManager, which is accessible from your Activity or any Context. like shown below:
InputStream is = null;
try {
is = context.getAssets().open("data.properties");
} catch (final IOException e) {
e.printStackTrace();
} finally {
closeStreamGracefully(is);
}
getRessourceAsStream return an InputStream. When you call toString on this it will return a string representation of the object. Then when you create your data file and try to read it will try to open a file like #sdqzeffdfsf. If you whant to read the properties from this file use Properties
Properties properties = new Properties();
properties.load(propStream);
This is for standard java. However in android you usualy use AssetManager

File Upload with spring data - gridfs

Hi i am trying to upload a file using spring data. When i try to upload file, i get an exception.
My code for file upload is
try {
File file = new File(this.TEMPORARY_FILES_DIRECTORY, Calendar.getInstance().getTimeInMillis() + "_" + fileNameUnderscored);
writeByteArrayToFile(file, form.getFile().getBytes());
FileInputStream inputStream = new FileInputStream(file);
GridFSFile gridFSFile = gridFsTemplate.store(inputStream, "test.png");
PropertyImage img = new PropertyImage();
img.setPropertyUid(gridFSFile.getFilename());
imagesRepository.save(img);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
where TEMPORARY_FILES_DIRECTORY = new File("/home/temp/");
the exception i am getting is
java.io.IOException: File '/home/temp/1392807425028_file' could not be created
on debugging FileUtils class
if (parent.mkdirs() == false) {
throw new IOException("File '" + file + "' could not be created");
}
parent.mkdirs() is false.
Can anyone kindly tell me what is wrong with this code.
Are you sure it's /home/temp and not /home/username/temp? You can't create directories outside your home directory. Try something like Systen.getProperty("user.home") + "/temp", if you'd like to store the files inside your home directory. Anyway, why didn't you choose /tmp to be your temporary directory?

Android: Dowloaded files got deleted when the app restarts

I download audio files from server using
try {
// URL url = new URL("http://commonsware.com/misc/test2.3gp");
URL url = new URL("http://192.168.0.2/supplications/"+fileName);
//URL url = new URL("http://www.msoftech.com/supplications/android/"+fileName);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
Log.v("log_tag", "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1)
{
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (IOException e) {
Log.d("log_tag", "Error: " + e);
}
Log.v("log_tag", "Check: " +cd2);
Here PATH = "/data/data/packagename/sounds/filename
It works fine, audio file downloaded and played successfully, but my problem is when I click the home button and then restart the app means the folder with the downloaded audio was not found, ie, when exit the app means all the downloaded audios were deleted automatically. It throws the exception file not found.
For playing the downloaded file I used the code as below,
public void audioPlayer(String path, String fileName) throw FileNotFoundException
{
//set up MediaPlayer
FileInputStream fileInputStream = new FileInputStream(PATH+"/"+fileName);
//String command = "chmod 666 " + recordFile.toString();
try {
mp.setDataSource(fileInputStream.getFD());
// mp.setDataSource(path+"/"+filename.mp3);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
whats the problem with it what I have to do for saving the audio file permenantly.
There is nothing problem in your code it is a file permission issue.
When you download file into internal file system under application package a security is assigned to it like "-rw------" this means your file is accessible for the same application only.As android is on Linux based so every file have some permission.
Your file would be there but not accessible to other application like media player etc, so these application throws error like file not found.(you can check though DDMS tool).
Just change the file path to external drive.
Accept the answer if it is helpful.

Categories

Resources