Android Open Source - dCache-Cloud Upload Service






From Project

Back to project page dCache-Cloud.

License

The source code is released under:

Copyright ? 2013, Michael Stapelberg and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following ...

If you think the Android project dCache-Cloud listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package de.desy.dCacheCloud;
/* ww w. j av  a  2s  . c  o m*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultRedirectHandler;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.IntentService;
import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import de.desy.dCacheCloud.CountingInputStreamEntity.UploadListener;

/**
 * @author Tom Schubert
 * @version 0.9 BETA
 * @since 18.08.2014
 *
 */
@SuppressLint("NewApi")
public class UploadService extends IntentService {

  // Defines begin //
  private static boolean HTTPLOG = false;
  // Defines End //
  
  private boolean isRedirected = false;
  private DefaultHttpClient httpClient = null;
  private HttpContext context = null;
  private CountingInputStreamEntity entity = null;
  private ContentResolver cr = null;
  private NotificationManager mNotificationManager = null;
  private HttpPut httpPut = null;

  private List<String> target = new ArrayList<String>();
  private String filename = null;
  private Uri fileUri = null;
  private CryptoHelper ch = null;

  public UploadService() {
    super("UploadService");
  }
  
  private boolean uploadFile() {
  
    isRedirected = false;
    
    // the return Value from the doors seems to be like "[Location: http:....?uid=...]"
    String finalTarget = target.get(target.size()-1);
    //Log.d("finalTarget: ", finalTarget);
    
    if (finalTarget != null && !finalTarget.startsWith("http")) {
      finalTarget = finalTarget.substring(finalTarget.indexOf("http"), finalTarget.length()-1);
      target.set(target.size()-1, finalTarget);
    } else if (finalTarget != null && !finalTarget.endsWith(filename)) {
      finalTarget += filename;
      target.set(target.size()-1, finalTarget);
    }

    URI uri = null;
    try {
    URL url = new URL(finalTarget);
      uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
    } catch (URISyntaxException e1) {
      e1.printStackTrace();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }

    //httpPut.setURI(URI.create(finalTarget));
    httpPut.setURI(uri);
    
    HttpResponse response = null;
    try {
      response = httpClient.execute(httpPut, context);
    } catch (ClientProtocolException e) {
      e.printStackTrace();
      return false;
    } catch (IOException e) {    
      e.printStackTrace();
      return false;
    }
    
    if (isRedirected) {
      uploadFile();
      return true;
    }
    
    int status = response.getStatusLine().getStatusCode();
    
    // 201 means the file was created.
    // 200 and 204 mean it was stored but already existed.
    
    if (android.os.Build.VERSION.SDK_INT >= 11) {
      if (status == 201 || status == 200 || status == 204) {
        NotificationCancel(fileUri.toString());
      }
      else 
      {
        // Uploading Failed!
        Log.d("davsyncs", "" + response.getStatusLine());
        NotificationNotify(fileUri.toString(),NotificationFailurePrepare(response.getStatusLine().toString()));
      }
    }
  
    return true;
  }

  private boolean InitializeComponents(Intent intent)
  {
    cr = getContentResolver();
    context = new BasicHttpContext();
    
    if (android.os.Build.VERSION.SDK_INT >= 11) {
      mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    }
    
    /* Get Settings Begin */
    SharedPreferences preferences = getSharedPreferences("de.desy.dCacheCloud_preferences", Context.MODE_PRIVATE);
    target.add(preferences.getString("webdav_url", null));
    String user = preferences.getString("webdav_user", null);
    String password = preferences.getString("webdav_password", null);
    /* Get Settings End */
    
    /*
    if (target.get(target.size()-1) == null) {
      Log.d("dCache", "No URL set up.");
      return false;
    }
    */
      
    // Get Extras from Intend-Loader

    fileUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);

    File sdCard = Environment.getExternalStorageDirectory();
    fileUri = Uri.parse(String.format("file://%s/%s/%s", sdCard.getAbsolutePath(), "dCacheCloud/.enc", fileUri.getLastPathSegment()));
//    File fileOutput = new File(sdCard, String.format("dCacheCloud/%s", CryptoHelper.hash(fileUri.getLastPathSegment())));
    
    Log.d("davsync", "Uploading " + fileUri.toString());
    filename = fileUri.getLastPathSegment();


    
    if (filename == null) {
      Log.d("dCache", "fileName returned null");
      return false;
    }
    setFileHandling();
    
    try {
      httpClient = ServerHelper.getClient();
    } catch (GeneralSecurityException e) {
      Log.d("SECURITY", String.format("General Security Error: %s", e.toString()));
      e.printStackTrace();
    } catch (IOException e1) {
      Log.d("Unknown", String.format("Error: %s", e1.toString()));
      e1.printStackTrace();
    }
    
    httpClient.setRedirectHandler(new DefaultRedirectHandler() {  
      @Override
      public URI getLocationURI(HttpResponse response, HttpContext contet) throws org.apache.http.ProtocolException {
        
        Log.d("Rederection!!: ", Arrays.toString(response.getHeaders("Location")));
        System.out.println(Arrays.toString(response.getHeaders("Location")));
        
        target.add(Arrays.toString(response.getHeaders("Location")));
        isRedirected = true;
        return super.getLocationURI(response, context);
      }
      
    });
    
