Ejemplo n.º 1
1
    private SegmentItem deserializeItem(JsonObject json, JsonDeserializationContext context) {
      if (!json.has("actions")) {
        throw new ProtectionParseException("Missing actions identifier");
      }

      SegmentItem segment = new SegmentItem();

      segment.types.addAll(
          deserializeAsArray(
              json.get("actions"),
              context,
              new TypeToken<ItemType>() {},
              new TypeToken<List<ItemType>>() {}.getType()));
      json.remove("actions");

      if (json.has("isAdjacent")) {
        segment.isAdjacent = json.get("isAdjacent").getAsBoolean();
        json.remove("isAdjacent");
      }

      if (json.has("clientUpdate")) {
        JsonObject jsonClientUpdate = json.get("clientUpdate").getAsJsonObject();
        segment.clientUpdate =
            new ClientBlockUpdate(
                (Volume) context.deserialize(jsonClientUpdate.get("coords"), Volume.class));
        if (jsonClientUpdate.has("directional")) {
          segment.directionalClientUpdate = jsonClientUpdate.get("directional").getAsBoolean();
        }
        json.remove("clientUpdate");
      }

      return segment;
    }
Ejemplo n.º 2
0
    private SegmentBlock deserializeBlock(JsonObject json, JsonDeserializationContext context) {
      if (!json.has("actions")) {
        throw new ProtectionParseException("Missing actions identifier");
      }
      SegmentBlock segment = new SegmentBlock();
      segment.types.addAll(
          deserializeAsArray(
              json.get("actions"),
              context,
              new TypeToken<BlockType>() {},
              new TypeToken<List<BlockType>>() {}.getType()));
      json.remove("actions");

      if (json.has("meta")) {
        segment.meta = json.get("meta").getAsInt();
        json.remove("meta");
      }

      if (json.has("clientUpdate")) {
        segment.clientUpdate =
            new ClientBlockUpdate(
                (Volume)
                    context.deserialize(
                        json.get("clientUpdate").getAsJsonObject().get("coords"), Volume.class));
        json.remove("clientUpdate");
      }

      return segment;
    }
  @Override
  public JsonObject upgrade(JsonObject unitGroup, Map<File, JsonObject> dbSnapshot)
      throws CouldNotPerformException {
    String newUnitType = unitTypeMap.get(unitGroup.get(UNIT_TYPE_FIELD).getAsString());
    unitGroup.remove(UNIT_TYPE_FIELD);
    unitGroup.addProperty(UNIT_TYPE_FIELD, newUnitType);

    JsonArray serviceTemplates = unitGroup.getAsJsonArray(SERVICE_TEMPLATE_FIELD);
    if (serviceTemplates != null) {
      JsonArray newServiceTemplates = new JsonArray();
      for (JsonElement serviceTemplateElem : serviceTemplates) {
        JsonObject serviceTemplate = serviceTemplateElem.getAsJsonObject();

        String oldServiceType = serviceTemplate.get(SERVICE_TYPE_FIELD).getAsString();
        String newServiceType = serviceTypeMap.get(oldServiceType);
        serviceTemplate.remove(SERVICE_TYPE_FIELD);
        serviceTemplate.addProperty(TYPE_FIELD, newServiceType);
        serviceTemplate.addProperty(PATTERN_FIELD, PROVIDER_PATTERN);
        newServiceTemplates.add(serviceTemplate);

        if (oldServiceType.endsWith("SERVICE")) {
          JsonObject operationServiceTemplate = new JsonObject();
          operationServiceTemplate.addProperty(TYPE_FIELD, newServiceType);
          operationServiceTemplate.addProperty(PATTERN_FIELD, OPERATION_PATTERN);
          operationServiceTemplate.add(META_CONFIG_FIELD, serviceTemplate.get(META_CONFIG_FIELD));
          newServiceTemplates.add(operationServiceTemplate);
        }
      }
      unitGroup.remove(SERVICE_TEMPLATE_FIELD);
      unitGroup.add(SERVICE_TEMPLATE_FIELD, newServiceTemplates);
    }

    return unitGroup;
  }
