public void onEventMainThread(UserPortraitUploadEvent event) {
    if (!isValidEvent(event)) {
      return;
    }

    if (event.isFailed()) {
      try {
        storeToCacheAndLaunchEvent(false, event, event.getUserId(), event.getPicturePath());
      } catch (Exception e) {
        notifyError(event);
      }
    } else {
      if (event.isRemote()) {
        store(true, event.getUserId(), event.getPicturePath());
      }

      User oldLoggedUser = SessionContext.getLoggedUser();

      if (event.getJSONObject() != null) {
        User user = new User(event.getJSONObject());
        if (oldLoggedUser != null && user.getId() == oldLoggedUser.getId()) {
          SessionContext.setLoggedUser(user);
        }
      }

      try {
        getListener().onUserPortraitUploaded(oldLoggedUser.getId());
      } catch (Exception e) {
        getListener().onUserPortraitUploadFailure(e);
      }
    }
  }
  private void sendRecords(Cache cache) {

    Long groupId = LiferayServerContext.getGroupId();
    List<DDLRecordCache> records = getLatestRecordsToSync(cache);

    DDLRecordService recordService =
        new DDLRecordService(SessionContext.createSessionFromCurrentSession());

    for (DDLRecordCache cachedRecord : records) {
      try {
        Record record = cachedRecord.getRecord();
        record.setCreatorUserId(SessionContext.getLoggedUser().getId());
        final JSONObject serviceContextAttributes = new JSONObject();
        serviceContextAttributes.put("userId", record.getCreatorUserId());
        serviceContextAttributes.put("scopeGroupId", groupId);
        JSONObjectWrapper serviceContextWrapper = new JSONObjectWrapper(serviceContextAttributes);
        JSONObject jsonContent = cachedRecord.getJSONContent();

        JSONObject jsonObject =
            saveOrUpdate(recordService, record, groupId, serviceContextWrapper, jsonContent);

        cachedRecord.setDirty(false);
        cachedRecord.setSyncDate(new Date());
        cache.set(cachedRecord);
      } catch (Exception e) {
        LiferayLogger.e("Error syncing a record", e);
      }
    }
  }
  @Override
  protected void onUserAction(
      String userActionName, BaseUserPortraitInteractor interactor, Object... args) {

    try {
      if (UPLOAD_PORTRAIT.equals(userActionName)) {
        UserPortraitUploadInteractor userPortraitInteractor =
            (UserPortraitUploadInteractor) getInteractor(userActionName);
        String path = (String) args[0];
        if (_userId != 0) {
          userPortraitInteractor.upload(_userId, path);
        }
      } else {
        UserPortraitLoadInteractor userPortraitLoadInteractor =
            (UserPortraitLoadInteractor) getInteractor(userActionName);
        if (_portraitId != 0 && _uuid != null) {
          userPortraitLoadInteractor.load(_male, _portraitId, _uuid);
        } else {
          if (SessionContext.hasUserInfo() && _userId == 0) {
            userPortraitLoadInteractor.load(SessionContext.getLoggedUser().getId());
          } else {
            userPortraitLoadInteractor.load(_userId);
          }
        }
      }
    } catch (Exception e) {
      onUserPortraitLoadFailure(e);
    }
  }
  @Override
  protected View createScreenletView(Context context, AttributeSet attributes) {
    TypedArray typedArray =
        context
            .getTheme()
            .obtainStyledAttributes(attributes, R.styleable.UserPortraitScreenlet, 0, 0);

    _autoLoad = typedArray.getBoolean(R.styleable.UserPortraitScreenlet_autoLoad, true);
    _male = typedArray.getBoolean(R.styleable.UserPortraitScreenlet_male, true);
    _portraitId = typedArray.getInt(R.styleable.UserPortraitScreenlet_portraitId, 0);
    _uuid = typedArray.getString(R.styleable.UserPortraitScreenlet_uuid);
    _editable = typedArray.getBoolean(R.styleable.UserPortraitScreenlet_editable, false);

    int offlinePolicy =
        typedArray.getInt(
            R.styleable.UserPortraitScreenlet_offlinePolicy, OfflinePolicy.REMOTE_ONLY.ordinal());
    _offlinePolicy = OfflinePolicy.values()[offlinePolicy];

    _userId =
        castToLongOrUseDefault(typedArray.getString(R.styleable.UserPortraitScreenlet_userId), 0L);

    if (SessionContext.hasUserInfo() && _portraitId == 0 && _uuid == null && _userId == 0) {
      _userId = SessionContext.getLoggedUser().getId();
    }

    int layoutId =
        typedArray.getResourceId(R.styleable.UserPortraitScreenlet_layoutId, getDefaultLayoutId());

    typedArray.recycle();

    return LayoutInflater.from(context).inflate(layoutId, null);
  }
  @Override
  public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (!SessionContext.isLoggedIn()) {
      SessionContext.loadStoredCredentials(
          CredentialsStorageBuilder.StorageType.SHARED_PREFERENCES);
      ((MenuActivity) getActivity()).loadPortrait();
    }
  }
  @Override
  protected boolean cached(Object[] args) {

    long groupId = (long) args[0];
    String articleId = (String) args[1];
    Locale locale = (Locale) args[2];
    Long templateId = (Long) args[3];

    String id = articleId + (templateId == null || templateId == 0 ? "" : templateId);
    Long userId = SessionContext.getUserId();
    TableCache webContent =
        (TableCache)
            CacheSQL.getInstance()
                .getById(DefaultCachedType.WEB_CONTENT, id, groupId, userId, locale);
    if (webContent != null) {
      onEvent(
          new WebContentDisplayEvent(
              getTargetScreenletId(),
              groupId,
              articleId,
              locale,
              templateId,
              webContent.getContent()));
      return true;
    }
    return false;
  }
 protected JournalArticleService getJournalArticleService(
     long groupId, String articleId, Locale locale) {
   Session session = SessionContext.createSessionFromCurrentSession();
   session.setCallback(
       new WebContentDisplayFromArticleIdCallback(
           getTargetScreenletId(), groupId, articleId, locale));
   return new JournalArticleService(session);
 }
 protected ScreensjournalarticleService getScreensJournalArticleService(
     long groupId, String articleId, Locale locale, Long templateId) {
   Session session = SessionContext.createSessionFromCurrentSession();
   WebContentDisplayFromArticleIdCallback callback =
       new WebContentDisplayFromArticleIdCallback(
           getTargetScreenletId(), groupId, articleId, locale, templateId);
   session.setCallback(callback);
   return new ScreensjournalarticleService(session);
 }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_notification_detail);

    if (!SessionContext.hasSession()) {
      startActivity(new Intent(this, LoginActivity.class));
    }

    new LiferayCrouton.Builder().withInfoColor(R.color.material_primary_crouton).build();

    ddlFormScreenlet = (DDLFormScreenlet) findViewById(R.id.ddl_form_screenlet);
    ddlFormScreenlet.setRecordId(getIntent().getIntExtra("recordId", 0));
    ddlFormScreenlet.setListener(this);
  }
  private void sendDocuments(Cache cache) {
    long userId = SessionContext.getDefaultUserId();
    long groupId = LiferayServerContext.getGroupId();

    List<DocumentUploadCache> documentsToUpload =
        cache.get(
            DOCUMENT_UPLOAD,
            DocumentUploadCache.DIRTY
                + " = 1 "
                + "AND "
                + DocumentUploadCache.USER_ID
                + " = ? "
                + "AND "
                + DocumentUploadCache.GROUP_ID
                + " = ? ",
            userId,
            groupId);

    for (DocumentUploadCache document : documentsToUpload) {
      try {
        Map<String, Object> objectObjectHashMap = new HashMap<>();
        DocumentField documentField = new DocumentField(objectObjectHashMap, new Locale("es"));
        documentField.createLocalFile(document.getPath());

        UploadService uploadService = new UploadService();
        JSONObject jsonObject =
            uploadService.uploadFile(
                documentField,
                document.getUserId(),
                document.getGroupId(),
                document.getRepositoryId(),
                document.getFolderId(),
                document.getFilePrefix());

        document.setDirty(false);
        document.setSyncDate(new Date());
        cache.set(document);
      } catch (Exception e) {
        LiferayLogger.e("Error sending documentsToUpload", e);
      }
    }
  }
  private void registerWithLiferayPortal(String register) {
    Push.with(SessionContext.createSessionFromCurrentSession())
        .onSuccess(
            new Push.OnSuccess() {

              @Override
              public void onSuccess(Object result) {
                LiferayLogger.i("Device registered with Liferay Portal: " + result);
              }
            })
        .onFailure(
            new Push.OnFailure() {

              @Override
              public void onFailure(Exception e) {
                LiferayLogger.e("Some error occurred: ", e);
              }
            })
        .register(register);
  }
  @Override
  protected void onHandleIntent(Intent intent) {
    ConnectivityManager cm =
        (ConnectivityManager)
            getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

    if (isConnected && SessionContext.hasSession()) {
      try {
        Cache cache = CacheSQL.getInstance();
        sendPortrait(cache);
        sendDocuments(cache);
        sendRecords(cache);
      } catch (Exception e) {
        LiferayLogger.e("Error syncing resources", e);
      }
    }
    CacheReceiver.completeWakefulIntent(intent);
  }
  private void sendPortrait(Cache cache) {
    long userId = SessionContext.getDefaultUserId();

    List<TableCache> userPortraits =
        cache.get(
            USER_PORTRAIT_UPLOAD,
            " AND " + TableCache.DIRTY + " = 1 " + " AND " + TableCache.USER_ID + " = ? ",
            userId);

    for (TableCache userPortrait : userPortraits) {
      try {
        UserPortraitService userPortraitService = new UserPortraitService();
        JSONObject jsonObject =
            userPortraitService.uploadUserPortrait(
                Long.valueOf(userPortrait.getId()), userPortrait.getContent());

        userPortrait.setDirty(false);
        userPortrait.setSyncDate(new Date());
        cache.set(userPortrait);
      } catch (Exception e) {
        LiferayLogger.e("Error sending portrait images", e);
      }
    }
  }
public class DisplayBusesFragment extends ListFragment {

  static String TAG = DisplayBusesFragment.class.getSimpleName();
  Session session = SessionContext.createSessionFromCurrentSession();
  List<Bus> busList;

  private OnFragmentInteractionListener mListener;

  String fromLocation;
  String toLocation;
  String date;

  public DisplayBusesFragment() {}

  public interface OnFragmentInteractionListener {
    public void onFragmentInteraction(Bus bus);
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    new GetBusesAsyncTask().execute(this.date, this.fromLocation, this.toLocation);
  }

  @Override
  public void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    if (null != mListener) {
      Bus tempBus = this.busList.get(position);
      Log.v(TAG, "Following Bus object was clicked " + tempBus.getBusId());
      mListener.onFragmentInteraction(tempBus);
    }
  }

  private class GetBusesAsyncTask extends AsyncTask<String, Void, List> {

    @Override
    protected List<Bus> doInBackground(String[] params) {
      BusroutetimingsService busroutetimingsService = null;
      JSONArray jsonArray = null;
      List<Bus> tempBusList = null;

      if (session != null) {
        Log.v(TAG, "Got Session");
        busroutetimingsService = new BusroutetimingsService(session);
        try {
          jsonArray =
              busroutetimingsService.getBusBasedOnRouteAndDate(params[0], params[1], params[2]);
        } catch (Exception e) {
          Log.v(TAG, "Error " + e.getMessage());
        }
      }

      if (jsonArray != null) {
        tempBusList = new ArrayList<Bus>();
        for (int i = 0; i < jsonArray.length(); i++) {
          try {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Log.v(TAG, "From JSON - " + jsonObject.getString("price"));

            int id = i + 1;
            Bus tempBus =
                new Bus(
                    id,
                    jsonObject.getString("busDetails"),
                    jsonObject.getInt("total"),
                    jsonObject.getInt("available"),
                    jsonObject.getDouble("price"),
                    jsonObject.getString("travelTime"),
                    jsonObject.getString("travelDate"));

            if (tempBus != null) {
              tempBusList.add(tempBus);
            }
          } catch (Exception e) {
            Log.v(TAG, "Error " + e.getMessage());
          }
        }
      }

      return tempBusList;
    }

    @Override
    protected void onPostExecute(List list) {
      super.onPostExecute(list);
      busList = list;
      if (busList != null) {
        Log.v(TAG, busList.get(1).getBusName());
        // TODO: Change Adapter to display your content

        setListAdapter(
            new ArrayAdapter<Bus>(
                getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, busList) {
              @Override
              public View getView(int pos, View v, ViewGroup vg) {
                TextView textView = (TextView) super.getView(pos, v, vg);
                /*
                SpannableStringBuilder builder = new SpannableStringBuilder();
                builder.append(textView.getText()+"  ")
                        .append(" ", new ImageSpan(getActivity(), R.drawable.arrow), 0);

                textView.setText(builder);
                */
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
                textView.setTextAppearance(getContext(), android.R.style.TextAppearance_Large);
                textView.setTextColor(getResources().getColor(R.color.westeros_red));
                return textView;
              }
            });
      }
    }
  }

  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
      mListener = (OnFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
      throw new ClassCastException(
          activity.toString() + " must implement OnFragmentInteractionListener");
    }
  }

  @Override
  public void onDetach() {
    super.onDetach();
    mListener = null;
  }

  public void setFromLocation(String fromLocation) {
    this.fromLocation = fromLocation;
  }

  public void setToLocation(String toLocation) {
    this.toLocation = toLocation;
  }

  public void setDate(String date) {
    this.date = date;
  }
}
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    Log.v(TAG, "Going to store session");
    SessionContext.storeSession(CredentialsStoreBuilder.StorageType.SHARED_PREFERENCES);
    Log.v(TAG, "session stored");
    _user = SessionContext.getLoggedUser();

    View view = inflater.inflate(R.layout.fragment_home, container, false);
    welcomeHomeId = (TextView) view.findViewById(R.id.welcomeHomeId);
    travelDate = (Button) view.findViewById(R.id.travelDateId);
    fromLocation = (Spinner) view.findViewById(R.id.fromLocationId);
    toLocation = (Spinner) view.findViewById(R.id.toLocationId);
    findBusesButton = (Button) view.findViewById(R.id.findBusId);
    findBusesButton.setOnClickListener(this);
    travelDate.setOnClickListener(this);

    if (_user != null) {
      Log.v(TAG, "In Home user is " + _user.getEmail());
      welcomeHomeId.setText("Welcome " + _user.getFirstName());
    }

    ArrayAdapter<Locations> fromLocationsAdapter =
        new ArrayAdapter<Locations>(
            getActivity(), android.R.layout.simple_spinner_item, Locations.fromLocationsArray);
    fromLocationsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    fromLocation.setAdapter(fromLocationsAdapter);
    fromLocation.setOnItemSelectedListener(
        new AdapterView.OnItemSelectedListener() {
          @Override
          public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Log.v(TAG, "From Drop down clicked ");
            Locations location = (Locations) parent.getItemAtPosition(position);
            Log.v(TAG, "Got location ");
            fromLocationId = location.getLocationId();
            Log.v(TAG, "Selected from location id is " + fromLocationId);
          }

          @Override
          public void onNothingSelected(AdapterView<?> parent) {}
        });

    ArrayAdapter<Locations> toLocationsAdapter =
        new ArrayAdapter<Locations>(
            getActivity(), android.R.layout.simple_spinner_item, Locations.toLocationsArray);
    toLocationsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    toLocation.setAdapter(toLocationsAdapter);
    toLocation.setOnItemSelectedListener(
        new AdapterView.OnItemSelectedListener() {
          @Override
          public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Locations location = (Locations) parent.getItemAtPosition(position);
            toLocationId = location.getLocationId();
            Log.v(TAG, "Selected to location id is " + toLocationId);
          }

          @Override
          public void onNothingSelected(AdapterView<?> parent) {}
        });

    return view;
  }