    httpPut = new HttpPut();
    httpPut.setEntity(entity);
    ServerHelper.setCredentials(httpClient, httpPut, user, password);
    
    return true;
  }
  
  private Builder NotificationFailurePrepare(String text) {
    
    Builder mBuilder = new Builder(this);
    
    mBuilder.setContentText(filename + ": " + text);
    mBuilder.setContentTitle("Error uploading to dCache server");
    mBuilder.setProgress(0, 0, false);
    mBuilder.setOngoing(false);
    
    return mBuilder;
  }
  
  private Builder NotificationUploadPrepare(String text){
    
    Builder mBuilder = new Builder(this);
    
    /* Setup Notification Manager Begin */
    mBuilder.setContentTitle("Uploading to dCache server");
    mBuilder.setContentText(text);
    mBuilder.setSmallIcon(android.R.drawable.ic_menu_upload);
    mBuilder.setOngoing(true);
    mBuilder.setProgress(100, 0, false);
    /* Setup Notification Manager End */
    
    return mBuilder;
  }
  
  @SuppressWarnings("deprecation")
  private void NotificationNotify(String tag, Builder mBuilder) {
    if (android.os.Build.VERSION.SDK_INT < 11) {
      // Not supported
    }
    if (android.os.Build.VERSION.SDK_INT < 16)
      mNotificationManager.notify(tag, 0, mBuilder.getNotification());
    else
      mNotificationManager.notify(tag, 0, mBuilder.build());
  }
  
  private void setFileHandling() {
    ParcelFileDescriptor fd;
    InputStream stream;
    try {
      fd = cr.openFileDescriptor(fileUri, "r");
      stream = cr.openInputStream(fileUri);
    } catch (FileNotFoundException e1) {
      Log.d("dCache", "File not Found!");
      e1.printStackTrace();
      return;
    }
    
    if (android.os.Build.VERSION.SDK_INT >= 11) {    
      final Builder mBuilder = NotificationUploadPrepare(filename);
      NotificationNotify(fileUri.toString(), mBuilder);
      
      entity = new CountingInputStreamEntity(stream, fd.getStatSize());
      
      entity.setUploadListener(new UploadListener() {
        @Override
        public void onChange(int percent) {
          mBuilder.setProgress(100, percent, false);
          NotificationNotify(fileUri.toString(), mBuilder);
        }
      });
    }
  }
  
  private void NotificationCancel(String tag) {
    mNotificationManager.cancel(tag, 0);
    DatabaseHelper helper = new DatabaseHelper(this);
    helper.removeUriFromQueue(fileUri.toString());
  }
  
  @Override
  protected void onHandleIntent(Intent intent) {
    
    SharedPreferences preferences = getSharedPreferences("de.desy.dCacheCloud_preferences", Context.MODE_PRIVATE);
    String user = preferences.getString("webdav_user", null);
    String password = preferences.getString("webdav_password", null);
    ch = new CryptoHelper();
    
    if (user != null || password != null || user != "" || password != "") { 
    
      int retryCount = 5;
      while (!InitializeComponents(intent) && retryCount-- != 0);
      
      uploadFile();
    } else
      alert();
      
  }

  private void alert() {
    {
      
      AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);

      dlgAlert.setMessage("This is an alert with no consequence");
      dlgAlert.setTitle("App Title");
      dlgAlert.setPositiveButton("OK", null);
      dlgAlert.setCancelable(true);
      dlgAlert.create().show();      
      
    }
  }
}




Java Source Code List

External.Contents.java
External.IntentIntegrator.java
External.IntentResult.java
External.QRCodeEncoder.java
de.desy.dCacheCloud.CountingInputStreamEntity.java
de.desy.dCacheCloud.CryptoHelper.java
de.desy.dCacheCloud.DatabaseHelper.java
de.desy.dCacheCloud.DownloadService.java
de.desy.dCacheCloud.KeyStoreHelper.java
de.desy.dCacheCloud.MySSLSocketFactory.java
de.desy.dCacheCloud.ServerHelper.java
de.desy.dCacheCloud.UploadService.java
de.desy.dCacheCloud.Activities.FriendFoundActivity.java
de.desy.dCacheCloud.Activities.ImportDataActivity.java
de.desy.dCacheCloud.Activities.MainActivity.java
de.desy.dCacheCloud.Activities.ProfileActivity.java
de.desy.dCacheCloud.Activities.ServerViewActivity.java
de.desy.dCacheCloud.Activities.SettingsActivity.java
de.desy.dCacheCloud.Activities.ShareDataActivity.java
de.desy.dCacheCloud.Activities.ShareWithFriendActivity.java
de.desy.dCacheCloud.Activities.UploadActivity.java
de.desy.dCacheCloud.Activities.UserPasswordActivity.java
de.desy.dCacheCloud.BCReceiver.NetworkReceiver.java
de.desy.dCacheCloud.BCReceiver.NewMediaReceiver.java