Ejemplo n.º 4
0
  /**
   * Create a configuration file based on the internally stored configuration.
   *
   * @return The StringBuffer object associated with the internal JSON configuration file.
   */
  private static StringBuffer create() {
    Logger.log("Creating default configuration file 'config.json'...", Logger.CRITICAL);
    StringBuffer fileData = getLocalConfig();

    try {
      JsonObject json = (JsonObject) new JsonParser().parse(fileData.toString());

      // # Remove config version from the output
      // # This config string will be used internally for
      // # tracking versions of cingif files when writing new ones
      // # or receiving new ones.
      json.remove("config-version");

      // # Write configuration file.
      FileOutputStream out = new FileOutputStream("config.json");
      out.write(json.toString().getBytes());
      out.close();

    } catch (JsonParseException e) {
      // # Should never get here because the config file is packaged internaly...
      // # If it fails, probably a developer not formatting the config file properly.
      Logger.log(
          "Compiling and creating the config file failed. Ensure you have properly formatted JSON data before recompiling your extension.",
          Logger.CRITICAL);
    } catch (IOException e) {
      Logger.log("Failed to write the configuration file: " + e.getMessage(), Logger.CRITICAL);
    }

    return fileData;
  }
Ejemplo n.º 5
0
    private SegmentSpecialBlock deserializeSpecialBlock(
        JsonObject json, JsonDeserializationContext context) {
      SegmentSpecialBlock segment = new SegmentSpecialBlock();

      if (json.has("meta")) {
        segment.meta = json.get("meta").getAsInt();
        json.remove("meta");
      }

      if (json.has("isAlwaysBreakable")) {
        segment.isAlwaysBreakable = json.get("isAlwaysBreakable").getAsBoolean();
        json.remove("isAlwaysBreakable");
      }

      return segment;
    }
Ejemplo n.º 6
0
  public boolean changeCartProductCount(Product product, int count) {
    try {
      Log.d(TAG, "changeCartProductCount: " + product.getArticle() + "  ||  " + count);
      if (count <= 0) {
        if (cartJson.has(product.getArticle() + "")) {
          cartJson.remove(product.getArticle() + "");
          if (setCartJson()) {
            return true;
          } else {
            return false;
          }
        }
        return true;
      }

      ProductCart productCart = getProductCart(product);
      if (productCart.setCount(count)) {
        cartJson.addProperty(productCart.getArticle() + "", productCart.getCount());
        if (setCartJson()) {
          return true;
        }
      }
    } catch (Exception e) {
      Log.e(TAG, "cart" + cartJson.toString() + "\n" + e.toString());
    }
    return false;
  }
Ejemplo n.º 7
0
 /**
  * Builds the start message.
  *
  * @param options the options
  * @return the request
  */
 private String buildStartMessage(RecognizeOptions options) {
   JsonObject startMessage =
       new JsonParser().parse(new Gson().toJson(options)).getAsJsonObject();
   startMessage.remove(MODEL);
   startMessage.addProperty(ACTION, START);
   return startMessage.toString();
 }