/** A simple {@link Fragment} subclass. */
public class HomeFragment extends Fragment implements View.OnClickListener {

  static String TAG = HomeFragment.class.getSimpleName();

  List<Bus> busList;
  User _user;
  HomeListener mHomeListener;

  TextView welcomeHomeId;
  Button findBusesButton;
  Button travelDate;
  Spinner fromLocation;
  Spinner toLocation;

  int fromLocationId;
  int toLocationId;

  Session session = SessionContext.createSessionFromCurrentSession();

  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    Log.v(TAG, "Going to store session");
    SessionContext.storeSession(CredentialsStoreBuilder.StorageType.SHARED_PREFERENCES);
    Log.v(TAG, "session stored");
    _user = SessionContext.getLoggedUser();

    View view = inflater.inflate(R.layout.fragment_home, container, false);
    welcomeHomeId = (TextView) view.findViewById(R.id.welcomeHomeId);
    travelDate = (Button) view.findViewById(R.id.travelDateId);
    fromLocation = (Spinner) view.findViewById(R.id.fromLocationId);
    toLocation = (Spinner) view.findViewById(R.id.toLocationId);
    findBusesButton = (Button) view.findViewById(R.id.findBusId);
    findBusesButton.setOnClickListener(this);
    travelDate.setOnClickListener(this);

