예제 #1
0
  /**
   * Both Model and Set are oplog-only; they never pass the state on the wire, only the oplog; new
   * replicas are booted with distilled oplog as well. So, this is the only point in the code that
   * mutates the state of a Set.
   */
  @SwarmOperation(kind = SwarmOperationKind.Logged)
  public void change(FullSpec spec, JsonValue value) throws SwarmException {
    value = this.distillOp(spec, value);
    if (!value.isObject()) return;

    JsonObject jo = (JsonObject) value;

    for (JsonObject.Member entry : jo) {
      String keySpecStr = entry.getName();
      TypeIdSpec key_spec = new TypeIdSpec(keySpecStr);
      JsonValue val = entry.getValue();
      if (TRUE.equals(val)) {
        T obj = this.host.get(key_spec);
        this.objects.put(key_spec, obj);
        obj.on(JsonValue.NULL, this.proxy);
      } else if (FALSE.equals(val)) {
        T obj = this.objects.get(key_spec);
        if (obj != null) {
          obj.off(this.proxy);
          this.objects.remove(key_spec);
        }
      } else {
        logger.warn("unexpected value: {}->{}", spec, value);
      }
    }
  }
예제 #2
0
 @Override
 public void getContactRequests(boolean fromWebsocket) throws ConnectionException {
   JsonArray array =
       Endpoints.AUTH_REQUESTS_URL
           .open(this)
           .as(JsonArray.class)
           .expect(200, "While loading authorization requests")
           .get();
   for (JsonValue contactRequest : array) {
     JsonObject contactRequestObj = contactRequest.asObject();
     try {
       ContactRequestImpl request =
           new ContactRequestImpl(
               contactRequestObj.get("event_time").asString(),
               getOrLoadContact(contactRequestObj.get("sender").asString()),
               contactRequestObj.get("greeting").asString(),
               this);
       if (!this.allContactRequests.contains(request)) {
         if (fromWebsocket) {
           ContactRequestEvent event = new ContactRequestEvent(request);
           getEventDispatcher().callEvent(event);
         }
         this.allContactRequests.add(request);
       }
     } catch (java.text.ParseException e) {
       getLogger().log(Level.WARNING, "Could not parse date for contact request", e);
     }
   }
   if (fromWebsocket) this.updateContactList();
 }
예제 #3
0
  @Test
  public void parse_handlesStringsThatExceedBufferSize() throws IOException {
    String input = "[ \"lorem ipsum dolor sit amet\" ]";

    JsonValue value = new JsonParser(new StringReader(input), 3).parse();

    assertEquals("[\"lorem ipsum dolor sit amet\"]", value.toString());
  }
예제 #4
0
  @Test
  public void parse_handlesInputsThatExceedBufferSize() throws IOException {
    String input = "[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 ]";

    JsonValue value = new JsonParser(new StringReader(input), 3).parse();

    assertEquals("[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47]", value.toString());
  }
예제 #5
0
  @Test
  public void parse_handlesNumbersThatExceedBufferSize() throws IOException {
    String input = "[ 3.141592653589 ]";

    JsonValue value = new JsonParser(new StringReader(input), 3).parse();

    assertEquals("[3.141592653589]", value.toString());
  }
예제 #6
0
  @Test
  public void numbers_minusZero() {
    // allowed by JSON, allowed by Java
    JsonValue value = parse("-0");

    assertEquals(0, value.asInt());
    assertEquals(0l, value.asLong());
    assertEquals(0f, value.asFloat(), 0);
    assertEquals(0d, value.asDouble(), 0);
  }
예제 #7
0
 @Override
 public int hashCode() {
   int result = 1;
   result = 31 * result + name.hashCode();
   result = 31 * result + value.hashCode();
   return result;
 }
예제 #8
0
 @Override
 public void updateContactList() throws ConnectionException {
   JsonObject obj =
       Endpoints.GET_ALL_CONTACTS
           .open(this, getUsername(), "notification")
           .as(JsonObject.class)
           .expect(200, "While loading contacts")
           .get();
   for (JsonValue value : obj.get("contacts").asArray()) {
     if (value.asObject().get("suggested") == null
         || !value.asObject().get("suggested").asBoolean()) {
       String id = value.asObject().get("id").asString();
       ContactImpl impl = (ContactImpl) allContacts.get(id);
       impl.update(value.asObject());
     }
   }
 }