Ejemplo n.º 8
0
  @Override
  public void write(JsonWriter out, Patch<Data> value) throws IOException {
    JsonTreeWriter treeWriter = new JsonTreeWriter();
    treeWriter.setSerializeNulls(true);
    _dataAdapter.write(treeWriter, value.data());
    JsonObject tree = treeWriter.get().getAsJsonObject();

    Set<String> presentJsonProperties = new HashSet<>();
    for (Field field : value.changedFields()) {
      SerializedName nameSpecifier = field.getAnnotation(SerializedName.class);
      String jsonPropertyName = (nameSpecifier != null ? nameSpecifier.value() : field.getName());
      presentJsonProperties.add(jsonPropertyName);
    }

    for (Map.Entry<String, JsonElement> entry : new ArrayList<>(tree.entrySet())) {
      if (!presentJsonProperties.contains(entry.getKey())) {
        tree.remove(entry.getKey());
      }
    }

    // If a data field changed to null the null should be serialized.
    // This is the whole point of this adapter.
    ObjectTargetedJsonWriter patchWriter = new ObjectTargetedJsonWriter(out);
    patchWriter.setTargetedSerializeNulls(true);
    _gson.getAdapter(JsonObject.class).write(patchWriter, tree);
  }
  // AmbientColorAgents MetaConfig entries with pattern UNIT_(number)
  private void updateAmbientColorAgentMetaConfig(
      JsonArray metaConfigEntries, Map<File, DatabaseEntryDescriptor> dalUnitDB)
      throws CouldNotPerformException {
    JsonObject metaConfigEntry;
    String key, unitScope;
    for (JsonElement metaConfigEntryElem : metaConfigEntries) {
      metaConfigEntry = metaConfigEntryElem.getAsJsonObject();

      if (!metaConfigEntry.has(KEY_FIELD) || !metaConfigEntry.has(VALUE_FIELD)) {
        continue;
      }

      key = metaConfigEntry.get(KEY_FIELD).getAsString();
      if (key.matches("UNIT_[0123456789]+")) {
        unitScope = updateScopeToNewUnitTypes(metaConfigEntry.get(VALUE_FIELD).getAsString());
        if (!unitScopeIdMap.containsKey(unitScope)) {
          throw new CouldNotPerformException(
              "Could not replace scope ["
                  + unitScope
                  + "] with unit id in metaConfigEntry with key ["
                  + key
                  + "] of PowerStateSynchroniser");
        }
        metaConfigEntry.remove(VALUE_FIELD);
        metaConfigEntry.addProperty(VALUE_FIELD, unitScopeIdMap.get(unitScope));
      }
    }
  }
Ejemplo n.º 10
0
    private SegmentTileEntity deserializeTileEntity(
        JsonObject json, JsonDeserializationContext context) {
      SegmentTileEntity segment = new SegmentTileEntity();

      segment.retainsOwner = json.getAsJsonObject().get("retainsOwner").getAsBoolean();
      json.remove("retainsOwner");

      return segment;
    }
Ejemplo n.º 11
0
 @Override
 public BlockDefinition getBlockDefinitionForSection(JsonObject json, String sectionName) {
   if (json.has(sectionName) && json.get(sectionName).isJsonObject()) {
     JsonObject sectionJson = json.getAsJsonObject(sectionName);
     json.remove(sectionName);
     JsonMergeUtil.mergeOnto(json, sectionJson);
     return createBlockDefinition(sectionJson);
   }
   return null;
 }
Ejemplo n.º 12
0
  private JsonObject getResponse(HttpServletRequest request) throws IOException {
    JsonObject requestJSON = null;
    if (request.getInputStream() != null) {
      BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream()));
      StringBuilder s = new StringBuilder();
      String line;
      while ((line = rd.readLine()) != null) {
        s.append(line);
      }
      rd.close();
      String json = s.toString();
      if (!"".equals(json)) {
        requestJSON = new JsonParser().parse(json).getAsJsonObject();
      }
    }

    JsonObject res = new JsonObject();
    res.addProperty("success", false);

    // the id can be specified via a param, or in the json request.
    String session;
    if (requestJSON == null) {
      session = request.getParameter("session");
    } else {
      if (!requestJSON.has("session")) {
        res.addProperty(
            "msg",
            "you need to specify at least a session or internalKey when call the test slot status service.");
        return res;
      }
      session = requestJSON.get("session").getAsString();
    }

    TestSession testSession = getRegistry().getSession(ExternalSessionKey.fromString(session));

    if (testSession == null) {
      res.addProperty(
          "msg", "Cannot find test slot running session " + session + " in the registry.");
      return res;
    }
    res.addProperty("msg", "slot found !");
    res.remove("success");
    res.addProperty("success", true);
    res.addProperty("session", testSession.getExternalKey().getKey());
    res.addProperty("internalKey", testSession.getInternalKey());
    res.addProperty("inactivityTime", testSession.getInactivityTime());
    RemoteProxy p = testSession.getSlot().getProxy();
    res.addProperty("proxyId", p.getId());
    return res;
  }
 /**
  * do a PUT request on the StackMob platform, treating some of the fields as counters to be
  * incremented rather than as values to set
  *
  * @param path the path to put
  * @param id the id of the object to put
  * @param requestObject the object to serialize and send in the PUT body. this object will be
  *     serialized with Gson
  * @param counterFields a list of the fields in the object to be treated as counters being
  *     incremented
  * @param callback callback to be called when the server returns. may execute in a separate thread
  */
 public void putAndUpdateAtomicCounters(
     String path,
     String id,
     Object requestObject,
     List<String> counterFields,
     StackMobRawCallback callback) {
   JsonObject obj = new Gson().toJsonTree(requestObject).getAsJsonObject();
   for (Map.Entry<String, JsonElement> field :
       new HashSet<Map.Entry<String, JsonElement>>(obj.entrySet())) {
     if (counterFields.contains(field.getKey())) {
       obj.remove(field.getKey());
       obj.add(field.getKey() + "[inc]", field.getValue());
     }
   }
   put(path, id, obj.toString(), callback);
 }
  private static JsonObject removeSystemProperties(JsonObject instance) {
    boolean haveCloned = false;

    for (Entry<String, JsonElement> property : instance.entrySet()) {
      if (property.getKey().startsWith("__")) {
        if (!haveCloned) {
          instance = (JsonObject) new JsonParser().parse(instance.toString());
          haveCloned = true;
        }

        instance.remove(property.getKey());
      }
    }

    return instance;
  }
