Example #1
0
  public static List<MarshalledMessage> decodePayload(final String value) {
    if (value == null || value.trim().length() == 0) return Collections.emptyList();

    /**
     * We have to do a two-stage decoding of the message. We cannot fully decode the message here,
     * as we cannot be sure the destination endpoint exists within this Errai bundle. So we extract
     * the ToSubject field and send the unparsed JSON object onwards.
     */
    JSONValue val = null;

    try {
      val = JSONParser.parseStrict(value);
    } catch (ClassCastException e) {
      if (!GWT.isProdMode()) {
        System.out.println("*** working around devmode bug ***");
        val = JSONParser.parseStrict(value);
      }
    }

    if (val == null) {
      return Collections.emptyList();
    }
    final JSONArray arr = val.isArray();
    if (arr == null) {
      throw new RuntimeException("unrecognized payload" + val.toString());
    }
    final ArrayList<MarshalledMessage> list = new ArrayList<MarshalledMessage>();
    unwrap(list, arr);
    return list;
  }
 @Override
 public T decode(String value) throws DecodingException {
   try {
     return decode(JSONParser.parseStrict(value));
   } catch (JSONException e) {
     // that can happen for generic key types like Object and then a String key gets passed in
     return decode(JSONParser.parseStrict("\"" + value + "\""));
   }
 }
 /**
  * メッセージから、メッセージの送信者名を取得する
  *
  * @param message
  * @return
  */
 public String getSenderName(String message) {
   return JSONParser.parseStrict(message)
       .isObject()
       .get(KEY_MESSENGER_NAME)
       .isString()
       .stringValue();
 }
  /**
   * 入力されたメッセージを元に、宛先とコマンドを変更したものを返す
   *
   * @deprecated 0.7.4 親子関係を組み込むと、callの部分がmanualに成る為、使用不可とする。
   * @param receiverName
   * @param command
   * @param eventString
   * @return
   */
  public String copyOut(
      int messageCategoly, String newReceiverName, String newCommand, String eventString) {
    // 内容チェックを行い、receiverとcommandを書き換える
    debug.assertTrue(newReceiverName != null, "newReceiverName = null");
    debug.assertTrue(newCommand != null, "newCommand = null");
    debug.assertTrue(eventString != null, "eventString = null");

    JSONObject eventObj = JSONParser.parseStrict(eventString).isObject();
    debug.assertTrue(
        eventObj.containsKey(KEY_MESSAGE_CATEGOLY), "not contain KEY_MESSAGE_CATEGOLY");
    debug.assertTrue(eventObj.containsKey(KEY_MESSENGER_NAME), "not contain KEY_MESSENGER_NAME");
    debug.assertTrue(eventObj.containsKey(KEY_MESSENGER_ID), "not contain KEY_MESSENGER_ID");
    debug.assertTrue(eventObj.containsKey(KEY_MESSENGER_EXEC), "not contain KEY_MESSENGER_EXEC");
    debug.assertTrue(eventObj.containsKey(KEY_TO_NAME), "not contain KEY_TO_NAME");
    debug.assertTrue(eventObj.containsKey(KEY_TO_ID), "not contain KEY_TO_ID");
    debug.assertTrue(
        eventObj.containsKey(KEY_MESSENGER_TAGVALUE_GROUP),
        "not contain KEY_MESSENGER_TAGVALUE_GROUP");

    // categolyの書き換えを行う

    return replaceSenderInformation(
            messageCategoly, getName(), getID(), newReceiverName, newCommand, eventObj)
        .toString();
  }
