Android Open Source - opentraining Wger Image Downloader






From Project

Back to project page opentraining.

License

The source code is released under:

GNU General Public License

If you think the Android project opentraining 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

/**
 * /* ww  w.ja va2 s . com*/
 * This is OpenTraining, an Android application for planning your your fitness training.
 * Copyright (C) 2012-2014 Christian Skubich
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package de.skubware.opentraining.activity.settings.sync;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import de.skubware.opentraining.basic.ExerciseType;
import de.skubware.opentraining.basic.License;
import de.skubware.opentraining.basic.License.LicenseType;
import de.skubware.opentraining.db.DataHelper;
import de.skubware.opentraining.db.IDataProvider;

/**
 * A class to encapsulate downloading missing images from wger.
 * 
 */
public class WgerImageDownloader {
  /** Tag for logging */
  private static final String TAG = "WgerImageDownloader";

  private String mLicenseJSONString;
  private Context mContext;
  private RestClient mClient;

  public WgerImageDownloader(String licenseJSONString, Context context, RestClient client) {
    mLicenseJSONString = licenseJSONString;
    mContext = context;
    mClient = client;
  }

  /**
   * Download the missing images from wger. If an image already exists Open
   * Training assumes that the exercise is duplicate and will remove it from
   * the download list.
   */
  public ArrayList<ExerciseType> downloadImages(List<ExerciseType.Builder> exerciseBuilderList) throws IOException, JSONException {
    ArrayList<ExerciseType> newExerciseList = new ArrayList<ExerciseType>();

    // add label to be able to break/continue from inner loop
    outerloop:
    for (ExerciseType.Builder exBuilder : exerciseBuilderList) {
      List<File> newImagePathList = new ArrayList<File>();
      Map<File, License> newImageLicenseMap = new HashMap<File, License>();

      ExerciseType ex = exBuilder.build();
      for (File img : ex.getImagePaths()) {
        String imageAsJSON = mClient.get(img.getPath() + "/");
        
        // get image name
        JSONObject imageJSONObject = new JSONObject(imageAsJSON);
        String imageDownloadPath = imageJSONObject.getString("image");
        
        
        // parse JSON and get license
        SparseArray<LicenseType> licenseSparseArray = WgerJSONParser.parseLicenses(mLicenseJSONString);

        int licenseNumber = WgerJSONParser.getLastNumberOfJson(imageJSONObject.getString("license"));
        LicenseType licenseType = licenseSparseArray.get(licenseNumber);
        String author = imageJSONObject.getString("license_author");
        Log.v(TAG, "license=" + licenseType.toString() + " license_author=" + author);
        
        License license = new License(licenseType, author);
        //String licensePath = imageJSONObject.getString("license");

        
        // skip exercise (and image download) if there's already one with the same name
        DataHelper dataHelper = new DataHelper(mContext);
        String imageName = (new File(imageDownloadPath)).getName();
        if(dataHelper.drawableExist(imageName)){
          Log.d(TAG, "There's already an image with the same name as: " + imageDownloadPath + ". The exercise: " + ex.getLocalizedName() + " is propably duplicate, it will not be added.");
          continue outerloop;
        }else{
          // only download image if its name is unique
          imageName = downloadImageToSyncedImagesFolder(imageDownloadPath); // imageName may change!
        }
        
        // add image name + license to list/map
        File imageFile = new File(imageName);
        newImagePathList.add(imageFile);
        newImageLicenseMap.put(imageFile, license);
      }
      // set collected values for builder, add new object to exercise list
      exBuilder.imagePath(newImagePathList);
      exBuilder.imageLicenseMap(newImageLicenseMap);

      newExerciseList.add(exBuilder.build());

    }
    return newExerciseList;
  }