예제 #9
0
 @Override
 public void loadAllContacts() throws ConnectionException {
   JsonObject object =
       Endpoints.GET_ALL_CONTACTS
           .open(this, getUsername(), "default")
           .as(JsonObject.class)
           .expect(200, "While loading contacts")
           .get();
   for (JsonValue value : object.get("contacts").asArray()) {
     JsonObject obj = value.asObject();
     if (obj.get("suggested") == null || !obj.get("suggested").asBoolean()) {
       if (!allContacts.containsKey(obj.get("id").asString())) {
         this.allContacts.put(obj.get("id").asString(), new ContactImpl(this, obj));
       }
     }
   }
 }
  /** Tests the result of the rest api single subject key GET when there is a config. */
  @Test
  public void testSingleSubjectKeyConfig() {
    setUpConfigData();
    final WebTarget wt = target();
    final String response = wt.path("network/configuration/devices").request().get(String.class);

    final JsonObject result = Json.parse(response).asObject();
    Assert.assertThat(result, notNullValue());

    Assert.assertThat(result.names(), hasSize(1));

    JsonValue device1 = result.asObject().get("device1");
    Assert.assertThat(device1, notNullValue());

    JsonValue basic = device1.asObject().get("basic");
    Assert.assertThat(basic, notNullValue());

    checkBasicAttributes(basic);
  }
예제 #11
0
  public static JsonValue removePaths(JsonValue jsonValue, Paths paths, Paths pathsToIgnore) {
    if (paths.matches(pathsToIgnore)) return JsonValue.NULL;

    if (jsonValue.isObject()) {
      paths = new Paths(paths);
      paths.extend("{}");

      if (paths.matches(pathsToIgnore)) return JsonValue.NULL;

      JsonObject jsonObject = new JsonObject();
      for (String name : jsonValue.asObject().names()) {
        Paths currentPaths = new Paths(paths);
        currentPaths.extend(name);
        jsonObject.set(
            name, removePaths(jsonValue.asObject().get(name), currentPaths, pathsToIgnore));
      }
      return jsonObject;
    }
    if (jsonValue.isArray()) {
      Paths currentPaths = new Paths(paths);
      currentPaths.extend("[]");

      if (currentPaths.matches(pathsToIgnore)) return JsonValue.NULL;

      JsonArray jsonArray = new JsonArray();
      for (int index = 0; index < jsonValue.asArray().size(); index++) {
        currentPaths = new Paths(paths);
        currentPaths.extend("[]", "[" + index + "]");

        jsonArray.add(removePaths(jsonValue.asArray().get(index), currentPaths, pathsToIgnore));
      }
      return jsonArray;
    }
    return jsonValue;
  }
 @Override
 protected void parseMember(JsonObject.Member member) {
   super.parseMember(member);
   try {
     JsonValue value = member.getValue();
     String memberName = member.getName();
     if ("roles".equals(memberName)) {
       this.writable =
           value
               .asArray()
               .values()
               .stream()
               .filter(JsonValue::isString)
               .map(JsonValue::asString)
               .anyMatch("write"::equalsIgnoreCase);
     } else if ("link".equals(memberName)) {
       link = new OneDriveSharingLink(value.asObject());
     } else if ("grantedTo".equals(memberName)) {
       grantedTo = new OneDriveIdentitySet(value.asObject());
     } else if ("inheritedFrom".equals(memberName)) {
       JsonObject valueObject = value.asObject();
       String id = valueObject.get("id").asString();
       OneDriveFolder inheritedFromFolder = new OneDriveFolder(getApi(), id);
       inheritedFrom = inheritedFromFolder.new Reference(valueObject);
     } else if ("shareId".equals(memberName)) {
       shareId = value.asString();
     }
   } catch (ParseException e) {
     throw new OneDriveRuntimeException("Parse failed, maybe a bug in client.", e);
   }
 }
예제 #13
0
  @Override
  public void generateBuildScript(Configuration cfg, Context ctx) {
    try {
      final InputStream input =
          this.getClass().getClassLoader().getResourceAsStream("javascript/lib/package.json");
      final List<String> packLines = IOUtils.readLines(input);
      String pack = "";
      for (String line : packLines) {
        pack += line + "\n";
      }
      input.close();
      pack = pack.replace("<NAME>", cfg.getName());

      final JsonObject json = JsonObject.readFrom(pack);
      final JsonValue deps = json.get("dependencies");
      for (Thing t : cfg.allThings()) {
        for (String dep : t.annotation("js_dep")) {
          deps.asObject().add(dep.split(":")[0].trim(), dep.split(":")[1].trim());
        }
      }

      for (Thing t : cfg.allThings()) {
        if (t.getStreams().size() > 0) {
          deps.asObject().add("rx", "^2.5.3");
          deps.asObject().add("events", "^1.0.2");
          break;
        }
      }

      final File f = new File(ctx.getOutputDirectory() + "/" + cfg.getName() + "/package.json");
      f.setWritable(true);
      final PrintWriter w = new PrintWriter(new FileWriter(f));
      w.println(json.toString());
      w.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 @Override
 protected void parseMember(JsonObject.Member member) {
   super.parseMember(member);
   try {
     JsonValue value = member.getValue();
     String memberName = member.getName();
     if ("small".equals(memberName)) {
       OneDriveThumbnail thumbnail = initThumbnail(OneDriveThumbnailSize.SMALL);
       small = thumbnail.new Metadata(value.asObject());
     } else if ("medium".equals(memberName)) {
       OneDriveThumbnail thumbnail = initThumbnail(OneDriveThumbnailSize.MEDIUM);
       medium = thumbnail.new Metadata(value.asObject());
     } else if ("large".equals(memberName)) {
       OneDriveThumbnail thumbnail = initThumbnail(OneDriveThumbnailSize.LARGE);
       large = thumbnail.new Metadata(value.asObject());
     } else if ("source".equals(memberName)) {
       OneDriveThumbnail thumbnail = initThumbnail(OneDriveThumbnailSize.SOURCE);
       source = thumbnail.new Metadata(value.asObject());
     }
   } catch (ParseException e) {
     throw new OneDriveRuntimeException("Parse failed, maybe a bug in client.", e);
   }
 }
예제 #15
0
 /**
  * Indicates whether a given object is "equal to" this JsonObject. An object is considered equal
  * if it is also a <code>JsonObject</code> and both objects contain the same members <em>in the
  * same order</em>.
  *
  * <p>If two JsonObjects are equal, they will also produce the same JSON output.
  *
  * @param object the object to be compared with this JsonObject
  * @return <tt>true</tt> if the specified object is equal to this JsonObject, <code>false</code>
  *     otherwise
  */
 @Override
 public boolean equals(Object object) {
   if (this == object) {
     return true;
   }
   if (object == null) {
     return false;
   }
   if (getClass() != object.getClass()) {
     return false;
   }
   Member other = (Member) object;
   return name.equals(other.name) && value.equals(other.value);
 }
예제 #16
0
 @Override
 public String validate(FullSpec spec, JsonValue val) {
   if (!CHANGE.equals(spec.getOp())) {
     return VALID;
   }
   if (val.isObject()) {
     JsonObject jo = (JsonObject) val;
     for (String keySpecStr : jo.names()) {
       // member spec validity
       try {
         new TypeIdSpec(keySpecStr);
       } catch (IllegalArgumentException e) {
         return "invalid spec: " + keySpecStr;
       }
     }
   }
   return VALID;
 }
예제 #17
0
 /**
  * Returns the <code>float</code> value of the member with the specified name in this object. If
  * this object does not contain a member with this name, the given default value is returned. If
  * this object contains multiple members with the given name, the last one will be picked. If this
  * member's value does not represent a JSON number or if it cannot be interpreted as Java <code>
  * float</code>, an exception is thrown.
  *
  * @param name the name of the member whose value is to be returned
  * @param defaultValue the value to be returned if the requested member is missing
  * @return the value of the last member with the specified name, or the given default value if
  *     this object does not contain a member with that name
  */
 public float getFloat(String name, float defaultValue) {
   JsonValue value = get(name);
   return value != null ? value.asFloat() : defaultValue;
 }
예제 #18
0
/**
 * Created with IntelliJ IDEA.
 *
 * @author aleksisha Date: 05.09.2014 Time: 00:48
 */
@SwarmType("Set")
public class SyncSet<T extends Syncable> extends Syncable {

  public static final OpToken CHANGE = new OpToken(".change");
  public static final String VALID = "";

  public static final JsonValue TRUE = JsonValue.valueOf(1);
  public static final JsonValue FALSE = JsonValue.valueOf(0);

  private final Map<TypeIdSpec, T> objects = new HashMap<TypeIdSpec, T>();
  private final ProxyListener proxy = new ProxyListener(this);

  public SyncSet(IdToken id, Host host) throws SwarmException {
    super(id, host);
    this.logDistillator = new ModelLogDistillator();
  }

  /**
   * Both Model and Set are oplog-only; they never pass the state on the wire, only the oplog; new
   * replicas are booted with distilled oplog as well. So, this is the only point in the code that
   * mutates the state of a Set.
   */
  @SwarmOperation(kind = SwarmOperationKind.Logged)
  public void change(FullSpec spec, JsonValue value) throws SwarmException {
    value = this.distillOp(spec, value);
    if (!value.isObject()) return;

    JsonObject jo = (JsonObject) value;

    for (JsonObject.Member entry : jo) {
      String keySpecStr = entry.getName();
      TypeIdSpec key_spec = new TypeIdSpec(keySpecStr);
      JsonValue val = entry.getValue();
      if (TRUE.equals(val)) {
        T obj = this.host.get(key_spec);
        this.objects.put(key_spec, obj);
        obj.on(JsonValue.NULL, this.proxy);
      } else if (FALSE.equals(val)) {
        T obj = this.objects.get(key_spec);
        if (obj != null) {
          obj.off(this.proxy);
          this.objects.remove(key_spec);
        }
      } else {
        logger.warn("unexpected value: {}->{}", spec, value);
      }
    }
  }

  // should be generated?
  public void change(JsonObject changes) throws SwarmException {
    this.deliver(this.newEventSpec(CHANGE), changes, NOOP);
  }

  public void onObjects(OpRecipient callback) {
    this.proxy.on(callback);
  }

  public void offObjects(OpRecipient callback) {
    this.proxy.off(callback);
  }

  @Override
  public String validate(FullSpec spec, JsonValue val) {
    if (!CHANGE.equals(spec.getOp())) {
      return VALID;
    }
    if (val.isObject()) {
      JsonObject jo = (JsonObject) val;
      for (String keySpecStr : jo.names()) {
        // member spec validity
        try {
          new TypeIdSpec(keySpecStr);
        } catch (IllegalArgumentException e) {
          return "invalid spec: " + keySpecStr;
        }
      }
    }
    return VALID;
  }

  JsonValue distillOp(FullSpec spec, JsonValue val) {
    if (this.version == null
        || this.version.compareTo(spec.getVersion().toString()) < 0) { // TODO check condition
      return val; // no concurrent op
    }
    VersionOpSpec opkey = spec.getVersionOp();
    this.oplog.put(opkey, val);
    this.distillLog(); // may amend the value
    val = this.oplog.get(opkey);
    return (val == null ? JsonValue.NULL : val);
  }

  /**
   * Adds an object to the set.
   *
   * @param obj the object //TODO , its id or its specifier.
   */
  public void add(T obj) throws SwarmException {
    final TypeIdSpec key_spec = obj.getTypeId();
    JsonObject changes = new JsonObject();
    changes.set(key_spec.toString(), TRUE);
    change(changes);
  }

  public void add(TypeIdSpec typeId) throws SwarmException {
    JsonObject changes = new JsonObject();
    changes.set(typeId.toString(), TRUE);
    change(changes);
  }

  // FIXME reactions to emit .add, .remove

  public void remove(TypeIdSpec key_spec) throws SwarmException {
    JsonObject changes = new JsonObject();
    changes.set(key_spec.toString(), FALSE);
    change(changes);
  }

  public void remove(T obj) throws SwarmException {
    remove(obj.getTypeId());
  }

  /**
   * @param key_spec key (specifier)
   * @return object by key
   */
  public T get(TypeIdSpec key_spec) {
    return this.objects.get(key_spec);
  }

  /**
   * @param order ordering
   * @return sorted list of objects currently in set
   */
  public List<T> list(Comparator<T> order) {
    List<T> ret = this.list();
    Collections.sort(ret, order);
    return ret;
  }

  public List<T> list() {
    return new ArrayList<T>(this.objects.values());
  }
}
예제 #19
0
 public static JsonArray getArray(JsonObject obj, String name) {
   JsonValue value = obj.get(name);
   return value != null ? value.asArray() : null;
 }
예제 #20
0
 /**
  * Reads a JSON array from the given reader.
  *
  * <p>Characters are read in chunks and buffered internally, therefore wrapping an existing reader
  * in an additional <code>BufferedReader</code> does <strong>not</strong> improve reading
  * performance.
  *
  * @param reader the reader to read the JSON array from
  * @return the JSON array that has been read
  * @throws IOException if an I/O error occurs in the reader
  * @throws ParseException if the input is not valid JSON
  * @throws UnsupportedOperationException if the input does not contain a JSON array
  * @deprecated Use {@link Json#parse(Reader)}{@link JsonValue#asArray() .asArray()} instead
  */
 @Deprecated
 public static JsonArray readFrom(Reader reader) throws IOException {
   return JsonValue.readFrom(reader).asArray();
 }
예제 #21
0
 /**
  * Reads a JSON array from the given string.
  *
  * @param string the string that contains the JSON array
  * @return the JSON array that has been read
  * @throws ParseException if the input is not valid JSON
  * @throws UnsupportedOperationException if the input does not contain a JSON array
  * @deprecated Use {@link Json#parse(String)}{@link JsonValue#asArray() .asArray()} instead
  */
 @Deprecated
 public static JsonArray readFrom(String string) {
   return JsonValue.readFrom(string).asArray();
 }
예제 #22
0
 /**
  * Returns the <code>String</code> value of the member with the specified name in this object. If
  * this object does not contain a member with this name, the given default value is returned. If
  * this object contains multiple members with the given name, the last one is picked. If this
  * member's value does not represent a JSON string, an exception is thrown.
  *
  * @param name the name of the member whose value is to be returned
  * @param defaultValue the value to be returned if the requested member is missing
  * @return the value of the last member with the specified name, or the given default value if
  *     this object does not contain a member with that name
  */
 public String getString(String name, String defaultValue) {
   JsonValue value = get(name);
   return value != null ? value.asString() : defaultValue;
 }
예제 #23
0
 public static Integer getInteger(JsonObject obj, String name) {
   JsonValue value = obj.get(name);
   return value != null ? value.asInt() : null;
 }
예제 #24
0
 /**
  * Returns the <code>boolean</code> value of the member with the specified name in this object. If
  * this object does not contain a member with this name, the given default value is returned. If
  * this object contains multiple members with the given name, the last one will be picked. If this
  * member's value does not represent a JSON <code>true</code> or <code>false</code> value, an
  * exception is thrown.
  *
  * @param name the name of the member whose value is to be returned
  * @param defaultValue the value to be returned if the requested member is missing
  * @return the value of the last member with the specified name, or the given default value if
  *     this object does not contain a member with that name
  */
 public boolean getBoolean(String name, boolean defaultValue) {
   JsonValue value = get(name);
   return value != null ? value.asBoolean() : defaultValue;
 }
 private void checkBasicAttributes(JsonValue basic) {
   Assert.assertThat(basic.asObject().get("field1").asString(), is("v1"));
   Assert.assertThat(basic.asObject().get("field2").asString(), is("v2"));
 }
예제 #26
0
 /**
  * Reads a JSON object from the given reader.
  *
  * @param reader the reader to read the JSON object from
  * @return the JSON object that has been read
  * @throws IOException if an I/O error occurs in the reader
  * @throws ParseException if the input is not valid JSON
  * @throws UnsupportedOperationException if the input does not contain a JSON object
  */
 public static JsonObject readFrom(Reader reader) throws IOException {
   return JsonValue.readFrom(reader).asObject();
 }
예제 #27
0
 /**
  * Returns the <code>int</code> value of the member with the specified name in this object. If
  * this object does not contain a member with this name, the given default value is returned. If
  * this object contains multiple members with the given name, the last one will be picked. If this
  * member's value does not represent a JSON number or if it cannot be interpreted as Java <code>
  * int</code>, an exception is thrown.
  *
  * @param name the name of the member whose value is to be returned
  * @param defaultValue the value to be returned if the requested member is missing
  * @return the value of the last member with the specified name, or the given default value if
  *     this object does not contain a member with that name
  */
 public int getInt(String name, int defaultValue) {
   JsonValue value = get(name);
   return value != null ? value.asInt() : defaultValue;
 }
예제 #28
0
 public static Boolean getBoolean(JsonObject obj, String name) {
   JsonValue value = obj.get(name);
   return value != null ? value.asBoolean() : null;
 }
예제 #29
0
 /**
  * Reads a JSON object from the given string.
  *
  * @param string the string that contains the JSON object
  * @return the JSON object that has been read
  * @throws ParseException if the input is not valid JSON
  * @throws UnsupportedOperationException if the input does not contain a JSON object
  */
 public static JsonObject readFrom(String string) {
   return JsonValue.readFrom(string).asObject();
 }
예제 #30
0
 /**
  * Returns the <code>double</code> value of the member with the specified name in this object. If
  * this object does not contain a member with this name, the given default value is returned. If
  * this object contains multiple members with the given name, the last one will be picked. If this
  * member's value does not represent a JSON number or if it cannot be interpreted as Java <code>
  * double</code>, an exception is thrown.
  *
  * @param name the name of the member whose value is to be returned
  * @param defaultValue the value to be returned if the requested member is missing
  * @return the value of the last member with the specified name, or the given default value if
  *     this object does not contain a member with that name
  */
 public double getDouble(String name, double defaultValue) {
   JsonValue value = get(name);
   return value != null ? value.asDouble() : defaultValue;
 }