    if (_user != null) {
      Log.v(TAG, "In Home user is " + _user.getEmail());
      welcomeHomeId.setText("Welcome " + _user.getFirstName());
    }

    ArrayAdapter<Locations> fromLocationsAdapter =
        new ArrayAdapter<Locations>(
            getActivity(), android.R.layout.simple_spinner_item, Locations.fromLocationsArray);
    fromLocationsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    fromLocation.setAdapter(fromLocationsAdapter);
    fromLocation.setOnItemSelectedListener(
        new AdapterView.OnItemSelectedListener() {
          @Override
          public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Log.v(TAG, "From Drop down clicked ");
            Locations location = (Locations) parent.getItemAtPosition(position);
            Log.v(TAG, "Got location ");
            fromLocationId = location.getLocationId();
            Log.v(TAG, "Selected from location id is " + fromLocationId);
          }

          @Override
          public void onNothingSelected(AdapterView<?> parent) {}
        });

    ArrayAdapter<Locations> toLocationsAdapter =
        new ArrayAdapter<Locations>(
            getActivity(), android.R.layout.simple_spinner_item, Locations.toLocationsArray);
    toLocationsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    toLocation.setAdapter(toLocationsAdapter);
    toLocation.setOnItemSelectedListener(
        new AdapterView.OnItemSelectedListener() {
          @Override
          public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Locations location = (Locations) parent.getItemAtPosition(position);
            toLocationId = location.getLocationId();
            Log.v(TAG, "Selected to location id is " + toLocationId);
          }

          @Override
          public void onNothingSelected(AdapterView<?> parent) {}
        });

    return view;
  }

  @Override
  public void onClick(View v) {
    int id = v.getId();
    Log.v(TAG, "Clicked " + id);
    if (id == R.id.findBusId) {
      if (this.fromLocationId == 0) {
        Toast.makeText(v.getContext(), "Please choose a starting point", Toast.LENGTH_SHORT).show();
      } else if (this.toLocationId == 0) {
        Toast.makeText(v.getContext(), "Please choose your final stop", Toast.LENGTH_SHORT).show();
      } else if (travelDate == null) {
        Toast.makeText(v.getContext(), "When do you want to travel ?", Toast.LENGTH_SHORT).show();
      } else {
        if (this.mHomeListener != null) {
          Log.v(TAG, "Data being passed is " + this.fromLocationId + " and " + this.toLocationId);
          this.mHomeListener.displayBuses(
              String.valueOf(this.fromLocationId),
              String.valueOf(this.toLocationId),
              travelDate.getText().toString());
        }
      }
    } else if (id == R.id.travelDateId) {
      Log.v(TAG, "In Date Picker");
      DatePickerFragment dialogFragment = new DatePickerFragment();
      dialogFragment.setTravelDateIdText(travelDate);
      dialogFragment.show(getFragmentManager(), "datePicker");
    }
  }

  static interface HomeListener {
    void displayBuses(String fromLocation, String toLocation, String date);
  }

  public HomeFragment() {
    // Required empty public constructor
  }

  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);
    mHomeListener = (HomeListener) activity;
  }
}