Commit 0aab9660 authored by Loris Croce's avatar Loris Croce
Browse files

sender devrait marcher

parent 450bb168
......@@ -33,5 +33,6 @@ dependencies {
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation "com.androidplot:androidplot-core:1.5.6"
implementation 'com.android.volley:volley:1.1.1'
implementation 'com.squareup.retrofit2:retrofit:2.0.0'
implementation 'com.squareup.retrofit2:converter-gson:2.0.0'
}
......@@ -3,10 +3,10 @@ package de.tonifetzer.sensorrecorder;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
......@@ -16,9 +16,9 @@ import android.widget.Toast;
import android.widget.ToggleButton;
import java.io.File;
import java.io.FileNotFoundException;
import co.nstant.in.cbor.CborException;
import de.tonifetzer.sensorrecorder.sender.Sender;
import de.tonifetzer.sensorrecorder.sensors.Entry;
import de.tonifetzer.sensorrecorder.sensors.Logger;
import de.tonifetzer.sensorrecorder.sensors.MySensor;
......@@ -42,6 +42,7 @@ public class MainActivity extends AppCompatActivity {
private PhoneSensors phoneSensors;
private final Logger dataLogger = new Logger(this);
private final Sender sender = new Sender();
private String appUser;
private String appPosition;
......@@ -51,6 +52,8 @@ public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sender.start();
//this is super ugly. normally we would use fragments to switch ui
mainView = getLayoutInflater().inflate(R.layout.activity_main, null);
setContentView(mainView);
......@@ -84,9 +87,9 @@ public class MainActivity extends AppCompatActivity {
@Override
public void onClick(View v) {
try {
fileSend();
//TODO list files in directory and send them
} catch (Exception e) {
e.printStackTrace();
}
}
});
......
package de.tonifetzer.sensorrecorder.sender;
import java.util.List;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
public
interface ApiConfig {
@Multipart
@POST("retrofit_example/upload_image.php")
Call uploadFile(@Part MultipartBody.Part file, @Part("file") RequestBody name);
@Multipart
@POST("retrofit_example/upload_multiple_files.php")
Call < ServerResponse > uploadMulFile(@Part List<MultipartBody.Part> files);
}
package de.tonifetzer.sensorrecorder.sender;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class AppConfig {
private static String BASE_URL = "http://192.168.1.39:12345";
public static Retrofit getRetrofit() {
return new Retrofit.Builder()
.baseUrl(AppConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
}
package de.tonifetzer.sensorrecorder.sender;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import de.tonifetzer.sensorrecorder.MainActivity;
import de.tonifetzer.sensorrecorder.sender.ApiConfig;
import de.tonifetzer.sensorrecorder.sender.AppConfig;
import de.tonifetzer.sensorrecorder.sender.ServerResponse;
import de.tonifetzer.sensorrecorder.sensors.Logger;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.Response;
public final class Sender {
private Context context;
private Logger dataLogger;
public void start() {
this.context = MainActivity.getAppContext();
dataLogger = new Logger(context);
}
public Sender() {
}
// Uploading Image/Video
public void uploadMultipleFiles(List<File> files) {
//progressDialog.show();
// Map is used to multipart the file using okhttp3.RequestBody
// Parsing any Media type file
List<RequestBody> requests = new ArrayList<>();
List<MultipartBody.Part> filesToUpload = new ArrayList<>();
RequestBody requestBody;
for (File file: files) {
requestBody = RequestBody.create(MediaType.parse("*/*"), file);
filesToUpload.add(MultipartBody.Part.createFormData("file1", file.getName(),
requestBody));
}
ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
retrofit2.Call<ServerResponse> call = getResponse.uploadMulFile(filesToUpload);
call.enqueue(new retrofit2.Callback<ServerResponse> () {
@Override
public void onResponse(retrofit2.Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
ServerResponse serverResponse = response.body();
if (serverResponse != null) {
if (serverResponse.getSuccess()) {
Toast.makeText(context, serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
assert serverResponse != null;
Log.v("Response", serverResponse.toString());
}
//progressDialog.dismiss();
}
@Override
public void onFailure(retrofit2.Call<ServerResponse> call, Throwable t) {
}
});
}
}
\ No newline at end of file
package de.tonifetzer.sensorrecorder.sender;
import com.google.gson.annotations.SerializedName;
public class ServerResponse {
// variable name should be same as in the json response from php
@SerializedName("success")
boolean success;
@SerializedName("message")
String message;
public String getMessage() {
return message;
}
public boolean getSuccess() {
return success;
}
}
/*
package de.tonifetzer.sensorrecorder.sensors;
import android.content.Context;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import de.tonifetzer.sensorrecorder.MainActivity;
public final class Sender {
private Context context;
private Logger dataLogger;
private String url = "http://192.168.1.39:12345";
private File folder = dataLogger.getFolder().getFolder();
public void start() {
this.context = MainActivity.getAppContext();
dataLogger = new Logger(context);
}
public Sender() { }
public void sendFile() {
VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(
Request.Method.POST,
url,
new Response.Listener<NetworkResponse>() {
@Override
public void onResponse(NetworkResponse response) {
//Handle response
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Handle error
}
}
) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
//Params
return params;
}
@Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();;
params.put("cbor", new DataPart(pdfName, getFileData()));
return params;
}
};
//I used this because it was sending the file twice to the server
volleyMultipartRequest.setRetryPolicy(
new DefaultRetryPolicy(
0,
-1,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
)
);
Volley.newRequestQueue(context).add(volleyMultipartRequest);
}
}
*/
package de.tonifetzer.sensorrecorder.sensors;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
public class VolleyMultipartRequest extends Request<NetworkResponse> {
private final String twoHyphens = "--";
private final String lineEnd = "\r\n";
private final String boundary = "apiclient-" + System.currentTimeMillis();
private Response.Listener<NetworkResponse> mListener;
private Response.ErrorListener mErrorListener;
private Map<String, String> mHeaders;
public VolleyMultipartRequest(int method, String url,
Response.Listener<NetworkResponse> listener,
Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return (mHeaders != null) ? mHeaders : super.getHeaders();
}
@Override
public String getBodyContentType() {
return "multipart/form-data;boundary=" + boundary;
}
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
try {
// populate text payload
Map<String, String> params = getParams();
if (params != null && params.size() > 0) {
textParse(dos, params, getParamsEncoding());
}
// populate data byte payload
Map<String, DataPart> data = getByteData();
if (data != null && data.size() > 0) {
dataParse(dos, data);
}
// close multipart form data after text and file data
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* Custom method handle data payload.
*
* @return Map data part label with data byte
* @throws AuthFailureError
*/
protected Map<String, DataPart> getByteData() throws AuthFailureError {
return null;
}
@Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
try {
return Response.success(
response,
HttpHeaderParser.parseCacheHeaders(response));
} catch (Exception e) {
return Response.error(new ParseError(e));
}
}
@Override
protected void deliverResponse(NetworkResponse response) {
mListener.onResponse(response);
}
@Override
public void deliverError(VolleyError error) {
mErrorListener.onErrorResponse(error);
}
/**
* Parse string map into data output stream by key and value.
*
* @param dataOutputStream data output stream handle string parsing
* @param params string inputs collection
* @param encoding encode the inputs, default UTF-8
* @throws IOException
*/
private void textParse(DataOutputStream dataOutputStream, Map<String, String> params, String encoding) throws IOException {
try {
for (Map.Entry<String, String> entry : params.entrySet()) {
buildTextPart(dataOutputStream, entry.getKey(), entry.getValue());
}
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Encoding not supported: " + encoding, uee);
}
}
/**
* Parse data into data output stream.
*
* @param dataOutputStream data output stream handle file attachment
* @param data loop through data
* @throws IOException
*/
private void dataParse(DataOutputStream dataOutputStream, Map<String, DataPart> data) throws IOException {
for (Map.Entry<String, DataPart> entry : data.entrySet()) {
buildDataPart(dataOutputStream, entry.getValue(), entry.getKey());
}
}
/**
* Write string data into header and data output stream.
*
* @param dataOutputStream data output stream handle string parsing
* @param parameterName name of input
* @param parameterValue value of input
* @throws IOException
*/
private void buildTextPart(DataOutputStream dataOutputStream, String parameterName, String parameterValue) throws IOException {
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + parameterName + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(parameterValue + lineEnd);
}
/**
* Write data file into header and data output stream.
*
* @param dataOutputStream data output stream handle data parsing
* @param dataFile data byte as DataPart from collection
* @param inputName name of data input
* @throws IOException
*/
private void buildDataPart(DataOutputStream dataOutputStream, DataPart dataFile, String inputName) throws IOException {
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" +
inputName + "\"; filename=\"" + dataFile.getFileName() + "\"" + lineEnd);
if (dataFile.getType() != null && !dataFile.getType().trim().isEmpty()) {
dataOutputStream.writeBytes("Content-Type: " + dataFile.getType() + lineEnd);
}
dataOutputStream.writeBytes(lineEnd);
ByteArrayInputStream fileInputStream = new ByteArrayInputStream(dataFile.getContent());
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024 * 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
}
class DataPart {
private String fileName;
private byte[] content;
private String type;
public DataPart() {
}
DataPart(String name, byte[] data) {
fileName = name;
content = data;
}
String getFileName() {
return fileName;
}
byte[] getContent() {
return content;
}
String getType() {
return type;
}
}
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment