Convert Base64 to zip file (password protected) in android - android

I have a base64 string which when decoded online using this website gives a zip file. When the zip file is downloaded it is password protected.
In my case, I know the password but I am not able to convert base64 to a zip file and also open it and read it in Android.
I used this answer on stack overflow but I am getting an error
Error: "java.util.zip.ZipException: Not in GZIP format"
I need a solution where I have the base64 String that it should decode into a zip file and then read the content of this zip file using the given password which has XML data.
Here is the code I have used so far:
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
public class GzipUtil {
public static void unzip() throws Base64DecodingException {
String encoded = "PUT BASE 64ENCODED GZIPPED STRING HERE";
byte[] compressed = Base64.decode(encoded);
String data = new String(compressed);
//System.out.println(data);AAAA";
if ((compressed == null) || (compressed.length == 0)) {
throw new IllegalArgumentException("Cannot unzip null or empty bytes");
}
if (!isZipped(compressed)) {
System.out.println(compressed);
}
try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(compressed)) {
try (GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream)) {
try (InputStreamReader inputStreamReader =
new InputStreamReader(gzipInputStream, StandardCharsets.UTF_8)) {
try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
StringBuilder output = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
output.append(line);
System.out.println(output.toString());
}
}
}
}
} catch (IOException e) {
throw new RuntimeException("Failed to unzip content", e);
}
}
public static boolean isZipped(final byte[] compressed) {
return (compressed[0] == (byte) (GZIPInputStream.GZIP_MAGIC))
&& (compressed[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8));
}
}
Please help!

Related

Awkward result found on reading CSV file

I want to read CSV file. The problem is when i print a value of 0 or any other index the awkward result shown as you can see on snapshot. Snapshot attached.
Read value from this code:
InputStream inputStream = getResources().openRawResource(R.raw.stats);
FileReader csvFile = new FileReader(inputStream);
List<String[]> scoreList = csvFile.read();
for(String[] scoreData:scoreList ) {
Toast.makeText(this, scoreData[1], Toast.LENGTH_SHORT).show();
}
FileReader class:
package com.example.zohaib.ultimatesmsblocker;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class FileReader {
InputStream inputStream;
public FileReader(InputStream inputStream){
this.inputStream = inputStream;
}
public List<String[]> read(){
List<String[]> resultList = new ArrayList();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String csvLine;
while ((csvLine = reader.readLine()) != null) {
String[] row = csvLine.split(",");
resultList.add(row);
}
}
catch (IOException ex) {
throw new RuntimeException("Error in reading CSV file: "+ex);
}
finally {
try {
inputStream.close();
}
catch (IOException e) {
throw new RuntimeException("Error while closing input stream: "+e);
}
}
return resultList;
}
}
CSV file:
The file you're trying to load is not a CSV, but a XLSX.
Not every Excel file is a CSV file. You need to export it to a CSV using Excel.
Excel's .xlsx files are actually XML files in certain format packed in ZIP. The PK you see as the first two letters represent the ZIP header.

Android File Copy Confirm for Completeness

In my scenario, I'm using an external read only db zipped in Assets and extracting/copying to internal storage on initial run.
The issue happens when user's device does not have sufficient memory on disk to complete the copy.
I do check for available space prior, however Android OS itself will use virtual memory/page file when low on Ram so # of free MB's is not constant.
I would like to find a way to check if file itself is complete, any way to accomplish this?
Checking that the files are consistent is always done by checking the MD5 hash of the two file if they match each other.
You can use this class from the CyanogenMod ROM repository on github.This should work pretty well https://github.com/CyanogenMod/android_packages_apps_CMUpdater/blob/cm-10.2/src/com/cyanogenmod/updater/utils/MD5.java
/*
* Copyright (C) 2012 The CyanogenMod Project
*
* * Licensed under the GNU GPLv2 license
*
* The text of the license can be found in the LICENSE file
* or at https://www.gnu.org/licenses/gpl-2.0.txt
*/
package com.cyanogenmod.updater.utils;
import android.text.TextUtils;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5 {
private static final String TAG = "MD5";
public static boolean checkMD5(String md5, File updateFile) {
if (TextUtils.isEmpty(md5) || updateFile == null) {
Log.e(TAG, "MD5 string empty or updateFile null");
return false;
}
String calculatedDigest = calculateMD5(updateFile);
if (calculatedDigest == null) {
Log.e(TAG, "calculatedDigest null");
return false;
}
Log.v(TAG, "Calculated digest: " + calculatedDigest);
Log.v(TAG, "Provided digest: " + md5);
return calculatedDigest.equalsIgnoreCase(md5);
}
public static String calculateMD5(File updateFile) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "Exception while getting digest", e);
return null;
}
InputStream is;
try {
is = new FileInputStream(updateFile);
} catch (FileNotFoundException e) {
Log.e(TAG, "Exception while getting FileInputStream", e);
return null;
}
byte[] buffer = new byte[8192];
int read;
try {
while ((read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read);
}
byte[] md5sum = digest.digest();
BigInteger bigInt = new BigInteger(1, md5sum);
String output = bigInt.toString(16);
// Fill to 32 chars
output = String.format("%32s", output).replace(' ', '0');
return output;
} catch (IOException e) {
throw new RuntimeException("Unable to process file for MD5", e);
} finally {
try {
is.close();
} catch (IOException e) {
Log.e(TAG, "Exception on closing MD5 input stream", e);
}
}
}
}
You should precalculate your md5 hash of the file and just check if it matches with the new transfered file.