  /**
   * 
   * @param urlToDownload
   *            the url
   * @return the name of the downloaded image. This name can be different from
   *         the original name if there's already a file with the same name.
   */
  private String downloadImageToSyncedImagesFolder(String urlToDownload) {
    try {
      URL url = new URL(urlToDownload);
      URLConnection connection = url.openConnection();
      connection.connect();
      // this will be useful so that you can show a typical 0-100%
      // progress bar
      int fileLength = connection.getContentLength();

      // download the file
      InputStream input = new BufferedInputStream(url.openStream());

      // create output folder
      String outputFolder = mContext.getFilesDir().toString() + "/" + IDataProvider.SYNCED_IMAGES_FOLDER;
      (new File(outputFolder)).mkdir();
      String imageName = new File(urlToDownload).getName();
      String outputPath = outputFolder + "/" + imageName;

      // skip files that already exist
      if ((new File(outputPath)).exists()) {
        Log.e(TAG, "already such a file: " + outputPath);
        Log.e(TAG, "Will SKIP this file.");
        return imageName;
      }
      OutputStream output = new FileOutputStream(outputPath);

      byte data[] = new byte[1024];
      long total = 0;
      int count;
      while ((count = input.read(data)) != -1) {
        total += count;
        // publishing the progress....
        Bundle resultData = new Bundle();
        resultData.putInt("progress", (int) (total * 100 / fileLength));
        // receiver.send(UPDATE_PROGRESS, resultData);
        output.write(data, 0, count);
      }

      output.flush();
      output.close();
      input.close();

      return imageName;
    } catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }

}




Java Source Code List