Ejemplo n.º 15
0
    private SegmentEntity deserializeEntity(JsonObject json, JsonDeserializationContext context) {
      if (!json.has("actions")) {
        throw new ProtectionParseException("Missing actions identifier");
      }

      SegmentEntity segment = new SegmentEntity();

      segment.types.addAll(
          deserializeAsArray(
              json.get("actions"),
              context,
              new TypeToken<EntityType>() {},
              new TypeToken<List<EntityType>>() {}.getType()));
      json.remove("actions");

      return segment;
    }
Ejemplo n.º 16
0
  public String getCartPrice(Context context) {
    float price = 0;
    for (Map.Entry<String, JsonElement> item : cartJson.entrySet()) {
      try {
        ProductCart product = getProductCart(dataWorker.getProduct(Integer.valueOf(item.getKey())));
        price += product.getPrice() * product.getCount();
      } catch (Exception e) {
        Log.e(TAG, e.toString());
        cartJson.remove(item.getKey());
        setCartJson();
      }
    }

    price = price / 100 * (100 - SharedPreferencesHelper.getDiscount(context));

    int mod = Math.round(price * 100) % 100;
    return (int) price + "." + (mod > 9 ? mod : "0" + mod);
  }
Ejemplo n.º 17
0
 public ArrayList<Product> getCartList() {
   ArrayList<Product> products = new ArrayList<>();
   for (Map.Entry<String, JsonElement> item : cartJson.entrySet()) {
     try {
       products.add(dataWorker.getProduct(Integer.valueOf(item.getKey())));
     } catch (Exception e) {
       Log.e(TAG, e.toString());
       cartJson.remove(item.getKey());
       setCartJson();
     }
   }
   Collections.sort(
       products,
       new Comparator<Product>() {
         @Override
         public int compare(Product product1, Product product2) {
           return product1.getTitle().compareTo(product2.getTitle());
         }
       });
   return products;
 }
Ejemplo n.º 18
0
 /**
  * Validate put request Json for Set Password API.
  *
  * @param requestBody the request Json object
  * @return true, if successful
  */
 private boolean validatePut(final JsonObject requestBody) {
   LOG.trace("Start UserResourceValidator#validatePut()");
   boolean isValid = false;
   // validation for password
   setInvalidParameter(VtnServiceJsonConsts.PASSWORD);
   if (requestBody.has(VtnServiceJsonConsts.PASSWORD)
       && requestBody.get(VtnServiceJsonConsts.PASSWORD) instanceof JsonObject
       && requestBody
               .get(VtnServiceJsonConsts.PASSWORD)
               .getAsJsonObject()
               .getAsJsonPrimitive(VtnServiceJsonConsts.PASSWORD)
               .getAsString()
           != null) {
     final String password =
         requestBody
             .get(VtnServiceJsonConsts.PASSWORD)
             .getAsJsonObject()
             .get(VtnServiceJsonConsts.PASSWORD)
             .getAsString();
     requestBody.remove(VtnServiceJsonConsts.PASSWORD);
     requestBody.addProperty(VtnServiceJsonConsts.PASSWORD, password);
   }
   if (requestBody.has(VtnServiceJsonConsts.PASSWORD)
       && requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.PASSWORD).getAsString() != null
       && !requestBody
           .getAsJsonPrimitive(VtnServiceJsonConsts.PASSWORD)
           .getAsString()
           .trim()
           .isEmpty()) {
     isValid =
         validator.isValidMaxLength(
             requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.PASSWORD).getAsString().trim(),
             VtnServiceJsonConsts.LEN_72);
   } else {
     isValid = false;
   }
   LOG.trace("Complete UserResourceValidator#validatePut()");
   return isValid;
 }
Ejemplo n.º 19
0
    @Override
    public Image deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)
        throws JsonParseException {
      JsonObject json = jsonElement.getAsJsonObject();
      Map<String, String> metadata = null;
      List<BlockDeviceMapping> blockDeviceMapping = null;

      JsonElement meta = json.get(METADATA);
      if (meta != null && meta.isJsonObject()) {
        metadata = Maps.newTreeMap();
        for (Map.Entry<String, JsonElement> e : meta.getAsJsonObject().entrySet()) {
          Object value;
          if (e.getValue().isJsonArray()) {
            value = context.deserialize(e.getValue().getAsJsonArray(), ArrayList.class);
          } else if (e.getValue().isJsonObject()) {
            value = context.deserialize(e.getValue().getAsJsonObject(), TreeMap.class);
          } else if (e.getValue().isJsonPrimitive()) {
            value = e.getValue().getAsJsonPrimitive().getAsString();
          } else {
            continue;
          }

          // keep non-string members out of normal metadata
          if (value instanceof String) {
            metadata.put(e.getKey(), (String) value);
          } else if (value instanceof List && BLOCK_DEVICE_MAPPING.equals(e.getKey())) {
            blockDeviceMapping =
                context.deserialize(
                    e.getValue(), new TypeToken<List<BlockDeviceMapping>>() {}.getType());
          }
        }
        json.remove(METADATA);
      }

      return apply(
          context.<ImageInternal>deserialize(json, ImageInternal.class),
          metadata,
          blockDeviceMapping);
    }
    @Override
    public T read(JsonReader in) throws IOException {
      JsonObject el = Streams.parse(in).getAsJsonObject();

      // Strip existing json schedules
      JsonObject directSchedules =
          el.has(SCHEDULES_FIELD_NAME)
              ? el.remove(SCHEDULES_FIELD_NAME).getAsJsonObject()
              : new JsonObject();

      // Strip off @schedule annotations to update schedules attribute
      // Load annotated schedules
      JsonObject annotatedSchedules = new JsonObject();
      // TODO: make this recursive to have nested schedules with dot notation
      for (Map.Entry<String, JsonElement> entry : el.entrySet()) {
        JsonElement entryEl = entry.getValue();
        if (entryEl.isJsonObject()) {
          JsonObject subConfig = entryEl.getAsJsonObject();
          if (subConfig.has(SCHEDULE)) {
            JsonElement scheduleConfig = subConfig.remove(SCHEDULE);
            annotatedSchedules.add(entry.getKey(), scheduleConfig);
          }
        }
      }

      T result = delegateAdapter.read(new JsonTreeReader(el));

      // If there is a 'schedules' field, inject schedules
      Field schedulesField = AnnotationUtil.getField(SCHEDULES_FIELD_NAME, result.getClass());
      if (schedulesField != null) {
        ///// Default schedules for every schedulable top level object
        JsonObject defaultSchedules = new JsonObject();
        List<Field> fields = new ArrayList<Field>();
        for (Field field : AnnotationUtil.getAllFields(fields, result.getClass())) {
          DefaultSchedule defaultSchedule = field.getAnnotation(DefaultSchedule.class);
          if (defaultSchedule == null) {
            boolean currentAccessibility = field.isAccessible();
            try {
              field.setAccessible(true);
              Object fieldValue = field.get(result);
              if (fieldValue != null) {
                Class<?> fieldRuntimeClass = field.get(result).getClass();
                defaultSchedule = fieldRuntimeClass.getAnnotation(DefaultSchedule.class);
              }
            } catch (IllegalArgumentException e) {
              Log.e(LogUtil.TAG, "Bad access of configurable fields!!", e);
            } catch (IllegalAccessException e) {
              Log.e(LogUtil.TAG, "Bad access of configurable fields!!", e);
            } finally {
              field.setAccessible(currentAccessibility);
            }
          }
          if (defaultSchedule != null) {
            defaultSchedules.add(
                field.getName(), gson.toJsonTree(defaultSchedule, DefaultSchedule.class));
          }
        }

        JsonObject schedulesJson = directSchedules;
        JsonUtils.deepCopyOnto(
            defaultSchedules,
            schedulesJson,
            false); // Copy in default schedules, but do not replace
        JsonUtils.deepCopyOnto(
            annotatedSchedules, schedulesJson, true); // Override with annotations

        // For each schedule find default schedule, fill in remainder
        Map<String, Schedule> schedules =
            gson.fromJson(schedulesJson, new TypeToken<Map<String, Schedule>>() {}.getType());

        boolean currentAccessibility = schedulesField.isAccessible();
        try {
          schedulesField.setAccessible(true);
          schedulesField.set(result, schedules);
        } catch (IllegalArgumentException e) {
          Log.e(LogUtil.TAG, "Bad access of configurable fields!!", e);
        } catch (IllegalAccessException e) {
          Log.e(LogUtil.TAG, "Bad access of configurable fields!!", e);
        } finally {
          schedulesField.setAccessible(currentAccessibility);
        }
      }

      return result;
    }
Ejemplo n.º 21
0
 /**
  * method used to clear the changes object.
  *
  * <p>It should be used after the changes have been saved to the database
  *
  * @private
  */
 private void clearChanges() {
   for (Entry<String, JsonElement> pairs : this.changes.entrySet()) {
     changes.remove(pairs.getKey());
   }
 }
  /**
   * @param requestBody , for request
   * @param opFlag , for getting option1 type
   * @return true , if parameter are in correct format values
   */
  public final boolean isValidGetForMappingIdIndex(
      final JsonObject requestBody, final boolean opFlag) {
    LOG.trace("Start CommonValidator#isValidGetForMappingIdIndex");
    boolean isValid = true;

    // validation for key: targetdb
    setInvalidParameter(VtnServiceJsonConsts.TARGETDB);
    isValid = validator.isValidRequestDBState(requestBody);

    /*
     * Remove unwanted parameters from request body for Show APIs
     */
    if (!opFlag) {
      if (requestBody.has(VtnServiceJsonConsts.OP)) {
        requestBody.remove(VtnServiceJsonConsts.OP);
      } else {
        LOG.debug("No need to remove");
      }
      if (requestBody.has(VtnServiceJsonConsts.INDEX)) {
        requestBody.remove(VtnServiceJsonConsts.INDEX);
      } else {
        LOG.debug("No need to remove");
      }
      if (requestBody.has(VtnServiceJsonConsts.MAX)) {
        requestBody.remove(VtnServiceJsonConsts.MAX);
      } else {
        LOG.debug("No need to remove");
      }
    } else {
      // validation for key: op
      if (isValid) {
        setInvalidParameter(VtnServiceJsonConsts.OP);
        isValid = validator.isValidOperationForDetail(requestBody);
      }
      // validation for key: index where index is combination of
      // controller id and domain id
      if (isValid) {
        setInvalidParameter(VtnServiceJsonConsts.INDEX);
        if (requestBody.has(VtnServiceJsonConsts.INDEX)
            && requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.INDEX).getAsString() != null) {
          final String[] mappingId =
              requestBody
                  .getAsJsonPrimitive(VtnServiceJsonConsts.INDEX)
                  .getAsString()
                  .split(VtnServiceJsonConsts.HYPHEN);
          isValid = validator.isValidMappingId(mappingId);
        }
      }
      // validation for key: max_repitition
      if (isValid) {
        setInvalidParameter(VtnServiceJsonConsts.MAX);
        isValid = validator.isValidMaxRepetition(requestBody);
      }

      // validation for key: vnode_type
      if (isValid) {
        setInvalidParameter(VtnServiceJsonConsts.VNODETYPE);
        if (requestBody.has(VtnServiceJsonConsts.VNODETYPE)
            && requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.VNODETYPE).getAsString()
                != null) {
          final String vnodeType =
              requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.VNODETYPE).getAsString();
          isValid = validator.isValidVnodeType(vnodeType);
        }
      }

      // validation for key: vnode_name
      if (isValid) {
        setInvalidParameter(VtnServiceJsonConsts.VNODENAME);
        if (requestBody.has(VtnServiceJsonConsts.VNODENAME)
            && requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.VNODENAME).getAsString()
                != null) {
          final String vnodeName =
              requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.VNODENAME).getAsString();
          isValid = validator.isValidMaxLengthAlphaNum(vnodeName, VtnServiceJsonConsts.LEN_31);
        }
      }

      // validation for key: if_name
      if (isValid) {
        setInvalidParameter(VtnServiceJsonConsts.VIFNAME);
        if (requestBody.has(VtnServiceJsonConsts.VIFNAME)
            && requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.VIFNAME).getAsString() != null) {
          final String ifName =
              requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.VIFNAME).getAsString();
          isValid = validator.isValidMaxLengthAlphaNum(ifName, VtnServiceJsonConsts.LEN_31);
        }
      }
    }
    LOG.trace("Complete CommonValidator#isValidGetForMappingIdIndex");
    return isValid;
  }
Ejemplo n.º 23
0
    @Override
    public Segment deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
      if (!json.getAsJsonObject().has("class")) {
        throw new ProtectionParseException("One of the segments is missing a class identifier");
      }

      JsonObject jsonObject = json.getAsJsonObject();
      String classString = jsonObject.get("class").getAsString();

      if (!json.getAsJsonObject().has("type")) {
        throw new ProtectionParseException("Segment for " + classString + " is missing a type");
      }
      String type = jsonObject.get("type").getAsString();
      jsonObject.remove("type");

      Segment segment = null;
      if ("specialBlock".equals(type)) {
        segment = deserializeSpecialBlock(jsonObject, context);
      } else if ("block".equals(type)) {
        segment = deserializeBlock(jsonObject, context);
      } else if ("entity".equals(type)) {
        segment = deserializeEntity(jsonObject, context);
      } else if ("item".equals(type)) {
        segment = deserializeItem(jsonObject, context);
      } else if ("tileEntity".equals(type)) {
        segment = deserializeTileEntity(jsonObject, context);
      }

      if (segment == null) {
        throw new ProtectionParseException("Identifier type is invalid");
      }

      try {
        segment.checkClass = Class.forName(classString);
      } catch (ClassNotFoundException ex) {
        // throw new ProtectionParseException("Invalid class identifier: " + classString);
        MyTown.instance.LOG.error(
            "Invalid class identifier {" + classString + "}: >>> Segment Rejected <<<");
        return null;
      }
      jsonObject.remove("class");

      if (!(segment instanceof SegmentSpecialBlock)) {
        if (!json.getAsJsonObject().has("flags")) {
          throw new ProtectionParseException("Segment for " + classString + " is missing flags");
        }
        segment.flags.addAll(
            deserializeAsArray(
                jsonObject.get("flags"),
                context,
                new TypeToken<FlagType<Boolean>>() {},
                new TypeToken<List<FlagType<Boolean>>>() {}.getType()));
        jsonObject.remove("flags");

        if (jsonObject.has("condition")) {
          segment.condition = new Condition(jsonObject.get("condition").getAsString());
          jsonObject.remove("condition");
        }

        if (jsonObject.has("priority")) {
          segment.priority = Priority.valueOf(jsonObject.get("priority").getAsString());
          jsonObject.remove("priority");
        }

        for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
          Getter getter = context.deserialize(entry.getValue(), Getter.class);
          getter.setName(entry.getKey());
          segment.getters.add(getter);
        }
      }

      return segment;
    }