Esempio n. 1
0
 @Override
 public final JsonValue asJson() {
   JsonObjectBuilder builder = JsonUtils.createObjectBuilder();
   JsonUtils.add(builder, TYPE_PROPERTY, getElementType());
   addJsonProperties(builder);
   return builder.build();
 }
Esempio n. 2
0
  public static String Group(String user, String channel) {
    String group = "None :<";

    try {
      Perms perm = Main.map.get(channel);

      if (perm.getPermission().getMods().contains(user)) group = "Moderator";

      if (perm.getPermission().getAdmins().contains(user)) group = "Admin";

      String Exec = JsonUtils.getStringFromFile(Main.jsonFilePath.toString());
      JsonObject exec = JsonUtils.getJsonObject(Exec);
      for (String users :
          exec.getAsJsonObject("Perms")
              .get("Exec")
              .toString()
              .replaceAll("[\\[\\]\"]", "")
              .split(",")) {
        if (users.equalsIgnoreCase(user)) return "Exec";
      }

    } catch (IOException e) {
      e.printStackTrace();
    }

    return group;
  }
Esempio n. 3
0
 @Override
 protected void addTurnProperties(JsonObjectBuilder builder) {
   super.addTurnProperties(builder);
   JsonUtils.addDurationProperty(builder, CONNECT_TIMEOUT_PROPERTY, mConnectTimeout);
   JsonUtils.add(builder, TRANSFER_AUDIO_PROPERTY, mTransferAudio);
   JsonUtils.add(builder, DTMF_RECOGNITION_PROPERTY, mDtmfRecognition);
   JsonUtils.add(builder, SPEECH_RECOGNITION_PROPERTY, mSpeechRecognition);
 }
Esempio n. 4
0
 @Override
 public JsonValue asJson() {
   JsonObjectBuilder builder = JsonUtils.createObjectBuilder();
   JsonUtils.add(builder, NAME_PROPERTY, mName);
   JsonUtils.add(builder, EXPRESSION_PROPERTY, mExpression);
   JsonUtils.add(builder, VALUE_PROPERTY, mValue);
   return builder.build();
 }
Esempio n. 5
0
 @Override
 protected void addTurnProperties(JsonObjectBuilder builder) {
   JsonUtils.add(builder, DESTINATION_PROPERTY, mDestination);
   JsonUtils.add(
       builder,
       APPLICATION_TO_APPLICATION_INFORMATION_PROPERTY,
       mApplicationToApplicationInformation);
   JsonUtils.add(builder, TRANSFER_TYPE_PROPERTY, getTransferType());
 }
Esempio n. 6
0
 public PageBean(String json) {
   JsonUtils jsonUtils = new JsonUtils();
   PageBean bean = (PageBean) jsonUtils.getObjectFromJsonString(PageBean.class, json);
   if (bean != null) {
     this.pageNo = bean.getPageNo();
     this.pageCount = bean.getPageCount();
     this.pageSize = bean.getPageSize();
     this.orderBy = bean.getOrderBy();
     this.orderDir = bean.getOrderDir();
   }
 }
 @Override
 public StackTraceElement deserialize(
     JsonElement json, Type typeOfT, JsonDeserializationContext context)
     throws JsonParseException {
   JsonObject jsonObj = json.getAsJsonObject();
   return new StackTraceElement(
       JsonUtils.getAsString(jsonObj, "className"),
       JsonUtils.getAsString(jsonObj, "method"),
       JsonUtils.getAsString(jsonObj, "file"),
       JsonUtils.getAsInt(jsonObj, "line", -1));
 }
    @Override
    public IncomingTransferAccept deserialize(
        JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

      JsonObject object = json.getAsJsonObject();
      return new IncomingTransferAccept(
          Status.parse(JsonUtils.getMandatoryString(object, "status")),
          Error.parse(JsonUtils.getString(object, "error")),
          JsonUtils.getInt(object, "protection_code_attempts_available"),
          JsonUtils.getString(object, "ext_action_uri"));
    }
 private ObjectNode convert(Map<String, Integer> map) {
   ObjectNode res = JsonUtils.createObjectNode();
   for (Entry<String, Integer> entry : map.entrySet()) {
     res.put(entry.getKey(), entry.getValue());
   }
   return res;
 }
Esempio n. 10
0
  @Override
  public Boolean loadInBackground() {
    boolean flag = false;
    // 进行开启下载任务

    try {
      byte[] bs = webCache.getByteFromInternet(url);
      if (bs != null) {
        String json = new String(bs, "utf-8");
        List<News> list = JsonUtils.turnToJson(json);
        for (News news : list) {
          // 将list加入数据库中
          newshander.insertToSQL(news);
          // 下载图片
          String url = news.getLitpic();
          byte[] bytes = webCache.getByteFromInternet(url);
          // 保存图片
          Bitmap compress = Compress.ImageCompress(bytes, 60, 60);
          String filename = fileCache.addToSdcard(url, BitmapToByte.bitmapToByte(compress));
          newshander.updata(url, filename);
          memoryCache.addtoCache(filename, compress);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return flag;
  }
 @Test
 public void shouldContainPipelineCounterOrLabel() throws Exception {
   JsonMap jsonMap = presenter.toJson();
   JsonValue jsonValue = JsonUtils.from(jsonMap);
   JsonValue pipeline = jsonValue.getObject("groups", 0, "history", 0);
   assertThat(pipeline.getString("counterOrLabel"), is("1"));
 }
 @Test
 public void shouldShowFirstStageApproverNameInBuildCauseBy() throws Exception {
   JsonMap jsonMap = presenter.toJson();
   JsonValue jsonValue = JsonUtils.from(jsonMap);
   String revision = jsonValue.getString("groups", 0, "history", 0, "buildCauseBy");
   assertThat(revision, is("Triggered by " + GoConstants.DEFAULT_APPROVED_BY));
 }
Esempio n. 13
0
 /** Called, when operation finishes successfully. */
 public void onFinished(JavaScriptObject jso) {
   setList(JsonUtils.<ExtSource>jsoAsList(jso));
   sortTable();
   session.getUiElements().setLogText("Loading external sources finished: " + list.size());
   events.onFinished(jso);
   loaderImage.loadingFinished();
 }
 private ArrayNode convert(List<String> list) {
   ArrayNode res = JsonUtils.createArrayNode();
   for (String elem : list) {
     res.add(elem);
   }
   return res;
 }
 /** Called, when operation finishes successfully. */
 public void onFinished(JavaScriptObject jso) {
   setList(JsonUtils.<Publication>jsoAsList(jso));
   sortTable();
   session.getUiElements().setLogText("Publications loaded: " + list.size());
   events.onFinished(jso);
   loaderImage.loadingFinished();
 }
Esempio n. 16
0
  @POST
  public Response add(final String body) {
    logger.debug("Adding a new user with body {}", body);
    User user = userJsonConverter.convertFrom(body);
    if (user.getUserType().equals(User.UserType.EMPLOYEE)) {
      return Response.status(HttpCode.FORBIDDEN.getCode()).build();
    }

    HttpCode httpCode = HttpCode.CREATED;
    OperationResult result;
    try {
      user = userService.add(user);
      result = OperationResult.success(JsonUtils.getJsonElementWithId(user.getId()));
    } catch (final FieldNotValidException e) {
      httpCode = HttpCode.VALIDATION_ERROR;
      logger.error("One of the fields of the user is not valid", e);
      result = getOperationResultInvalidField(RESOURCE_MESSAGE, e);
    } catch (final UserExistException e) {
      httpCode = HttpCode.VALIDATION_ERROR;
      logger.error("There is already an user for the given email", e);
      result = getOperationResultExists(RESOURCE_MESSAGE, "email");
    }

    logger.debug("Returning the operation result after adding user: {}", result);
    return Response.status(httpCode.getCode())
        .entity(OperationResultJsonWriter.toJson(result))
        .build();
  }
 @Test
 public void shouldContainMaterialRevisions() throws Exception {
   JsonMap jsonMap = presenter.toJson();
   JsonValue jsonValue = JsonUtils.from(jsonMap);
   JsonValue revision = jsonValue.getObject("groups", 0, "history", 0, "materialRevisions", 0);
   assertThat(revision.getString("revision"), is("svn.100"));
   assertThat(revision.getString("user"), is("user"));
   assertThat(revision.getString("date"), is(DateUtils.formatISO8601(modificationDate)));
 }
 @GET
 public Response handle() {
   String json = JsonUtils.getListPersonJson(people);
   System.out.println(json);
   return Response.ok(json)
       .header("Access-Control-Allow-Origin", "*")
       .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
       .build();
 }
  @Test(expectedExceptions = SpecException.class)
  public void testSpecExceptions() throws IOException {
    String testPath = "/json/cardinality/failCardinalityType";
    Map<String, Object> testUnit = JsonUtils.classpathToMap(testPath + ".json");

    Object spec = testUnit.get("spec");

    // Should throw exception
    new CardinalityTransform(spec);
  }
  public URL getQueryUrl() throws Exception {
    RepositoryNode repositoryNode = new RepositoryNode(this.workspace.getRepository());
    StringBuilder url = new StringBuilder(repositoryNode.getUrl().toString());

    // add workspace path
    url.append('/')
        .append(JsonUtils.encode(workspace.getName()))
        .append(IJsonConstants.QUERY_CONTEXT);
    return new URL(url.toString());
  }
Esempio n. 21
0
 /**
  * Creates a new instance of callback
  *
  * @param entity entity
  * @param id entity ID
  * @param attributes list of attributes urns (null if default / empty if all / explicit for
  *     selection)
  */
 public GetRichAdminsWithAttributes(PerunEntity entity, int id, ArrayList<String> attributes) {
   this.entity = entity;
   this.entityId = id;
   // if null use default
   if (attributes == null) {
     this.attributes = JsonUtils.getAttributesListForUserTables();
   } else {
     this.attributes = attributes;
   }
 }
Esempio n. 22
0
 @Override
 protected void addTurnProperties(JsonObjectBuilder builder) {
   JsonUtils.add(builder, SUBMIT_URI_PROPERTY, mUri);
   JsonUtils.add(builder, SUBMIT_METHOD_PROPERTY, mMethod.name());
   JsonUtils.add(builder, SUBMIT_PARAMETERS_PROPERTY, mSubmitParameters);
   JsonUtils.add(builder, SUBDIALOGUE_PARAMETERS_PROPERTY, JsonUtils.toJson(mParameters));
   JsonUtils.add(builder, FETCH_CONFIGURATION_PROPERTY, mFetchConfiguration);
   JsonUtils.add(builder, POST_DIALOGUE_SCRIPT_PROPERTY, getPostDialogueScript());
 }
Esempio n. 23
0
  /**
   * 验证每行日志并转换为bean
   *
   * @param line
   * @return
   */
  public T checkLineAndToBean(String line, Class<T> clazz) {
    if (StringUtils.isBlank(line)) {
      return null;
    }
    if (!(line.startsWith("{") && line.endsWith("}"))) {
      return null;
    }
    T obj = JsonUtils.jsonToBean(line, clazz);

    return obj;
  }
 /** Renders a JSON report containing the collected metrics. */
 public ObjectNode report() {
   ObjectNode res = JsonUtils.createObjectNode();
   res.put("instructions", convert(instructions));
   res.put("formatters", convert(formatters));
   res.put("predicates", convert(predicates));
   res.put("variables", currentNode);
   res.put("textBytes", textBytes);
   // NOTE: this is temporary - phensley
   res.put("ifInstructions", convert(ifVariants));
   return res;
 }
  @Test(expected = JsonSyntaxException.class)
  public void testDeserializeCorrupt() throws Exception {
    File file = File.createTempFile("import", ".json");

    file.deleteOnExit();
    try (FileWriter writer = new FileWriter(file)) {
      writer.write("false,false],[true,false]]");
    }

    JsonUtils.deserialize(file);
  }
 /** Called, when operation finishes successfully. */
 public void onFinished(JavaScriptObject jso) {
   clearTable();
   for (Attribute a : JsonUtils.<Attribute>jsoAsList(jso)) {
     if (!a.getDefinition().equals("core")) {
       addToTable(a);
     }
   }
   sortTable();
   loaderImage.loadingFinished();
   session.getUiElements().setLogText("Resource required attributes loaded: " + list.size());
   events.onFinished(jso);
 }
 /** Pushes one variable scope level. */
 private void pushSection(String name) {
   JsonNode node = currentNode.path(name);
   ObjectNode obj = null;
   if (node.isObject()) {
     obj = (ObjectNode) node;
   } else {
     obj = JsonUtils.createObjectNode();
     currentNode.put(name, obj);
   }
   variables.push(currentNode);
   currentNode = obj;
 }
Esempio n. 28
0
  private JSONObject getConfigurationForEditor() {
    try {
      JSONObject editorConfig = JsonUtils.createJSONObject(editorConfigJson);

      // configure extensions
      for (CKEditorPanelExtension extension : extensions) {
        extension.addConfiguration(editorConfig);
      }

      // always use the language of the current CMS locale
      final Locale locale = getLocale();
      editorConfig.put(CKEditorConstants.CONFIG_LANGUAGE, locale.getLanguage());

      // convert Hippo-specific 'declarative' keystrokes to numeric ones
      final JSONArray declarativeAndNumericKeystrokes =
          editorConfig.optJSONArray(CKEditorConstants.CONFIG_KEYSTROKES);
      final JSONArray numericKeystrokes =
          DeclarativeKeystrokesConverter.convertToNumericKeystrokes(
              declarativeAndNumericKeystrokes);
      editorConfig.putOpt(CKEditorConstants.CONFIG_KEYSTROKES, numericKeystrokes);

      // load the localized hippo styles if no other styles are specified
      JsonUtils.putIfAbsent(
          editorConfig, CKEditorConstants.CONFIG_STYLES_SET, HippoStyles.getConfigStyleSet(locale));

      // disable custom config loading if not configured
      JsonUtils.putIfAbsent(
          editorConfig, CKEditorConstants.CONFIG_CUSTOM_CONFIG, StringUtils.EMPTY);

      if (log.isInfoEnabled()) {
        log.info(
            "CKEditor configuration:\n"
                + editorConfig.toString(LOGGED_EDITOR_CONFIG_INDENT_SPACES));
      }

      return editorConfig;
    } catch (JSONException e) {
      throw new IllegalStateException("Error creating CKEditor configuration.", e);
    }
  }
Esempio n. 29
0
  public static String shopBrowseUrl(ItemSearch sourceItemSearch, String alias, String strChange) {
    ItemSearch itemSearch;
    try {
      itemSearch = (ItemSearch) BeanUtils.cloneBean(sourceItemSearch);
    } catch (IllegalAccessException
        | InstantiationException
        | InvocationTargetException
        | NoSuchMethodException ex) {
      itemSearch = new ItemSearch();
    }
    if (strChange != null && !strChange.equals("")) {
      List<Map<String, String>> changes =
          (List<Map<String, String>>)
              JsonUtils.decode(strChange, new TypeToken<List<Map<String, String>>>() {}.getType());

      for (Map<String, String> ch : changes) {
        String op = ch.get("op");
        String key = ch.get("key");
        String val = ch.get("val");
        if (key.equals("cid")) {
          itemSearch.setShopCategoryId(val);
        }
        if (key.equals("keyword")) {
          if (op.equals("mk")) {
            itemSearch.setKeyword(val);
          } else if (op.equals("rm")) {
            itemSearch.setKeyword(null);
          }
        }
        if (key.equals("promotionId")) {
          if (op.equals("mk")) {
            itemSearch.setPromotionId(val);
          } else if (op.equals("rm")) {
            itemSearch.setPromotionId(null);
          }
        }
        if (key.equals("order")) {
          try {
            itemSearch.setOrderBy(Integer.parseInt(val));
          } catch (NumberFormatException ex) {
          }
        }
        if (key.equals("page")) {
          try {
            itemSearch.setPageIndex(Integer.parseInt(val));
          } catch (NumberFormatException ex) {
          }
        }
      }
    }
    return UrlUtils.shopBrowseUrl(itemSearch, alias);
  }
 @Test
 public void shouldEncodeStageLocator() throws Exception {
   Stage stage1 =
       new Stage(
           "stage-c%d",
           new JobInstances(), GoConstants.DEFAULT_APPROVED_BY, "manual", new TimeProvider());
   stage1.setIdentifier(new StageIdentifier("pipeline-a%b", 1, "label-1", "stage-c%d", "1"));
   StageJsonPresentationModel presenter =
       new StageJsonPresentationModel(pipeline, stage1, null, new Agents());
   Map json = presenter.toJson();
   assertThat(
       JsonUtils.from(json).getString("stageLocator"), is("pipeline-a%25b/1/stage-c%25d/1"));
 }