at.technikum.mti.fancycoverflow.FancyCoverFlowAdapter.java
at.technikum.mti.fancycoverflow.FancyCoverFlowItemWrapper.java
at.technikum.mti.fancycoverflow.FancyCoverFlow.java
de.skubware.opentraining.activity.ChangeLogDialog.java
de.skubware.opentraining.activity.DisclaimerDialog.java
de.skubware.opentraining.activity.MainActivity.java
de.skubware.opentraining.activity.NavigationGalleryAdapter.java
de.skubware.opentraining.activity.SelectWorkoutDialogFragment.java
de.skubware.opentraining.activity.WhatsNewDialog.java
de.skubware.opentraining.activity.acra.ACRACrashReportMailer.java
de.skubware.opentraining.activity.acra.ACRAFeedbackMailer.java
de.skubware.opentraining.activity.acra.OpenTrainingApplication.java
de.skubware.opentraining.activity.acra.RequestExerciseUpdate.java
de.skubware.opentraining.activity.create_exercise.CreateExerciseActivity.java
de.skubware.opentraining.activity.create_exercise.CustomSpinner.java
de.skubware.opentraining.activity.create_exercise.DescriptionFragment.java
de.skubware.opentraining.activity.create_exercise.EditImageMetadataDialog.java
de.skubware.opentraining.activity.create_exercise.EquipmentDataFragment.java
de.skubware.opentraining.activity.create_exercise.ExerciseImageListAdapter.java
de.skubware.opentraining.activity.create_exercise.ImageFragment.java
de.skubware.opentraining.activity.create_exercise.MuscleDataFragment.java
de.skubware.opentraining.activity.create_exercise.NameFragment.java
de.skubware.opentraining.activity.create_exercise.SimpleDataFragment.java
de.skubware.opentraining.activity.create_exercise.SpinnerDataFragment.java
de.skubware.opentraining.activity.create_workout.DialogFilterMusclesAndEquipment.java
de.skubware.opentraining.activity.create_workout.DialogWorkoutOverviewFragment.java
de.skubware.opentraining.activity.create_workout.ExerciseDetailOnGestureListener.java
de.skubware.opentraining.activity.create_workout.ExerciseTypeDetailActivity.java
de.skubware.opentraining.activity.create_workout.ExerciseTypeDetailFragment.java
de.skubware.opentraining.activity.create_workout.ExerciseTypeListActivity.java
de.skubware.opentraining.activity.create_workout.ExerciseTypeListAdapter.java
de.skubware.opentraining.activity.create_workout.ExerciseTypeListFragment.java
de.skubware.opentraining.activity.create_workout.SelectMuscleDialog.java
de.skubware.opentraining.activity.create_workout.SendExerciseFeedbackDialogFragment.java
de.skubware.opentraining.activity.create_workout.upload_exercise.ExerciseImage.java
de.skubware.opentraining.activity.create_workout.upload_exercise.UploadExerciseAsyncTask.java
de.skubware.opentraining.activity.create_workout.upload_exercise.UploadExerciseImagesAsyncTask.java
de.skubware.opentraining.activity.create_workout.upload_exercise.WgerRestService.java
de.skubware.opentraining.activity.manage_workouts.RenameWorkoutDialogFragment.java
de.skubware.opentraining.activity.manage_workouts.WorkoutDetailActivity.java
de.skubware.opentraining.activity.manage_workouts.WorkoutDetailFragment.java
de.skubware.opentraining.activity.manage_workouts.WorkoutListActivity.java
de.skubware.opentraining.activity.manage_workouts.WorkoutListFragment.java
de.skubware.opentraining.activity.settings.LicenseDialog.java
de.skubware.opentraining.activity.settings.SettingsActivity.java
de.skubware.opentraining.activity.settings.sync.OpenTrainingSyncResultReceiver.java
de.skubware.opentraining.activity.settings.sync.OpenTrainingSyncService.java
de.skubware.opentraining.activity.settings.sync.RestClient.java
de.skubware.opentraining.activity.settings.sync.SyncFinishedDialog.java
de.skubware.opentraining.activity.settings.sync.WgerImageDownloader.java
de.skubware.opentraining.activity.settings.sync.WgerJSONParser.java
de.skubware.opentraining.activity.start_training.DialogFragmentAddEntry.java
de.skubware.opentraining.activity.start_training.DialogFragmentTrainingEntryTable.java
de.skubware.opentraining.activity.start_training.FExDetailActivity.java
de.skubware.opentraining.activity.start_training.FExDetailFragment.java
de.skubware.opentraining.activity.start_training.FExListActivity.java
de.skubware.opentraining.activity.start_training.FExListAdapter.java
de.skubware.opentraining.activity.start_training.FExListFragment.java
de.skubware.opentraining.activity.start_training.RecoveryTimerManager.java
de.skubware.opentraining.activity.start_training.SwipeDismissListViewTouchListener.java
de.skubware.opentraining.activity.start_training.SwipeDismissTouchListener.java
de.skubware.opentraining.activity.start_training.TrainingEntryListAdapter.java
de.skubware.opentraining.basic.ActivationLevel.java
de.skubware.opentraining.basic.ExerciseTag.java
de.skubware.opentraining.basic.ExerciseType.java
de.skubware.opentraining.basic.FSet.java
de.skubware.opentraining.basic.FitnessExercise.java
de.skubware.opentraining.basic.IExercise.java
de.skubware.opentraining.basic.License.java
de.skubware.opentraining.basic.Muscle.java
de.skubware.opentraining.basic.SportsEquipment.java
de.skubware.opentraining.basic.TrainingEntry.java
de.skubware.opentraining.basic.Translatable.java
de.skubware.opentraining.basic.Workout.java
de.skubware.opentraining.db.Cache.java
de.skubware.opentraining.db.DataHelper.java
de.skubware.opentraining.db.DataProvider.java
de.skubware.opentraining.db.IDataProvider.java
de.skubware.opentraining.db.parser.AbstractJSONParser.java
de.skubware.opentraining.db.parser.ExerciseTagJSONParser.java
de.skubware.opentraining.db.parser.ExerciseTypeXMLParser.java
de.skubware.opentraining.db.parser.IParser.java
de.skubware.opentraining.db.parser.MuscleJSONParser.java
de.skubware.opentraining.db.parser.SportsEquipmentJSONParser.java
de.skubware.opentraining.db.parser.WorkoutXMLParser.java
de.skubware.opentraining.db.parser.XMLSaver.java
de.skubware.opentraining.db.rest.ExerciseImageGSONSerializer.java
de.skubware.opentraining.db.rest.ExerciseTypeGSONSerializer.java
de.skubware.opentraining.db.rest.LanguageGSONDeserializer.java
de.skubware.opentraining.db.rest.MuscleGSONDeserializer.java
de.skubware.opentraining.db.rest.ServerModel.java
de.skubware.opentraining.db.rest.SportsEquipmentGSONDeserializer.java
de.skubware.opentraining.exporter.HTMLExporter.java
de.skubware.opentraining.exporter.LaTeXExporter.java
de.skubware.opentraining.exporter.WorkoutExporter.java