Example #5
0
  private static ServerEvent parseJsonEvent(String msg) {
    try {
      JSONObject eventJ = JSONParser.parseStrict(msg).isObject();
      Name name = new Name(eventJ.get("name").isString().stringValue(), "");
      ServerEvent.Scope scope =
          ServerEvent.Scope.valueOf(eventJ.get("scope").isString().stringValue());
      ServerEvent.DataType dataType =
          eventJ.get("dataType") == null
              ? ServerEvent.DataType.STRING
              : ServerEvent.DataType.valueOf(eventJ.get("dataType").isString().stringValue());
      Serializable data;
      String from = eventJ.get("from") == null ? null : eventJ.get("from").toString();
      if (dataType == ServerEvent.DataType.BG_STATUS) {
        data = BackgroundStatus.parse(eventJ.get("data").isString().stringValue());
      } else if (dataType == ServerEvent.DataType.JSON) {
        data = eventJ.get("data").isObject().toString();
      } else {
        data = eventJ.get("data").isString().stringValue();
      }
      ServerEvent sEvent = new ServerEvent(name, scope, dataType, data);
      sEvent.setFrom(from);
      return sEvent;

    } catch (Exception e) {
      GwtUtil.getClientLogger()
          .log(Level.WARNING, "Unable to parse json message into ServerEvent: " + msg, e);
      return null;
    }
  }
 /**
  * メッセージから、メッセージコマンドを取得する
  *
  * @param message
  * @return
  */
 public String getCommand(String message) {
   return JSONParser.parseStrict(message)
       .isObject()
       .get(KEY_MESSENGER_EXEC)
       .isString()
       .stringValue();
 }
Example #7
0
    @Override
    public void onResponseReceived(Request request, Response response) {
      JSONValue j = JSONParser.parseStrict(response.getText());
      JSONObject obj = j.isObject();
      if (obj != null && obj.containsKey("error")) {
        Window.alert(obj.get("error").isString().stringValue());
        changeButtonSelection();
        setTextEnabled(false);
        clearTextBoxes();
        singleSelectionModel.clear();
      } else {
        List<OrganismInfo> organismInfoList =
            OrganismInfoConverter.convertJSONStringToOrganismInfoList(response.getText());
        dataGrid.setSelectionModel(singleSelectionModel);
        MainPanel.getInstance().getOrganismInfoList().clear();
        MainPanel.getInstance().getOrganismInfoList().addAll(organismInfoList);
        changeButtonSelection();
        OrganismChangeEvent organismChangeEvent = new OrganismChangeEvent(organismInfoList);
        organismChangeEvent.setAction(OrganismChangeEvent.Action.LOADED_ORGANISMS);
        Annotator.eventBus.fireEvent(organismChangeEvent);

        // in the case where we just add one . . .we should refresh the app state
        if (organismInfoList.size() == 1) {
          MainPanel.getInstance().getAppState();
        }
      }
      if (savingNewOrganism) {
        savingNewOrganism = false;
        setNoSelection();
        changeButtonSelection(false);
        loadingDialog.hide();
      }
    }
Example #8
0
 @Override
 public final void onResponseReceived(Request request, Response response) {
   if (200 == response.getStatusCode()) {
     parseJSON(JSONParser.parseStrict(response.getText()));
   } else {
     Window.alert(response.getStatusCode() + " : " + response.getStatusText());
     System.err.println(response.getStatusCode() + " : " + response.getStatusText());
   }
 }
Example #9
0
 public static JSONArray parseJSONArray(String jsonText) {
   if (jsonText != null && 0 < jsonText.length()) {
     JSONValue jsonValue = JSONParser.parse(jsonText);
     if (jsonValue != null) {
       return jsonValue.isArray();
     }
   }
   return null;
 }
  /**
   * Creates a JSON object from a string. If the string parses, but doesn't contain a JSON object,
   * null is returned.
   *
   * @param json
   * @return
   */
  public static JSONObject getObject(final String json) {
    JSONValue val = JSONParser.parseStrict(json);

    if (val == null) {
      return null;
    } else {
      return val.isObject();
    }
  }
