All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.parse.ParseIncrementOperation Maven / Gradle / Ivy

Go to download

A library that gives you access to the powerful Parse cloud platform from your Android app.

There is a newer version: 1.17.3
Show newest version
/*
 * Copyright (c) 2015-present, Parse, LLC.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
package com.parse;

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

/**
 * An operation that increases a numeric field's value by a given amount.
 */
/** package */ class ParseIncrementOperation implements ParseFieldOperation {
  private final Number amount;

  public ParseIncrementOperation(Number amount) {
    this.amount = amount;
  }

  @Override
  public JSONObject encode(ParseEncoder objectEncoder) throws JSONException {
    JSONObject output = new JSONObject();
    output.put("__op", "Increment");
    output.put("amount", amount);
    return output;
  }

  @Override
  public ParseFieldOperation mergeWithPrevious(ParseFieldOperation previous) {
    if (previous == null) {
      return this;
    } else if (previous instanceof ParseDeleteOperation) {
      return new ParseSetOperation(amount);
    } else if (previous instanceof ParseSetOperation) {
      Object oldValue = ((ParseSetOperation) previous).getValue();
      if (oldValue instanceof Number) {
        return new ParseSetOperation(Numbers.add((Number) oldValue, amount));
      } else {
        throw new IllegalArgumentException("You cannot increment a non-number.");
      }
    } else if (previous instanceof ParseIncrementOperation) {
      Number oldAmount = ((ParseIncrementOperation) previous).amount;
      return new ParseIncrementOperation(Numbers.add(oldAmount, amount));
    } else {
      throw new IllegalArgumentException("Operation is invalid after previous operation.");
    }
  }

  @Override
  public Object apply(Object oldValue, String key) {
    if (oldValue == null) {
      return amount;
    } else if (oldValue instanceof Number) {
      return Numbers.add((Number) oldValue, amount);
    } else {
      throw new IllegalArgumentException("You cannot increment a non-number.");
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy