Exemple #1
0
  public static void main(String[] args) {
    try {

      GsonFactory factory = new GsonFactory();
      List<TripOption> tripOptions =
          factory
              .fromString(
                  Files.toString(
                      new File("C:/projects/alacarte/backend/data/full_qpx.json"),
                      Charset.forName("UTF-8")),
                  TripsSearchResponse.class)
              .getTrips()
              .getTripOption();
      DataConverter dc = new DataConverter();
      /*
      ItineraryResults res = DataConverter.getItineraryResults(tripOptions);
      System.out.println(JSONUtil.write(res));
      System.out.println(JSONUtil.write(dc.getAxisData(tripOptions)));
      System.out.println(JSONUtil.write(dc.parseDate("2015-08-29T13:20+04:00")));
      */
      FlightSearchResults fsr = dc.getFlightSearchResults(tripOptions);
      System.out.println(JSONUtil.write(fsr));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
public class PlanningFragment extends Fragment {

  com.google.api.services.calendar.Calendar mService;
  GoogleAccountCredential credential;

  final HttpTransport transport = AndroidHttp.newCompatibleTransport();
  final JsonFactory jsonFactory = GsonFactory.getDefaultInstance();

  private TextView mStatusText;
  private ListView mResultsLv;

  static final int REQUEST_ACCOUNT_PICKER = 1000;
  static final int REQUEST_AUTHORIZATION = 1001;
  static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002;

  private static final String PREF_ACCOUNT_NAME = "accountName";
  private static final String[] SCOPES = {CalendarScopes.CALENDAR_READONLY};

  @Nullable
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View layout = inflater.inflate(R.layout.fragment_planning, container, false);

    mStatusText = (TextView) layout.findViewById(R.id.tvStatutPlanning);
    mStatusText.setText("Récupération des rendez-vous...");

    mResultsLv = (ListView) layout.findViewById(R.id.lvResultatPlanning);

    SharedPreferences settings = getActivity().getPreferences(Context.MODE_PRIVATE);

    credential =
        GoogleAccountCredential.usingOAuth2(getContext(), Arrays.asList(SCOPES))
            .setBackOff(new ExponentialBackOff())
            .setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));

    mService =
        new com.google.api.services.calendar.Calendar.Builder(transport, jsonFactory, credential)
            .setApplicationName("MapEleve")
            .build();

    return layout;
  }

  @Override
  public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_planning, menu);
    NavigationDrawerActivity.actionBar.setTitle(CalendarInfo.calendarInfoSelect.summary);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.action_synchro) {
      refreshResults();
      return true;
    }

    return super.onOptionsItemSelected(item);
  }

  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    // Indicate that this fragment would like to influence the set of actions in the action bar.
    setHasOptionsMenu(true);
  }

  @Override
  public void onResume() {
    super.onResume();
    if (isGooglePlayServicesAvailable()) {
      refreshResults();
    } else {
      mStatusText.setText(
          "Google Play Services requis : " + "après installation, fermer et relancer MapEleve.");
    }
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
  }

  @Override
  public void onLowMemory() {
    super.onLowMemory();
  }

  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
      case REQUEST_GOOGLE_PLAY_SERVICES:
        if (resultCode != Activity.RESULT_OK) {
          isGooglePlayServicesAvailable();
        }
        break;
      case REQUEST_ACCOUNT_PICKER:
        if (resultCode == Activity.RESULT_OK && data != null && data.getExtras() != null) {
          String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
          if (accountName != null) {
            credential.setSelectedAccountName(accountName);
            SharedPreferences settings = getActivity().getPreferences(Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString(PREF_ACCOUNT_NAME, accountName);
            editor.commit();
          }
        } else if (resultCode == Activity.RESULT_CANCELED) {
          mStatusText.setText("Pas de compte sélectionné");
        }
        break;
      case REQUEST_AUTHORIZATION:
        if (resultCode != Activity.RESULT_OK) {
          chooseAccount();
        }
        break;
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  /**
   * Attempt to get a set of data from the Google Calendar API to display. If the email address
   * isn't known yet, then call chooseAccount() method so the user can pick an account.
   */
  private void refreshResults() {
    if (credential.getSelectedAccountName() == null) {
      chooseAccount();
    } else {
      if (isDeviceOnline()) {
        new PlanningAsyncTask(this).execute();
      } else {
        mStatusText.setText("Pas de connexion Internet disponible.");
      }
    }
  }

  /**
   * Clear any existing Google Calendar API data from the TextView and update the header message;
   * called from background threads and async tasks that need to update the UI (in the UI thread).
   */
  public void clearResultsText() {
    getActivity()
        .runOnUiThread(
            new Runnable() {
              @Override
              public void run() {
                mStatusText.setText("Récupération des rendez-vous...");
                mResultsLv.setAdapter(null);
              }
            });
  }

  /**
   * Fill the data TextView with the given List of Strings; called from background threads and async
   * tasks that need to update the UI (in the UI thread).
   *
   * @param dataStrings a List of Strings to populate the menu_main TextView with.
   */
  public void updateResultsText(final List<Planning> dataStrings) {
    getActivity()
        .runOnUiThread(
            new Runnable() {
              @Override
              public void run() {
                if (dataStrings == null) {
                  mStatusText.setText("Erreur lors de la récupération");
                } else if (dataStrings.size() == 0) {
                  mStatusText.setText("Pas de rendez-vous inscrit au planning");
                } else {
                  mStatusText.setText("Liste des rendez-vous :");
                  PlanningAdapter p = new PlanningAdapter(getContext(), dataStrings);
                  mResultsLv.setAdapter(p);
                }
              }
            });
  }

  /**
   * Show a status message in the list header TextView; called from background threads and async
   * tasks that need to update the UI (in the UI thread).
   *
   * @param message a String to display in the UI header TextView.
   */
  public void updateStatus(final String message) {
    getActivity()
        .runOnUiThread(
            new Runnable() {
              @Override
              public void run() {
                mStatusText.setText(message);
              }
            });
  }

  /** Démarre un activité Google Play Services pour que l'utilisateur se connecte. */
  private void chooseAccount() {
    startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
  }

  /**
   * Vérifie si le téléphone est connecté à Internet.
   *
   * @return true si il l'est, false sinon.
   */
  private boolean isDeviceOnline() {
    ConnectivityManager connMgr =
        (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    return (networkInfo != null && networkInfo.isConnected());
  }

  /**
   * Vérifie que Google Play services APK est installé et à jour. Lancera un message d'erreur
   * demandant la mise à jour si nécessaire et possible.
   *
   * @return true si Google Play Services est dipo et à jour, sinon retourne false
   */
  private boolean isGooglePlayServicesAvailable() {
    final int connectionStatusCode =
        GooglePlayServicesUtil.isGooglePlayServicesAvailable(getContext());
    if (GooglePlayServicesUtil.isUserRecoverableError(connectionStatusCode)) {
      showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
      return false;
    } else if (connectionStatusCode != ConnectionResult.SUCCESS) {
      return false;
    }
    return true;
  }

  /**
   * Affiche un message d'erreur quand Google Play Services est manquant ou n'est pas à jour.
   *
   * @param connectionStatusCode sert à savoir la présence ou le manque de Google Play Services sur
   *     le téléphone
   */
  void showGooglePlayServicesAvailabilityErrorDialog(final int connectionStatusCode) {
    getActivity()
        .runOnUiThread(
            new Runnable() {
              public void run() {
                Dialog dialog =
                    GooglePlayServicesUtil.getErrorDialog(
                        connectionStatusCode, getActivity(), REQUEST_GOOGLE_PLAY_SERVICES);
                dialog.show();
              }
            });
  }
}
public class PolyMergedListActivity extends AppCompatActivity {
  private static final String PREF_ACCOUNT_NAME = "Pref_ColorManager";
  private static final String PREF_KEY_ACCOUNT_NAME = "accountName";
  private static final String APPLICATION_NAME = "PolyhedralTodoList/1.0";

  private static final int REQUEST_GOOGLE_PLAY_SERVICES = 0;
  public static final int REQUEST_AUTHORIZATION = 1;
  private static final int REQUEST_ACCOUNT_PICKER = 2;

  private static final String List_ID = "LIST_ID";

  final HttpTransport httpTransport = AndroidHttp.newCompatibleTransport();
  final GsonFactory gsonFactory = GsonFactory.getDefaultInstance();

  GoogleAccountCredential credential;

  PolyMergedList polyMergedList;

  ListView listView;
  PolyTodoItemArrayAdapter adapter;
  List<PolyTodoItem> polyTodoItems;

  //    List<MenuItem> disabledMenuItems;

  // ===========================================
  // LIFECYCLE
  // ===========================================
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_poly_main_list);

    // ListView
    listView = (ListView) findViewById(R.id.listViewPolyList);
    listView.setOnItemClickListener(
        new AdapterView.OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            Log.d("PolyMergedListActivity", "ListView.onItemClick is called.");
            boolean isSuccess = polyMergedList.moveUpGlobalTask(position);
            if (isSuccess) {
              polyTodoItems = polyMergedList.getGlobalTodoItems();
              refreshView();
            }
          }
        });
    listView.setOnItemLongClickListener(
        new AdapterView.OnItemLongClickListener() {
          @Override
          public boolean onItemLongClick(
              AdapterView<?> adapterView, View view, int position, long idl) {
            Log.d("PolyMergedListActivity", "ListView.onItemLongClick is called.");
            boolean isSuccess = polyMergedList.moveDownGlobalTask(position);
            if (isSuccess) {
              polyTodoItems = polyMergedList.getGlobalTodoItems();
              refreshView();
            }
            return true; // true: consume this event here
          }
        });

    // PolyMainList
    polyMergedList = PolyMergedListImpl.getInstance();
    polyMergedList.setOnListChanged(
        new OnMergedListChangedListener() {
          @Override
          public void mainListChanged() {
            //                polyTodoItems = polyMainList.getGlobalTodoItems();
            //                adapter.insert();
            //                refreshView();
          }
        });

    //        disabledMenuItems = new ArrayList<>();
  }

  @Override
  protected void onResume() {
    super.onResume();
    if (checkGooglePlayServicesAvailability()) {
      haveGooglePlayServices();
    }
  }

  // ----------
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
      case REQUEST_GOOGLE_PLAY_SERVICES:
        if (resultCode == Activity.RESULT_OK) {
          haveGooglePlayServices();
        } else {
          checkGooglePlayServicesAvailability();
        }
        break;
      case REQUEST_ACCOUNT_PICKER:
        if (resultCode == Activity.RESULT_OK && data != null && data.getExtras() != null) {
          String accountName = data.getExtras().getString(AccountManager.KEY_ACCOUNT_NAME);
          if (accountName != null) {
            credential.setSelectedAccountName(accountName);
            SharedPreferences pref = getSharedPreferences(PREF_ACCOUNT_NAME, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = pref.edit();
            editor.putString(PREF_KEY_ACCOUNT_NAME, accountName);
            editor.apply();
            //                        AsyncLoadTasks.run(this, polyMainList);
          }
        }
        break;
      case REQUEST_AUTHORIZATION: // In AsyncLoadTasks, when access right is needed.
        // UserRecoverableException
        if (resultCode == Activity.RESULT_OK) {
          //                    AsyncLoadTasks.run(this, polyMainList);
        } else {
          chooseAccount();
        }
        break;
    }
  }

  // ----------
  public void refreshView() {
    if (adapter == null) {
      adapter = new PolyTodoItemArrayAdapter(this, 0, polyTodoItems);
      listView.setAdapter(adapter);
    } else {
      adapter.notifyDataSetChanged();
    }

    //        for (MenuItem item : disabledMenuItems) {
    //            item.setEnabled(true);
    //        }
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    switch (id) {
      case R.id.action_insert:
        // TODO: Add function
        // If an item is not selected, add last.
        // If an item is selected, insert next the item.
        //                View selectedView = adapter.getSelectedView();
        //                adapter.getPosition(selectedView.getContext());
        //                if (selectedView == null) {
        //                    polyMainList.addTodoList(selectedView);
        //                }
        return true;
      case R.id.action_add:
        // TODO: Ask user which list the new item is added to.
        // show chooser to select list
        //                item.setEnabled(false);
        //                disabledMenuItems.add(item);
        String listId = polyMergedList.getPolyTodoListId(0); // test
        polyMergedList.addTodoItem(listId);
        setPolyTodoItems(polyMergedList.getGlobalTodoItems());
        adapter.notifyDataSetChanged(); // TODO: work???
        return true;
        //            case R.id.action_remove:
        //                // TODO: Remove function
        //                return true;
      case R.id.action_list_01:
        return startListActivity(0);
      case R.id.action_list_02:
        return startListActivity(1);
        //            case R.id.action_settings:
        //                return true;
    }

    return super.onOptionsItemSelected(item);
  }

  // ----------
  public Tasks getService() {
    return polyMergedList.getTasksService();
  }

  public void setPolyTodoItems(List<PolyTodoItem> polyTodoItems) {
    this.polyTodoItems = polyTodoItems;
  }

  // ===========================================
  // PRIVATE
  // ===========================================
  private boolean checkGooglePlayServicesAvailability() {
    final int connectionStatusCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (GooglePlayServicesUtil.isUserRecoverableError(connectionStatusCode)) {
      showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
      return false;
    }
    return true;
  }

  private void showGooglePlayServicesAvailabilityErrorDialog(final int connectionStatusCode) {
    runOnUiThread(
        new Runnable() {
          @Override
          public void run() {
            Dialog dialog =
                GooglePlayServicesUtil.getErrorDialog(
                    connectionStatusCode,
                    PolyMergedListActivity.this,
                    REQUEST_GOOGLE_PLAY_SERVICES);
            dialog.show();
          }
        });
  }

  private void haveGooglePlayServices() {
    if (polyMergedList.getTasksService() == null) {
      // TODO: New authentication ?
      Log.e("haveGooglePlayServices", "Not implement new authentication");
      chooseAccount();
    } else {
      if (polyMergedList != null && !polyMergedList.isLoaded()) {
        //                AsyncLoadTasks.run(this, polyMainList);
      } else {
        if (polyTodoItems == null) {
          polyTodoItems = polyMergedList.getGlobalTodoItems();
        }
        refreshView();
      }
    }
  }

  private void chooseAccount() {
    startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
  }

  private boolean startListActivity(int num) {
    try {
      Intent intent = new Intent(this, PolyListActivity.class);
      intent.putExtra(List_ID, polyMergedList.getPolyTodoListId(num));
      startActivity(intent);
      overridePendingTransition(R.anim.abc_slide_in_bottom, 0);
    } catch (IndexOutOfBoundsException e) {
      e.printStackTrace();
      return false; // ???
    }
    return true;
  }
}