Example #11
0
 /**
  * 静态函数:根据输入的Json字符串,解析成一个完整的菜单树
  *
  * @param menuStr Json字符串
  * @return 菜单树形根节点
  */
 public static GWTMenu GetMenuList(String menuStr) {
   // 解析菜单
   JSONValue obj1 = JSONParser.parse(menuStr);
   JSONArray menuList = obj1.isArray();
   GWTMenu menu = new GWTMenu();
   for (int i = 0; i < menuList.size(); i++) {
     AddGWTMenu(menu, menuList.get(i));
   }
   return menu;
 }
Example #12
0
 //
 // Utility methods, also useful when parsing third-party JSON
 //
 public static JSONObject parseJSONObject(String jsonText) {
   if (jsonText != null && 0 < jsonText.length()) {
     // TODO: use GWT json utils class to do safe parsing
     JSONValue jsonValue = JSONParser.parse(jsonText);
     if (jsonValue != null) {
       return jsonValue.isObject();
     }
   }
   return null;
 }
Example #13
0
 private JSONValue toJson() {
   final JSONObject data = null == restoreddata ? new JSONObject() : restoreddata;
   try {
     data.put("historyversion", new JSONString(SearchPanelModel.historyversion));
     data.put("selectedtype", new JSONString(selectedCriterion.displaytype));
     final Iterator<String> iter = criteria.keySet().iterator();
     while (iter.hasNext()) {
       final String searchTypeKey = iter.next();
       if (!selectedCriterionHistory.containsKey(searchTypeKey)) {
         continue;
       }
       final JSONObject searchdata = new JSONObject();
       final JSONObject userdata = new JSONObject();
       searchdata.put(Context.get().getChallengeLogin().toLowerCase(), userdata);
       userdata.put(
           "selectedcriterion",
           new JSONString(selectedCriterionHistory.get(searchTypeKey).getName()));
       final JSONObject criteriadata = new JSONObject();
       for (final Criterion criterion : criteria.get(searchTypeKey).values()) {
         final String s = CriterionHistory.Writer.toJson(criterion.getHistory());
         criteriadata.put(criterion.getName(), JSONParser.parseStrict(s));
       }
       userdata.put("criteria", criteriadata);
       if (searchhistory.containsKey(searchTypeKey)) {
         userdata.put(
             "searchhistory",
             JSONParser.parseStrict(
                 SearchHistory.Writer.toJson(searchhistory.get(searchTypeKey))));
       }
       if (accesshistory.containsKey(searchTypeKey)) {
         userdata.put(
             "accesshistory",
             JSONParser.parseStrict(
                 AccessHistory.Writer.toJson(accesshistory.get(searchTypeKey))));
       }
       data.put(selectedCriterionHistory.get(searchTypeKey).getType().toLowerCase(), searchdata);
     }
   } catch (final Exception e) {
     getLogger().severe("SearchModel.toJson() : " + e);
   }
   return data;
 }
Example #14
0
  private ResultMessage processResponse(Request request, Response response)
      throws ResultMessageException {
    JSONValue jsonValue = JSONParser.parseStrict(response.getText());

    ResultMessage result = new ResultMessage(BusinessObject.create(jsonValue.isObject()));

    if (result.getStatus() != 0) {
      handleResultError(result);
    }
    return result;
  }
Example #15
0
 /**
  * Factory method.
  *
  * @param <J> type of {@link JavaScriptObject} returned by this method
  * @param pJson the JSON representation of a {@link com.tj.civ.client.model.jso.CbGameJSO}
  * @return a new instance, or <code>null</code> if the instance could not be created
  */
 @SuppressWarnings("unchecked")
 public static <J extends JavaScriptObject> J createFromJson(final String pJson) {
   J result = null;
   JSONValue v = JSONParser.parseStrict(pJson);
   if (v != null) {
     JSONObject obj = v.isObject();
     if (obj != null) {
       result = (J) obj.getJavaScriptObject().cast();
     }
   }
   return result;
 }
  /**
   * tagValueグループに含まれるtagをリストとして取得する
   *
   * @param message
   * @return
   */
  public ArrayList<String> getTags(String message) {
    JSONObject obj =
        JSONParser.parseStrict(message).isObject().get(KEY_MESSENGER_TAGVALUE_GROUP).isObject();

    ArrayList<String> tags = new ArrayList<String>();

    Set<String> currentSet = obj.keySet();

    for (Iterator<String> currentSetItel = currentSet.iterator(); currentSetItel.hasNext(); ) {
      tags.add(currentSetItel.next());
    }

    return tags;
  }
Example #17
0
  public static HighchartConfig createFromServerSideString(String confStr, String jsonState) {
    HighchartConfig conf;
    if (confStr != null) {
      conf = (HighchartConfig) JSONParser.parseLenient(confStr).isObject().getJavaScriptObject();
      conf.prepare();
    } else {
      conf = JavaScriptObject.createObject().cast();
    }
    if (jsonState != null) {
      merge(conf, jsonState);
    }

    return conf;
  }
 @Override
 public UserDetails deserialize(String json) {
   JSONValue parsed = JSONParser.parseStrict(json);
   JSONObject jsonObj = parsed.isObject();
   UserDetailsDTO user = new UserDetailsDTO();
   if (jsonObj != null) {
     user.setUsername(jsonObj.get(UserDetailsDTO.USERNAME_FIELD).toString());
     JSONArray array = jsonObj.get(UserDetailsDTO.AUTHORITIES_FIELD).isArray();
     for (int i = 0; i < array.size(); i++) {
       JSONValue obj = array.get(i);
       user.getAuthorities().add(obj.toString());
     }
   }
   return user;
 }
  /**
   * tagValueグループに含まれるvalueをリストとして取得する
   *
   * @param message
   * @return
   */
  public ArrayList<JSONValue> getValues(String message) {
    JSONObject obj =
        JSONParser.parseStrict(message).isObject().get(KEY_MESSENGER_TAGVALUE_GROUP).isObject();

    ArrayList<JSONValue> values = new ArrayList<JSONValue>();

    Set<String> currentSet = obj.keySet();

    for (Iterator<String> currentSetItel = currentSet.iterator(); currentSetItel.hasNext(); ) {
      String currentKey = currentSetItel.next();
      values.add(obj.get(currentKey));
    }

    return values;
  }
  public void testToJson() {
    PropertyGroupContainer container1 = new PropertyGroupContainer("{}"); // $NON-NLS-1$
    PropertyGroup group = new PropertyGroup();
    Property property =
        new Property(
            JSONParser.parseStrict(
                    "{\"id\":\"blah-test-1.304116363485E12\",\"name\":\"\",\"label\":\"my widget\",\"description\":\"\",\"type\":\"\",\"isVisible\":true,\"value\":\"\",\"order\":0}") //$NON-NLS-1$
                .isObject());
    group.add(property);
    container1.add(group);

    JSONObject json1 = container1.toJson();
    PropertyGroupContainer container2 = new PropertyGroupContainer(json1.toString());
    JSONObject json2 = container2.toJson();
    UnitTestUtil.equalsIgnoreOrder(json1, json2);
  }
Example #21
0
 private DataSource getRecentlyAccessed() {
   final DataSource datasource = new DataSource();
   datasource.setClientOnly(true);
   datasource.setCacheAllData(true);
   datasource.setAutoCacheAllData(true);
   int j = accesshistory.get(selectedCriterion.displaytype).getStack().size();
   final Record[] records = new Record[j];
   for (final AccessString access : accesshistory.get(selectedCriterion.displaytype).getStack()) {
     final Record record =
         new Record(JSONParser.parseStrict(access.asString()).isObject().getJavaScriptObject());
     record.setAttribute("row", j);
     record.setAttribute("lastmodified", record.getAttribute("lastmodified").substring(0, 10));
     records[--j] = record;
   }
   datasource.setTestData(records);
   return datasource;
 }