Importing Text File in Android Application?

I've been getting the following error when I attempt to run an android application that inputs data from a text file.
"java.io.fileNotFoundException: /File.txt: open failed:ENOENT (No such file or directory)"
The file in question is in the Eclipse project folder.
I also tried putting it in the assets folder as well as several others.
Here is the code in question:
File file = new File("File.txt");
TestOutput = new ArrayList<String>();
String x = "";
try
{
Scanner scanner = new Scanner(file);
while (sc.hasNextLine())
{
x = sc.nextLine();
TestOutput.add(x);
}
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
So far I have attempted to use a wrapper class to no avail, the code of which is below:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class FileGet
{
ArrayList<String> TestOutput = new ArrayList<String>();
public FileGet() {
}
public ArrayList<String> getFile() {
File file = new File("TestOutput.txt");
TestOutput = new ArrayList<String>();
try
{
Scanner scanner = new Scanner(file);
String x = "";
while (scanner.hasNextLine())
{
x = scanner.nextLine();
TestOutput.add(x);
}
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
return TestOutput;
}
}
That code works fine outside of the android application. Any advice/responses would be greatly appreciated.
Try this, the string named "line" is the string where all the TextFile is read.
Put the .txt file under /resources/raw folder.
InputStream is = getResources().openRawResource(R.raw.name_of_file);
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line = null;
try {
while ((line = r.readLine()) != null)
total.append(line);
} catch (IOException e) {
e.printStackTrace();
}
line = total.toString();

Can not write more than 1 line into file

I am trying to write to a text file a list of names. It is written one line at a time and I have a class for Writing to File and Reading from it.
Here is the class:
package com.example.mobiledayoff;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import android.content.Context;
public class userListIO {
Context fileContext;
public userListIO(Context fileContext){
this.fileContext=fileContext;
}
public void writeItems(String fileName, String name){
final String ls = System.getProperty("line.separator");
BufferedWriter writer = null;
try{
writer =
new BufferedWriter(new OutputStreamWriter(fileContext.getApplicationContext().openFileOutput(fileName, Context.MODE_PRIVATE)));
writer.write(name + ls);
} catch (Exception e){
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public ArrayList<CharSequence> readItems(String filename){
ArrayList<CharSequence> list = new ArrayList<CharSequence> ();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(fileContext.getApplicationContext().openFileInput(filename)));
String line;
while((line = br.readLine()) != null){
list.add(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return list;
}
}
I use this class to write a line from user input (EditText) to the file. And then I read from file and Display contents of the file in another EditText. Here is how I do it:
public void addUser(View view){
EditText text = new EditText(this);
text = (EditText)findViewById(R.id.add_user_text);
String name = text.getText().toString();
String filename = "userList.txt";
userListIO messenger = new userListIO(this);
messenger.writeItems(filename, name);
text.setText("");
ArrayList<CharSequence> list = messenger.readItems(filename);
EditText editText = (EditText) findViewById(R.id.debug_text);
String info = "";
int count = 0;
for (CharSequence item: list){
info += item.toString();
count++;
}
info += "; there are " + count + " lines";
editText.setText(info);
}
My main problem is that it seems that file gets overwritten each time I write into it and so I always have 1 line. Do you guys know how to fix this? By fix I mean: How to append to the file if it already exists or create one if it doesn't exist.
Also I found out that after I close and reopen an app, the file does not exist. How to create and save a file, so that after closing and reopening I could still use the data stored there?
p.s. Read/Write was taken from here:
The best way to store user input data for later work
Change
new BufferedWriter(new OutputStreamWriter(fileContext.getApplicationContext().openFileOutput(fileName, Context.MODE_PRIVATE)));
to
new BufferedWriter(new OutputStreamWriter(fileContext.getApplicationContext().openFileOutput(fileName, Context.MODE_PRIVATE | Context.MODE_APPEND)));
This will combine the MODE_PRIVATE flag aswell as the MODE_APPEND flag.
P.S. You should get away from opening and closing a stream everytime you write a line. This produces a lot of overhead and rather should you try to keep the stream opened until all your data has been processed.

Android applications can't upload photos to the server

I want to do an App. It can realize to upload the phone picture to server. Now it can take the picture and save to the mobile phone. But it can not upload into server. How to deal with this? The server is using tomcat to setup.
Android upload code:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class uploadActivity extends Activity
{
private Button uploadbutton;
private String uploadFile = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Test.jpg";
private String srcPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Test.jpg";
private String actionUrl = "http://192.168.1.105:8080/ATestInternetCameraServlet/";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
uploadbutton=(Button)findViewById(R.id.button2);
uploadbutton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
uploadFile();
}
});
}
private void uploadFile()
{ String uploadUrl = "http://192.168.1.105:8080/ATestInternetCameraServlet/CameraServlet";
String end = "\r\n";
String twoHyphens = "--";
String boundary = "******";
try
{
URL url = new URL(uploadUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(httpURLConnection
.getOutputStream());
dos.writeBytes(twoHyphens + boundary + end);
dos
.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
+ srcPath.substring(srcPath.lastIndexOf("/") + 1)
+ "\"" + end);
dos.writeBytes(end);
FileInputStream fis = new FileInputStream(srcPath);
byte[] buffer = new byte[8192]; // 8k
int count = 0;
while ((count = fis.read(buffer)) != -1)
{
dos.write(buffer, 0, count);
}
fis.close();
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
dos.flush();
InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String result = br.readLine();
Toast.makeText(this, result, Toast.LENGTH_LONG).show();//
dos.close();
is.close();
} catch (Exception e)
{
e.printStackTrace();
setTitle(e.getMessage());
}
}
}
The server code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class CameraServlet extends HttpServlet
{
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
try
{
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out2 = response.getWriter();
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
String uploadPath = "d:\\cameraupload\\";
File file = new File(uploadPath);
if (!file.exists())
{
file.mkdir();
}
String filename = "";
InputStream is = null;
for (FileItem item : items)
{
if (item.isFormField())
{
if (item.getFieldName().equals("filename"))
{
if (!item.getString().equals(""))
filename = item.getString("UTF-8");
}
}
else if (item.getName() != null && !item.getName().equals(""))
{
filename = item.getName().substring(
item.getName().lastIndexOf("\\") + 1);
is = item.getInputStream(); // 得到上传文件的InputStream对象
}
}
filename = uploadPath + filename;
if (new File(filename).exists())
{
new File(filename).delete();
}
// Began to upload files
if (!filename.equals(""))
{
// use FileOutputStream to open the upload file in server
FileOutputStream fos2 = new FileOutputStream(filename);
byte[] buffer = new byte[8192];
int count = 0;
// Began to read the upload file in bytes,and input it to server's upload file output stream
while ((count = is.read(buffer)) > 0)
{
fos2.write(buffer, 0, count); // To write the byte stream server files
}
fos2.close(); // close FileOutputStream object
is.close(); // InputStream object
out2.println("file upload success!xii");
}
}
catch (Exception e)
{
}
}
}
Do you have any error tracing?? Our just happening nothing??
For using httpurlconnection, you need to change the policy at the beginning:
ThreadPolicy mThreadPolicy = new ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(mThreadPolicy);
Try this.
Isn't 192.168.1.105 an IP-adress on the local network? Are you sure it's reachable from your phone? Open your phone's browser and try to navigate to the URL, can you reach it?
At what end are you having problems with the upload? Client or server? If it's on the client, what error are you getting? Or is it silently failing? Have you tried to make a simple HTML form and do the upload from there? If that is working you know it's your Android code that is the problem?
Also, it hurts every time I see someone trying to implement file uploads on their own. I'm not saying that your code is wrong, but it's an awful lot of lines of code (thus more risk of errors) compared to if you'd use a 3rd party library to abstract away all of that code for you. A well known and popular library such as Android Asynchronous Http Client has good support for file uploads out of the box:
AsyncHttpClient client = new AsyncHttpClient();
String filename = "file.png";
File myFile = new File("/path/to/" + filename);
RequestParams params = new RequestParams();
try {
params.put("file", myFile);
params.put("filename", filename);
client.post("http://192.168.1.105:8080/ATestInternetCameraServlet/CameraServlet", params, responseHandler);
}
catch(FileNotFoundException e) {
// handle
}
Try this...add apache-mime4j-0.6.jar and httpmime-4.0.3.jar libs
File f=new File(exsistingFileName);
HttpClient http = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.1.105:8080/ATestInternetCameraServlet/CameraServlet");
MultipartEntity Mentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
String url1=exsistingFileName;
String mime;
String extension = MimeTypeMap.getFileExtensionFromUrl(url1);
if (extension != ""&&extension!=null) {
MimeTypeMap mime1 = MimeTypeMap.getSingleton();
mime = mime1.getMimeTypeFromExtension(extension);
}
else
{
String ext = url1.substring((url1.lastIndexOf(".") + 1), url1.length());
MimeTypeMap mime1 = MimeTypeMap.getSingleton();
mime = mime1.getMimeTypeFromExtension(ext);
}
ContentBody cbFile;
if(mime!=null)
cbFile= new FileBody(f,mime);
else
cbFile=new FileBody(f);
Mentity.addPart("file",cbFile);
post.setEntity(Mentity);
HttpResponse response = null;
try {
response = http.execute(post);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
responseString = new BasicResponseHandler().
handleResponse(response);
} catch (HttpResponseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}

Categories

Resources