/**
   * Test importing an unsupported field e.g. datetime, the program should continue and assign null
   * value to the field.
   *
   * @throws Exception
   */
  @Test
  public void testImportUnsupportedField() throws Exception {
    ConnectionProperties p = getConnectionProperties();
    Connection cn = DatabaseConnection.getConnection(p);
    try {
      List<Field> verifiedFields = new Vector<Field>();
      String[] fields = "ListingId, Title".split(",");
      String tableName = "Listings";
      DatabaseConnection.verifyTable(p, tableName, fields, verifiedFields);

      Collection<JsonNode> importNodes = new LinkedList<JsonNode>();
      JsonNodeFactory f = JsonNodeFactory.instance;

      int listingId = 1559350;

      ObjectNode n;
      n = new ObjectNode(f);
      n.put("ListingId", listingId);
      importNodes.add(n);

      JsonArrayImporter importer = new JsonArrayImporter(p);
      importer.doImport(tableName, verifiedFields, importNodes);

      Statement st = cn.createStatement();
      ResultSet rs = st.executeQuery("SELECT ListingId, Title FROM Listings");
      assertTrue("Expected result set to contain a record", rs.next());
      assertEquals(listingId, rs.getInt("ListingId"));
      assertEquals(null, rs.getString("Title"));
    } finally {
      cn.close();
    }
  }
Exemple #2
0
  /**
   * Update book-keeping fields on the alarm. Returns an up-to-date version of the alarm. Some of
   * its fields may have been updated since the REST client last retrieved the alarm being updated.
   *
   * @param alarmIdPath
   * @param stream input JSON
   * @return updated JSON encoded alarm
   */
  @PUT
  @Path("{alarm_id}")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public Response update(
      @PathParam("alarm_id") final String alarmIdPath, final InputStream stream) {
    log.info("PUT NEW ALARM at /{}", alarmIdPath);

    try {
      final ObjectNode jsonTree = (ObjectNode) mapper().readTree(stream);
      log.info("jsonTree={}", jsonTree);

      final Alarm alarm = codec(Alarm.class).decode(jsonTree, this);

      final AlarmService service = get(AlarmService.class);

      if (Long.parseLong(alarmIdPath) != alarm.id().fingerprint()) {
        throw new IllegalArgumentException(
            "id in path is "
                + Long.parseLong(alarmIdPath)
                + " but payload uses id="
                + alarm.id().fingerprint());
      }
      final Alarm updated = service.update(alarm);
      final ObjectNode encoded = new AlarmCodec().encode(updated, this);
      return ok(encoded.toString()).build();

    } catch (IOException ioe) {
      throw new IllegalArgumentException(ioe);
    }
  }
  /**
   * Converts partition info into a JSON object.
   *
   * @param partitionInfo partition descriptions
   */
  private JsonNode json(List<PartitionInfo> partitionInfo) {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode partitions = mapper.createArrayNode();

    // Create a JSON node for each partition
    partitionInfo
        .stream()
        .forEach(
            info -> {
              ObjectNode partition = mapper.createObjectNode();

              // Add each member to the "members" array for this partition
              ArrayNode members = partition.putArray("members");
              info.members().stream().forEach(members::add);

              // Complete the partition attributes and add it to the array
              partition
                  .put("name", info.name())
                  .put("term", info.term())
                  .put("leader", info.leader());
              partitions.add(partition);
            });

    return partitions;
  }
  @Override
  public void validate(
      final Processor<FullData, FullData> processor,
      final ProcessingReport report,
      final MessageBundle bundle,
      final FullData data)
      throws ProcessingException {
    final SchemaTree tree = data.getSchema();
    final JsonPointer schemaPointer = tree.getPointer();
    final JsonNode schemas = tree.getNode().get(keyword);
    final int size = schemas.size();
    final ObjectNode fullReport = FACTORY.objectNode();

    int nrSuccess = 0;
    ListProcessingReport subReport;
    JsonPointer ptr;
    FullData newData;

    for (int index = 0; index < size; index++) {
      subReport = new ListProcessingReport(report.getLogLevel(), LogLevel.FATAL);
      ptr = schemaPointer.append(JsonPointer.of(keyword, index));
      newData = data.withSchema(tree.setPointer(ptr));
      processor.process(subReport, newData);
      fullReport.put(ptr.toString(), subReport.asJson());
      if (subReport.isSuccess()) nrSuccess++;
    }

    if (nrSuccess == 0)
      report.error(
          newMsg(data, bundle, "err.common.schema.noMatch")
              .putArgument("nrSchemas", size)
              .put("reports", fullReport));
  }
  @Test
  public void testCommandGetFilteredCollection() {
    running(
        fakeApplication(),
        () -> {
          try {
            DbHelper.open("1234567890", TEST_USER, TEST_USER);
            ObjectNode cmd = MAPPER.createObjectNode();
            ObjectNode p = MAPPER.createObjectNode();
            ObjectNode q = MAPPER.createObjectNode();
            q.put("where", "idx < ?");
            ArrayNode params = MAPPER.createArrayNode();
            params.add("5");
            q.put("params", params);
            p.put("collection", TEST_COLLECTION);
            p.put("query", q);

            cmd.put(ScriptCommand.RESOURCE, "documents");
            cmd.put(ScriptCommand.NAME, "list");
            cmd.put(ScriptCommand.PARAMS, p);

            JsonNode node = CommandRegistry.execute(cmd, null);
            assertNotNull(node);
            assertTrue(node.isArray());
            assertEquals(5, node.size());
          } catch (Throwable t) {
            fail(ExceptionUtils.getFullStackTrace(t));
          } finally {
            DbHelper.close(DbHelper.getConnection());
          }
        });
  }
  /**
   * Sends a message envelope on this socket
   *
   * @param envelope The message envelope
   * @return This socket instance
   * @throws IOException Thrown if the message cannot be sent
   */
  public Socket push(final Envelope envelope) throws IOException {
    LOG.log(Level.FINE, "Pushing envelope: {0}", envelope);
    final ObjectNode node = objectMapper.createObjectNode();
    node.put("topic", envelope.getTopic());
    node.put("event", envelope.getEvent());
    node.put("ref", envelope.getRef());
    node.set(
        "payload",
        envelope.getPayload() == null ? objectMapper.createObjectNode() : envelope.getPayload());
    final String json = objectMapper.writeValueAsString(node);
    LOG.log(Level.FINE, "Sending JSON: {0}", json);

    RequestBody body = RequestBody.create(WebSocket.TEXT, json);

    if (this.isConnected()) {
      try {
        webSocket.sendMessage(body);
      } catch (IllegalStateException e) {
        LOG.log(Level.SEVERE, "Attempted to send push when socket is not open", e);
      }
    } else {
      this.sendBuffer.add(body);
    }

    return this;
  }
  /**
   * 图片语音文件下载
   *
   * @param fileUUID 文件在DB的UUID
   * @param shareSecret 文件在DB中保存的shareSecret
   * @param localPath 下载后文件存放地址
   * @param isThumbnail 是否下载缩略图 true:缩略图 false:非缩略图
   * @return
   */
  public static ObjectNode mediaDownload(
      String fileUUID, String shareSecret, File localPath, Boolean isThumbnail) {
    ObjectNode objectNode = factory.objectNode();
    File downLoadedFile = null;
    if (!JerseyUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", APPKEY)) {
      LOGGER.error("Bad format of Appkey: " + APPKEY);
      objectNode.put("message", "Bad format of Appkey");
      return objectNode;
    }

    try {
      JerseyWebTarget webTarget =
          EndPoints.CHATFILES_TARGET
              .resolveTemplate("org_name", APPKEY.split("#")[0])
              .resolveTemplate("app_name", APPKEY.split("#")[1])
              .path(fileUUID);
      List<NameValuePair> headers = new ArrayList<NameValuePair>();
      headers.add(new BasicNameValuePair("share-secret", shareSecret));
      headers.add(new BasicNameValuePair("Accept", "application/octet-stream"));
      if (isThumbnail != null && isThumbnail) {
        headers.add(new BasicNameValuePair("thumbnail", String.valueOf(isThumbnail)));
      }
      downLoadedFile = JerseyUtils.downLoadFile(webTarget, credential, headers, localPath);
      LOGGER.error(
          "File download successfully,file path : " + downLoadedFile.getAbsolutePath() + ".");
    } catch (Exception e) {
      e.printStackTrace();
    }

    objectNode.put("message", "File download successfully .");
    return objectNode;
  }
  protected void localize(ProcessInstance processInstance) {
    ExecutionEntity processInstanceExecution = (ExecutionEntity) processInstance;
    processInstanceExecution.setLocalizedName(null);
    processInstanceExecution.setLocalizedDescription(null);

    if (locale != null) {
      String processDefinitionId = processInstanceExecution.getProcessDefinitionId();
      if (processDefinitionId != null) {
        ObjectNode languageNode =
            Context.getLocalizationElementProperties(
                locale,
                processInstanceExecution.getProcessDefinitionKey(),
                processDefinitionId,
                withLocalizationFallback);
        if (languageNode != null) {
          JsonNode languageNameNode = languageNode.get(DynamicBpmnConstants.LOCALIZATION_NAME);
          if (languageNameNode != null && languageNameNode.isNull() == false) {
            processInstanceExecution.setLocalizedName(languageNameNode.asText());
          }

          JsonNode languageDescriptionNode =
              languageNode.get(DynamicBpmnConstants.LOCALIZATION_DESCRIPTION);
          if (languageDescriptionNode != null && languageDescriptionNode.isNull() == false) {
            processInstanceExecution.setLocalizedDescription(languageDescriptionNode.asText());
          }
        }
      }
    }
  }
 /**
  * 删除redis中的商品
  *
  * @param pid
  * @return
  */
 @AdminAuthenticated()
 public Result deleteRedisProductByPid(Long pid) {
   cache.clear(Constants.product_KEY + pid);
   ObjectNode result = Json.newObject();
   result.put("status", 1);
   return ok(Json.toJson(result));
 }
Exemple #10
0
  @Test
  public void addValidReview() {
    running(
        fakeApplication(),
        () -> {
          ObjectNode node = JsonNodeFactory.instance.objectNode();
          node.put("text", "text of review");
          node.put("rating", 4);
          JsonNode json = null;
          try {
            json = (JsonNode) new ObjectMapper().readTree(node.toString());
          } catch (IOException e) {
            e.printStackTrace();
          }

          Http.RequestBuilder rb =
              new Http.RequestBuilder()
                  .method(POST)
                  .uri("/v1/restaurants/1601994/reviews")
                  .bodyJson(json);
          Result result = route(rb);

          assertEquals(Http.Status.OK, result.status());
          assertTrue(PersistenceManager.getRestaurantById(1601994).getReviews().size() != 0);
          assertTrue(
              PersistenceManager.getRestaurantById(1601994)
                  .getReviews()
                  .get(0)
                  .getText()
                  .equals("text of review"));
        });
  }
Exemple #11
0
  @Test
  public void addToInvalidRestaurant() {
    running(
        fakeApplication(),
        () -> {
          ObjectNode node = JsonNodeFactory.instance.objectNode();
          node.put("text", "text of review");
          node.put("rating", 4);
          JsonNode json = null;
          try {
            json = (JsonNode) new ObjectMapper().readTree(node.toString());
          } catch (IOException e) {
            e.printStackTrace();
          }

          Http.RequestBuilder rb =
              new Http.RequestBuilder()
                  .method(POST)
                  .uri("/v1/restaurants/3213123/reviews")
                  .bodyJson(json);
          Result result = route(rb);

          assertEquals(Http.Status.NOT_FOUND, result.status());
        });
  }
  public ExternalDocs externalDocs(ObjectNode node, String location, ParseResult result) {
    ExternalDocs output = null;

    if (node != null) {
      output = new ExternalDocs();
      Set<String> keys = getKeys(node);

      String value = getString("description", node, false, location, result);
      output.description(value);

      value = getString("url", node, true, location, result);
      output.url(value);

      // extra keys
      for (String key : keys) {
        if (key.startsWith("x-")) {
          output.setVendorExtension(key, extension(node.get(key)));
        } else if (!EXTERNAL_DOCS_KEYS.contains(key)) {
          result.extra(location + ".externalDocs", key, node.get(key));
        }
      }
    }

    return output;
  }
  public Tag tag(ObjectNode node, String location, ParseResult result) {
    Tag tag = null;

    if (node != null) {
      tag = new Tag();
      Set<String> keys = getKeys(node);

      String value = getString("name", node, true, location, result);
      tag.name(value);

      value = getString("description", node, false, location, result);
      tag.description(value);

      ObjectNode externalDocs = getObject("externalDocs", node, false, location, result);
      ExternalDocs docs = externalDocs(externalDocs, location + "externalDocs", result);
      tag.externalDocs(docs);

      // extra keys
      for (String key : keys) {
        if (key.startsWith("x-")) {
          tag.setVendorExtension(key, extension(node.get(key)));
        } else if (!TAG_KEYS.contains(key)) {
          result.extra(location + ".externalDocs", key, node.get(key));
        }
      }
    }

    return tag;
  }
Exemple #14
0
  @At("/?/json")
  @Ok("raw")
  public ObjectNode getEditorJson(String modelId) {
    ObjectNode modelNode = null;

    Model model = repositoryService.getModel(modelId);

    if (model != null) {
      try {
        ObjectMapper objectMapper = new ObjectMapper();
        if (StringUtils.isNotEmpty(model.getMetaInfo())) {
          modelNode = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
        } else {
          modelNode = objectMapper.createObjectNode();
          modelNode.put(ModelDataJsonConstants.MODEL_NAME, model.getName());
        }
        modelNode.put(ModelDataJsonConstants.MODEL_ID, model.getId());
        ObjectNode editorJsonNode =
            (ObjectNode)
                objectMapper.readTree(
                    new String(repositoryService.getModelEditorSource(model.getId()), "utf-8"));
        modelNode.put("model", editorJsonNode);

      } catch (Exception e) {
        log.error("Error creating model JSON", e);
        throw new ActivitiException("Error creating model JSON", e);
      }
    }
    return modelNode;
  }
  @Override
  public SchemaAndValue toConnectData(String topic, byte[] value) {
    JsonNode jsonValue;
    try {
      jsonValue = deserializer.deserialize(topic, value);
    } catch (SerializationException e) {
      throw new DataException(
          "Converting byte[] to Kafka Connect data failed due to serialization error: ", e);
    }

    if (enableSchemas
        && (jsonValue == null
            || !jsonValue.isObject()
            || jsonValue.size() != 2
            || !jsonValue.has("schema")
            || !jsonValue.has("payload")))
      throw new DataException(
          "JsonDeserializer with schemas.enable requires \"schema\" and \"payload\" fields and may not contain additional fields");

    // The deserialized data should either be an envelope object containing the schema and the
    // payload or the schema
    // was stripped during serialization and we need to fill in an all-encompassing schema.
    if (!enableSchemas) {
      ObjectNode envelope = JsonNodeFactory.instance.objectNode();
      envelope.set("schema", null);
      envelope.set("payload", jsonValue);
      jsonValue = envelope;
    }

    return jsonToConnect(jsonValue);
  }
  /**
   * 获取一个用户参与的所有群组
   *
   * @param username
   * @return
   */
  private static ObjectNode getJoinedChatgroupsForIMUser(String username) {
    ObjectNode objectNode = factory.objectNode();
    // check appKey format
    if (!HTTPClientUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", APPKEY)) {
      LOGGER.error("Bad format of Appkey: " + APPKEY);
      objectNode.put("message", "Bad format of Appkey");
      return objectNode;
    }
    if (StringUtils.isBlank(username.trim())) {
      LOGGER.error("Property that named username must be provided .");
      objectNode.put("message", "Property that named username must be provided .");
      return objectNode;
    }

    try {
      URL getJoinedChatgroupsForIMUserUrl =
          HTTPClientUtils.getURL(
              Constants.APPKEY.replace("#", "/") + "/users/" + username + "/joined_chatgroups");
      objectNode =
          HTTPClientUtils.sendHTTPRequest(
              getJoinedChatgroupsForIMUserUrl, credential, null, HTTPMethod.METHOD_GET);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return objectNode;
  }
Exemple #17
0
 public F.Promise<Result> status() {
   ObjectNode status = Json.newObject();
   status.put("status", "ok");
   status.put("version", API_VERSION);
   F.Promise<JsonNode> responsePromise = F.Promise.promise(() -> status);
   return responsePromise.map(Results::ok);
 }
 /**
  * 根据频道ID重置频道
  *
  * @return
  */
 @AdminAuthenticated()
 public Result updateChannel(Long cid) {
   cache.clear(Constants.channelMouldIds_KEY + cid); // 将此Channel下的mould ids重置
   ObjectNode result = Json.newObject();
   result.put("status", 1);
   return ok(Json.toJson(result));
 }
 /**
  * 根据频道内容ID重置频道内容
  *
  * @return
  */
 @AdminAuthenticated()
 public Result deleteChmouldPro(Long cmpid) {
   cache.clear(Constants.channel_mould_pro_KEY + cmpid);
   ObjectNode result = Json.newObject();
   result.put("status", 1);
   return ok(Json.toJson(result));
 }
 private ObjectNode createObject(CSVRecord keys, CSVRecord values) {
   ObjectNode node = new ObjectNode(JsonNodeFactory.instance);
   for (int i = 0; i < keys.size(); ++i) {
     node.put(keys.get(i), values.get(i));
   }
   return node;
 }
 /** Returns a json representation of this */
 @Override
 public JsonNode toJson() {
   ObjectNode node = getFactory().objectNode();
   node.put("timeLimit", timeLimit);
   node.put("asynchronous", asynchronous);
   return node;
 }
  /**
   * Update details of a specified path id.
   *
   * @param id path id
   * @param stream pce path from json
   * @return 200 OK, 404 if given identifier does not exist
   */
  @PUT
  @Path("{path_id}")
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  public Response updatePath(@PathParam("path_id") String id, final InputStream stream) {
    log.debug("Update path by identifier {}.", id);
    try {
      ObjectNode jsonTree = (ObjectNode) mapper().readTree(stream);
      JsonNode pathNode = jsonTree.get("path");
      PcePath path = codec(PcePath.class).decode((ObjectNode) pathNode, this);
      // Assign cost
      List<Constraint> constrntList = new LinkedList<Constraint>();
      // TODO: need to uncomment below lines once CostConstraint class is ready
      if (path.costConstraint() != null) {
        // CostConstraint.Type costType = CostConstraint.Type.values()[path.constraint().cost()];
        // constrntList.add(CostConstraint.of(costType));
      }

      // Assign bandwidth. Data rate unit is in BPS.
      if (path.bandwidthConstraint() != null) {
        // TODO: need to uncomment below lines once BandwidthConstraint class is ready
        // constrntList.add(LocalBandwidthConstraint
        //        .of(path.constraint().bandwidth(), DataRateUnit.valueOf("BPS")));
      }

      Boolean result =
          nullIsNotFound(
              get(PceService.class).updatePath(TunnelId.valueOf(id), constrntList),
              PCE_PATH_NOT_FOUND);
      return Response.status(OK).entity(result.toString()).build();
    } catch (IOException e) {
      log.error("Update path failed because of exception {}.", e.toString());
      throw new IllegalArgumentException(e);
    }
  }
Exemple #23
0
  public Result addComentario() {
    DynamicForm form = new DynamicForm().bindFromRequest();
    ObjectNode response = Json.newObject();
    try {

      if (AuthManager.authCheck(session(), form)) {

        String msg = form.get("mensagem");
        String projecto = form.get("projecto");

        Projecto p = projectos.byId(Long.valueOf(projecto));
        String user_id = AuthManager.currentUsername(session("jwt"));
        Comentario c = new Comentario(msg, user_id, p);
        c.save();

        response.put("result", Json.toJson(c));
        return ok(response);
      } else {
        response.put("result", "Authorization missing or wrong");
        return forbidden(response);
      }
    } catch (Exception e) {
      response.put("exception", e.getMessage());
      return internalServerError(response);
    }
  }
 public void preStart() {
   try {
     System.out.println("=================================================");
     final Timeout timeout = new Timeout(Duration.create(1, SECONDS));
     Future<Object> rt =
         Patterns.ask(models.ChatRoom.defaultRoom, new Join(username, out), timeout);
     String result = (String) Await.result(rt, timeout.duration());
     System.out.println("-O-" + getSender());
     System.out.println("-O-" + getSelf());
     System.out.println("-O-" + getContext().self());
     System.out.println("-O-" + getContext().parent());
     if ("OK".equals(result)) {
       System.out.println("OK!");
       // go!
     } else {
       // Cannot connect, create a Json error.
       ObjectNode error = Json.newObject();
       error.put("error", result);
       // Send the error to the socket.
       out.tell(error, null);
       System.out.println("ERROR!");
       // getContext().parent().tell(PoisonPill.getInstance(), self());
       out.tell(PoisonPill.getInstance(), self());
     }
   } catch (Exception ex) {
     ex.printStackTrace();
     // force to stop actor
   }
 }
  @Test
  public void testCreateDocument() {
    running(
        fakeApplication(),
        () -> {
          try {
            DbHelper.open("1234567890", TEST_USER, TEST_USER);
            ObjectNode params = MAPPER.createObjectNode();
            ObjectNode doc = MAPPER.createObjectNode();
            doc.put("fresh", "fresh");
            params.put("collection", TEST_COLLECTION);
            params.put("data", doc);
            ObjectNode cmd = ScriptCommands.createCommand("documents", "post", params);

            JsonNode exec = CommandRegistry.execute(cmd, null);
            assertNotNull(exec);
            assertTrue(exec.isObject());
            assertNotNull(exec.get("id"));
            assertEquals(TEST_COLLECTION, exec.get("@class").asText());

          } catch (Throwable t) {
            fail(ExceptionUtils.getFullStackTrace(t));
          } finally {
            DbHelper.close(DbHelper.getConnection());
          }
        });
  }
Exemple #26
0
  /**
   * Encode the MRIB into json format.
   *
   * @param mcastRouteTable McastRouteTable
   * @param context CodecContext
   * @return result ObjectNode
   */
  @Override
  public ObjectNode encode(McastRouteTable mcastRouteTable, CodecContext context) {

    final JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
    final ObjectNode macastRouteTabNode = nodeFactory.objectNode();
    ArrayNode mcastGroupNode = context.mapper().createArrayNode();
    Optional<McastRouteTable> mcastRouteTabOpt = Optional.ofNullable(mcastRouteTable);

    // checking whether the McastRouteTable is present.
    if (mcastRouteTabOpt.isPresent()) {
      Map<IpPrefix, McastRouteGroup> mrib4 = mcastRouteTabOpt.get().getMrib4();
      Optional<Map<IpPrefix, McastRouteGroup>> mrib4Opt = Optional.ofNullable(mrib4);

      // checking whether the mrib4 is present.
      if (mrib4Opt.isPresent()) {

        for (McastRouteGroup mg : mrib4Opt.get().values()) {
          Collection<McastRouteSource> mcastRoute = mg.getSources().values();
          Optional<Collection<McastRouteSource>> mcastRouteOpt = Optional.ofNullable(mcastRoute);

          // checking whether the McastRouteSource List is present.
          if (mcastRouteOpt.isPresent()) {
            for (McastRouteSource mcastRouteSource : mcastRouteOpt.get()) {
              mcastGroupNode.add(createMcastGroupNode(mcastRouteSource, context));
            }
            macastRouteTabNode.put(MCAST_GROUP, mcastGroupNode);
          }
        }
      }
    }
    return macastRouteTabNode;
  }
  public static JsonNode build(final JsonProcessingException e, final boolean crlf) {
    final JsonLocation location = e.getLocation();
    final ObjectNode ret = JsonNodeFactory.instance.objectNode();

    /*
     * Unfortunately, for some reason, Jackson botches the column number in
     * its JsonPosition -- I cannot figure out why exactly. However, it does
     * have a correct offset into the buffer.
     *
     * The problem is that if the input has CR/LF line terminators, its
     * offset will be "off" by the number of lines minus 1 with regards to
     * what JavaScript sees as positions in text areas. Make the necessary
     * adjustments so that the caret jumps at the correct position in this
     * case.
     */
    final int lineNr = location.getLineNr();
    int offset = (int) location.getCharOffset();
    if (crlf) offset = offset - lineNr + 1;
    ret.put(LINE, lineNr);
    ret.put(OFFSET, offset);

    // Finally, put the message
    ret.put(MESSAGE, e.getOriginalMessage());
    return ret;
  }
  /** 在群组中减少一个人 */
  public static ObjectNode deleteUserFromGroup(String chatgroupid, String userName) {
    ObjectNode objectNode = factory.objectNode();
    // check appKey format
    if (!HTTPClientUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", APPKEY)) {
      LOGGER.error("Bad format of Appkey: " + APPKEY);
      objectNode.put("message", "Bad format of Appkey");
      return objectNode;
    }

    try {
      URL allMemberssByGroupIdUrl =
          HTTPClientUtils.getURL(
              Constants.APPKEY.replace("#", "/")
                  + "/chatgroups/"
                  + chatgroupid
                  + "/users/"
                  + userName);
      objectNode =
          HTTPClientUtils.sendHTTPRequest(
              allMemberssByGroupIdUrl, credential, null, HTTPMethod.METHOD_DELETE);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return objectNode;
  }
  @RequestMapping(value = "/getGRNFromOderId", method = RequestMethod.GET)
  public void getGRNFromOderId(
      HttpServletResponse httpservletResponse,
      @RequestParam String oderId,
      @RequestParam String status) {

    try {
      List<GrnVO> valueObj = grnManager.getGRNFromOderId(oderId, status);
      if (valueObj != null && valueObj.size() > 0) {
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode objectNode = new ObjectNode(mapper.getNodeFactory());
        JsonObjectUtil<GrnVO> jsonUtil = new JsonObjectUtil<GrnVO>();
        String m = jsonUtil.getJsonObjectDataDetail(valueObj, 1);
        ArrayNode node = mapper.readValue(m, ArrayNode.class);
        objectNode.put("Data", node);
        objectNode.put("success", true);
        writeJson(httpservletResponse, objectNode, mapper);
      } else {
        writeJsonString(httpservletResponse, "{\"Data\":\"Empty\",\"success\":false}");
      }
    } catch (Exception e) {
      getLogger().error(e.getMessage());
      writeJsonString(
          httpservletResponse, "{\"Data\":\"" + e.getMessage() + "\",\"success\":false}");
    }
  }
Exemple #30
0
  @Override
  public void execute() throws MojoExecutionException {
    try {
      JavaProjectBuilder builder = new JavaProjectBuilder();
      builder.addSourceTree(new File(srcDirectory, "src/main/java"));

      ObjectNode root = initializeRoot();
      ArrayNode tags = mapper.createArrayNode();
      ObjectNode paths = mapper.createObjectNode();

      root.set("tags", tags);
      root.set("paths", paths);

      builder.getClasses().forEach(jc -> processClass(jc, paths, tags));

      if (paths.size() > 0) {
        getLog().info("Generating ONOS REST API documentation...");
        genCatalog(root);

        if (!isNullOrEmpty(apiPackage)) {
          genRegistrator();
        }
      }

      project.addCompileSourceRoot(new File(dstDirectory, GEN_SRC).getPath());

    } catch (Exception e) {
      getLog().warn("Unable to generate ONOS REST API documentation", e);
      throw e;
    }
  }