Example #22
0
  private void printGitMessage(String messageText, GitOutputConsole console) {
    if (messageText == null || messageText.isEmpty()) {
      return;
    }
    JSONObject jsonObject = JSONParser.parseStrict(messageText).isObject();
    if (jsonObject == null) {
      return;
    }
    String message = "";
    if (jsonObject.containsKey("message")) {
      message = jsonObject.get("message").isString().stringValue();
    }

    console.print("");
    String[] lines = message.split("\n");
    for (String line : lines) {
      console.printError(line);
    }
  }
Example #23
0
    private void addProperties(Response response) {
      GWT.log(response.getText(), null);
      try {
        // parse the response text into JSON
        JSONValue jsonValue = JSONParser.parse(response.getText());
        JSONArray jsonArray = jsonValue.isArray();

        if (jsonArray != null) {
          for (int index = 0; index < jsonArray.size(); index++) {
            addProperty(((JSONObject) jsonArray.get(index)), index);
          }
        } else {
          throw new JSONException("Invalid Json structure when retrieve the Sling nodes");
        }
      } catch (JSONException e) {
        e.printStackTrace();
        GWT.log("ResourceGrids - Could not parse JSON", e);
      }
    }
 @SuppressWarnings({"rawtypes", "deprecation", "unchecked"})
 protected Object[] extractDate(Criteria criteria, OperatorId operator, Map values, String key) {
   Object value;
   String jsObj = JSON.encode(criteria.getJsObj());
   JSONObject criteriaObj = JSONParser.parse(jsObj).isObject();
   JSONObject valueObj = criteriaObj.get(key).isObject();
   if (valueObj != null) {
     value = parseRelativeDate((Map<String, String>) values.get(key));
   } else {
     value = values.get(key);
   }
   if (OperatorId.GREATER_THAN.getValue().equals(operator.getValue())
       || OperatorId.LESS_OR_EQUAL.getValue().equals(operator.getValue())) {
     ((Date) value).setHours(23);
     ((Date) value).setMinutes(59);
   } else {
     ((Date) value).setHours(0);
     ((Date) value).setMinutes(0);
   }
   return new Object[] {value};
 }
Example #25
0
 private void showList(String json) {
   JSONValue v = JSONParser.parseStrict(json);
   System.out.println("BlackList showList , json = " + json);
   JSONObject jo = v.isObject();
   page = (int) jo.get("page").isNumber().doubleValue();
   size = (int) jo.get("size").isNumber().doubleValue();
   JSONArray array = jo.get("list").isArray();
   ListDataProvider<BlackListRowData> provider = new ListDataProvider<BlackListRowData>();
   provider.addDataDisplay(cellTable);
   List<BlackListRowData> list = provider.getList();
   for (int i = 0; i < array.size(); i++) {
     JSONObject obj = array.get(i).isObject();
     int monetId = (int) obj.get("monetId").isNumber().doubleValue();
     String reason = obj.get("reason").isString().stringValue();
     String expire = obj.get("expire").isString().stringValue();
     BlackListRowData data = new BlackListRowData();
     data.setMonetId(monetId);
     data.setReason(reason);
     data.setExpire(expire);
     list.add(data);
   }
 }
Example #26
0
  public static void onMessage(String msg) {
    try {
      GwtUtil.getClientLogger().log(Level.INFO, "onMessage: " + msg);

      ServerEvent sEvent = parseJsonEvent(msg);
      Name name = sEvent == null ? null : sEvent.getName();
      Serializable data = sEvent.getData();

      if (name == null) {
        GwtUtil.getClientLogger().log(Level.INFO, "Failed to evaluate: " + msg);
      }
      if (name.equals(Name.EVT_CONN_EST)) {
        JSONObject dataJ = JSONParser.parseStrict(sEvent.getData().toString()).isObject();
        String sEventInfo =
            dataJ.get("connID").isString().stringValue()
                + "_"
                + dataJ.get("channel").isString().stringValue();
        Cookies.setCookie("seinfo", sEventInfo);
        GwtUtil.getClientLogger()
            .log(Level.INFO, "Websocket connection established: " + sEventInfo);
      } else if (data instanceof BackgroundStatus) {
        WebEvent<String> ev =
            new WebEvent<String>(
                ClientEventQueue.class, name, ((BackgroundStatus) data).serialize());
        WebEventManager.getAppEvManager().fireEvent(ev);
        GwtUtil.getClientLogger()
            .log(Level.INFO, "Event: Name:" + name.getName() + ", Data: " + ev.getData());
      } else {
        WebEvent<String> ev =
            new WebEvent<String>(ClientEventQueue.class, name, String.valueOf(data));
        WebEventManager.getAppEvManager().fireEvent(ev);
        GwtUtil.getClientLogger()
            .log(Level.INFO, "Event: Name:" + name.getName() + ", Data: " + sEvent.getData());
      }
    } catch (Exception e) {
      GwtUtil.getClientLogger()
          .log(Level.WARNING, "Exception interpreting incoming message: " + msg, e);
    }
  }
Example #27
0
 @RequestReceiver("Search")
 @EventMultiplexer(SearchResult.class)
 void executeSearch(
     final Request<ClickEvent> request,
     final ResponseMultiplexer<JSONValue, SearchResult> responsemultiplexer) {
   if (cansearch) {
     if ("Recently accessed".equals(getSelectedCriterion().getName())) {
       final Response<JSONValue, SearchResult> response = responsemultiplexer.multiplex();
       final SearchResult event = response.event();
       event.url = null;
       event.alias = getSelectedCriterion().getAlias();
       event.recycle = recycle;
       event.delimiter = null;
       event.datasource = getRecentlyAccessed();
       event.datatype = getSelectedCriterion().getDataType();
       final String data =
           "{\"response\":{\"data\":[],\"startRow\":0,\"endRow\":0,\"totalRows\":0,\"status\":0}}";
       response.onSuccess(JSONParser.parseStrict(data));
     } else {
       if (0 == locations.selection.length) {
         Dialogs.error("You need to select at least one location to search in.");
       } else {
         for (final Location location : locations.selectedlocations) {
           final Response<JSONValue, SearchResult> response = responsemultiplexer.multiplex();
           final SearchResult event = response.event();
           event.url = location.url + getSelectedCriterion().getType() + "/?" + getQuery();
           event.alias = location.shortname + ": " + getAlias();
           event.delimiter = ":";
           event.recycle = recycle;
           event.datatype = DataType.valueOf(getSelectedCriterion().getType());
           final String queryurl = event.url + "&from=0&to=50";
           JsonResource.get(queryurl, response, "Searching...", "No result: " + queryurl, true);
         }
       }
     }
   }
 }
Example #28
0
  /** {@code ClickHandler} */
  @Override
  public void onClick(ClickEvent event) {
    NativeEvent nativeEvent = event.getNativeEvent();
    Element element = DOM.eventGetTarget(Event.as(nativeEvent));
    element =
        GWTUtils.getElementWithAttr((com.google.gwt.user.client.Element) element.cast(), "uid");
    Element dataQueryEl = null;
    if (element != null) {
      dataQueryEl =
          GWTUtils.findDataQueryElement((com.google.gwt.user.client.Element) element.cast());
      String uid = element.getAttribute("uid");
      String json = dataQueryEl.getAttribute("data-query");

      if (!GWTUtils.isEmpty(uid)) {
        JSONObject targetJson = null;
        if (!GWTUtils.isEmpty(json)) {
          targetJson = (JSONObject) JSONParser.parse(json);
        }
        processClickEvent(uid, targetJson);
      }
    } else {
      return;
    }
  }
Example #29
0
 public ViewJson(String jsonString) {
   this.jsonObject = JSONParser.parseStrict(jsonString).isObject();
 }
 public PrefixMetadata(String json) {
   JSONObject metaMap = JSONParser.parseStrict(json).isObject();
   prefix = metaMap.get("prefix").isString().stringValue();
   statDataItemCount = metaMap.get("statcount").isString().stringValue();
 }