Java Code Examples for com.google.gson.JsonObject#toString()

The following examples show how to use com.google.gson.JsonObject#toString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StatsController.java    From EserKnife with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/shards")
@ResponseBody
public Object shards(@RequestParam("indexName") String indexName,
        @RequestParam("clusterName") String clusterName) {
    try {
        JsonObject object;
        String targetPath = "/"+indexName+"/_stats?level=shards&human&pretty";
        String targetMethod = "GET";
        JestResult jestResult = (JestResult) jestService.httpProxy(clusterName,targetPath,targetMethod,null);
        object=jestResult.getJsonObject();
        return object.toString();
    } catch (Exception e) {
        LOG.error("获取shards 信息失败:",e);
        return e.getMessage();
    }
}
 
Example 2
Source File: WxQRUtil.java    From util4j with Apache License 2.0 6 votes vote down vote up
/**
 * 生成临时二维码
 * http请求方式: POST URL:
 * https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN
 * POST数据格式:json POST数据例子:{"expire_seconds": 604800, "action_name": "QR_SCENE",
 * "action_info": {"scene": {"scene_id": 123}}}
 * @param scene_id
 * @return
 */
public static String getTemporaryQR_senceId(String accessToken, int expire_seconds, int scene_id) {
	String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
	JsonObject content = new JsonObject();
	content.addProperty("action_name", "QR_SCENE");
	content.addProperty("expire_seconds", expire_seconds);
	JsonObject scene = new JsonObject();
	scene.addProperty("scene_id", scene_id);
	JsonObject action_info = new JsonObject();
	action_info.add("scene", scene);
	content.add("action_info", action_info);
	// 发送给微信服务器的数据
	String jsonStr = content.toString();
	String qrurl = null;
	try {
		HttpUtil http = new HttpUtil();
		byte[] data = http.httpsPost(url, jsonStr.getBytes());
		JsonObject json = new JsonParser().parse(new String(data)).getAsJsonObject();
		qrurl = json.get("url").getAsString();
	} catch (Exception e) {
		e.printStackTrace();
	}
	return qrurl;
}
 
Example 3
Source File: VotifierProtocol2Encoder.java    From NuVotifier with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, VoteRequest req, ByteBuf buf) throws Exception {
    JsonObject object = new JsonObject();
    JsonObject payloadObject = req.getVote().serialize();
    payloadObject.addProperty("challenge", req.getChallenge());
    String payload = payloadObject.toString();
    object.addProperty("payload", payload);

    // Generate the MAC
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(key);
    mac.update(payload.getBytes(StandardCharsets.UTF_8));
    String computed = Base64.getEncoder().encodeToString(mac.doFinal());
    object.addProperty("signature", computed);

    // JSON message is ready for encoding.
    String finalMessage = object.toString();
    buf.writeShort(MAGIC);
    buf.writeShort(finalMessage.length());
    ByteBuf messageBytes = Unpooled.copiedBuffer(finalMessage, StandardCharsets.UTF_8);
    buf.writeBytes(messageBytes);
    messageBytes.release();
}
 
Example 4
Source File: MockJobAuditModel.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
@Override
public String getRestModelJson() {
    final JsonObject json = new JsonObject();
    json.addProperty("id", id);
    json.addProperty("configId", configId);
    json.addProperty("name", name);
    json.addProperty("eventType", eventType);

    final JsonObject auditInfo = new JsonObject();
    auditInfo.addProperty("timeAuditCreated", timeAuditCreated);
    auditInfo.addProperty("timeLastSent", timeLastSent);
    auditInfo.addProperty("status", status);

    json.add("auditJobStatusModel", auditInfo);
    json.addProperty("errorMessage", errorMessage);
    json.addProperty("errorStackTrace", errorStackTrace);
    return json.toString();
}
 
Example 5
Source File: APIShareFolderResponse.java    From sync-service with Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
	JsonObject jResponse = new JsonObject();

	if (getSuccess()) {

		JsonArray sharedTo = new JsonArray();

		for (User user : workspace.getUsers()) {
			JsonObject jUser = parseUser(user);
			sharedTo.add(jUser);
		}

		jResponse.add("shared_to", sharedTo);

	} else {
		jResponse.addProperty("error", getErrorCode());
		jResponse.addProperty("description", getDescription());
	}

	return jResponse.toString();
}
 
Example 6
Source File: RuleExecutorTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Test run.
 *
 * @throws Exception the exception
 */
@Test
public void testRunWithEmptyDS() throws Exception{
    
    PowerMockito.mockStatic(ESUtils.class);
    PowerMockito.when(ESUtils.getEsUrl()).thenReturn("");
    PowerMockito.when(ESUtils.publishMetrics(anyMap(),anyString())).thenReturn(Boolean.TRUE);
    
    
    JsonObject input = new JsonObject();
    PowerMockito.mockStatic(CommonUtils.class);
    input.addProperty("ruleName", "test");
    input.addProperty(PacmanSdkConstants.DATA_SOURCE_KEY, "");
    String[] args = {input.toString()};
    PowerMockito.mockStatic(RuleExecutor.class);
    RuleExecutor.main(args);    
}
 
Example 7
Source File: TimerChangeJobDefinitionSuspensionStateJobHandler.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Override
public String toCanonicalString() {
  JsonObject json = JsonUtil.createObject();

  JsonUtil.addField(json, JOB_HANDLER_CFG_BY, by);
  JsonUtil.addField(json, JOB_HANDLER_CFG_JOB_DEFINITION_ID, jobDefinitionId);
  JsonUtil.addField(json, JOB_HANDLER_CFG_PROCESS_DEFINITION_KEY, processDefinitionKey);
  JsonUtil.addField(json, JOB_HANDLER_CFG_INCLUDE_JOBS, includeJobs);
  JsonUtil.addField(json, JOB_HANDLER_CFG_PROCESS_DEFINITION_ID, processDefinitionId);

  if (isTenantIdSet) {
    if (tenantId != null) {
      JsonUtil.addField(json, JOB_HANDLER_CFG_PROCESS_DEFINITION_TENANT_ID, tenantId);
    } else {
      JsonUtil.addNullField(json, JOB_HANDLER_CFG_PROCESS_DEFINITION_TENANT_ID);
    }
  }

  return json.toString();
}
 
Example 8
Source File: StatelessFlowFile.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    JsonObject attributes = new JsonObject();
    this.attributes.forEach(attributes::addProperty);

    JsonObject result = new JsonObject();
    result.add("attributes", attributes);

    return result.toString();
}
 
Example 9
Source File: KvsHelper.java    From adamant-android with GNU General Public License v3.0 5 votes vote down vote up
public <T> Transaction<TransactionStateAsset> transformToTransaction(String key, boolean encrypted, T object) throws EncryptionException {
    JsonObject valueObject = new JsonObject();
    valueObject.add("payload", gson.toJsonTree(object));
    String valueString = valueObject.toString();

    KeyPair keyPair = api.getKeyPair();
    Account account = api.getAccount();

    if (keyPair == null || account == null){return null;}

    Transaction<TransactionStateAsset> transaction = new Transaction<>();
    transaction.setType(Transaction.STATE);
    transaction.setSenderId(account.getAddress());
    transaction.setSenderPublicKey(keyPair.getPublicKeyString().toLowerCase());
    transaction.setTimestamp(api.getEpoch() - api.getServerTimeDelta());

    TransactionState state = null;
    if (encrypted){
        state = encryptor.encryptState(key, valueString, keyPair.getSecretKeyString());
    } else {
        state = new TransactionState();
        state.setKey(key);
        state.setType(0);
        state.setValue(valueString);
    }

    TransactionStateAsset asset = new TransactionStateAsset();
    asset.setState(state);

    transaction.setAsset(asset);
    String sign = encryptor.createTransactionSignature(transaction, keyPair);
    transaction.setSignature(sign);

    return transaction;
}
 
Example 10
Source File: Market.java    From btdex with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Format the fields in a Json format.
 * 
 * @param fields
 * @throws Exception
 */
public String format(HashMap<String, String> fields) {
	JsonObject params = new JsonObject();
	for (String key: fields.keySet()) {
		params.addProperty(key, fields.get(key));			
	}
	return params.toString();
}
 
Example 11
Source File: AdminVersions.java    From fenixedu-cms with GNU Lesser General Public License v3.0 5 votes vote down vote up
@RequestMapping(value = "{slugSite}/{slugPost}/data", method = RequestMethod.POST, produces = JSON)
@ResponseBody public String versionData(@PathVariable String slugSite,
                          @PathVariable String slugPost,
                          @RequestParam(required = false) PostContentRevision revision) {
  Site site = Site.fromSlug(slugSite);
  ensureCanDoThis(site, Permission.EDIT_POSTS);
  Post post = site.postForSlug(slugPost);

  if (revision == null) {
    revision = post.getLatestRevision();
  }

  if (revision.getPost() != post) {
    throw new RuntimeException("Invalid Revision");
  }

  JsonObject json = new JsonObject();

  json.add("content", revision.getBody().json());
  json.addProperty("modifiedAt", revision.getRevisionDate().toString());
  json.addProperty("user", revision.getCreatedBy().getUsername());
  json.addProperty("userName", revision.getCreatedBy().getProfile().getDisplayName());
  json.addProperty("id", revision.getExternalId());
  json.addProperty("next", ofNullable(revision.getNext()).map(x -> x.getExternalId()).orElse(null));
  json.addProperty("previous", ofNullable(revision.getPrevious()).map(x -> x.getExternalId()).orElse(null));

  if (revision.getPrevious() != null) {
    json.add("previousContent", revision.getPrevious().getBody().json());
  }

  return json.toString();
}
 
Example 12
Source File: MCRWCMSFileBrowserResource.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@GET
@Path("/files")
public String getFiles(@QueryParam("path") String path, @QueryParam("type") String type) throws IOException {
    File dir = new File(MCRWebPagesSynchronizer.getWCMSDataDir().getPath() + path);
    JsonObject jsonObj = new JsonObject();
    JsonArray jsonArray = new JsonArray();
    File[] fileArray = dir.listFiles();
    if (fileArray != null) {
        for (File file : fileArray) {
            String mimetype = Files.probeContentType(file.toPath());
            if (mimetype != null && (type.equals("images") ? mimetype.split("/")[0].equals("image")
                : !mimetype.split("/")[1].contains("xml"))) {
                JsonObject fileJsonObj = new JsonObject();
                fileJsonObj.addProperty("name", file.getName());
                fileJsonObj.addProperty("path", context.getContextPath() + path + "/" + file.getName());
                if (file.isDirectory()) {
                    fileJsonObj.addProperty("type", "folder");
                } else {
                    fileJsonObj.addProperty("type", mimetype.split("/")[0]);
                }
                jsonArray.add(fileJsonObj);
            }
        }
        jsonObj.add("files", jsonArray);
        return jsonObj.toString();
    }
    return "";
}
 
Example 13
Source File: AttachmentMessageEventFactory.java    From messenger4j with MIT License 5 votes vote down vote up
private List<Attachment> getAttachmentsFromJsonArray(JsonArray attachmentsJsonArray) {
  final List<Attachment> attachments = new ArrayList<>(attachmentsJsonArray.size());
  for (JsonElement attachmentJsonElement : attachmentsJsonArray) {
    final JsonObject attachmentJsonObject = attachmentJsonElement.getAsJsonObject();
    final String type =
        getPropertyAsString(attachmentJsonObject, PROP_TYPE)
            .map(String::toUpperCase)
            .orElseThrow(IllegalArgumentException::new);
    switch (type) {
      case "IMAGE":
      case "AUDIO":
      case "VIDEO":
      case "FILE":
        final URL url =
            getPropertyAsString(attachmentJsonObject, PROP_PAYLOAD, PROP_URL)
                .map(this::getUrlFromString)
                .orElseThrow(IllegalArgumentException::new);
        attachments.add(new RichMediaAttachment(Type.valueOf(type), url));
        break;
      case "LOCATION":
        final Double latitude =
            getPropertyAsDouble(attachmentJsonObject, PROP_PAYLOAD, PROP_COORDINATES, PROP_LAT)
                .orElseThrow(IllegalArgumentException::new);
        final Double longitude =
            getPropertyAsDouble(attachmentJsonObject, PROP_PAYLOAD, PROP_COORDINATES, PROP_LONG)
                .orElseThrow(IllegalArgumentException::new);
        attachments.add(new LocationAttachment(latitude, longitude));
        break;
      case "FALLBACK":
        final String json = attachmentJsonObject.toString();
        attachments.add(new FallbackAttachment(json));
        break;
      default:
        throw new IllegalArgumentException("attachment type '" + type + "' is not supported");
    }
  }
  return attachments;
}
 
Example 14
Source File: JsonUtil.java    From camunda-bpm-identity-keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a specific member of a given JsonObject as JsonArray.
 * @param jsonObject the JsonObject
 * @param memberName the name of the member to return
 * @return the JsonArray value of the member or {@code null} if no such member exists
 * @throws JsonException in case of errors
 */
public static JsonArray getJsonArray(JsonObject jsonObject, String memberName) throws JsonException {
	if (jsonObject == null) return new JsonArray();
	try {
		JsonElement element = jsonObject.get(memberName);
		return element == null ? new JsonArray() : element.getAsJsonArray();
	} catch (ClassCastException | IllegalStateException ex) {
		throw new JsonException("Unable to get '" + memberName + "' from JsonObject " + jsonObject.toString(), ex);
	}
}
 
Example 15
Source File: JsonUtil.java    From camunda-bpm-identity-keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a specific member of a given JsonObject as JsonObject.
 * @param jsonObject the JsonObject
 * @param memberName the name of the member to return
 * @return the JsonObject value of the member or {@code null} if no such member exists
 * @throws JsonException in case of errors
 */
public static JsonObject getJsonObject(JsonObject jsonObject, String memberName) throws JsonException {
	if (jsonObject == null) return null;
	try {
		JsonElement element = jsonObject.get(memberName);
		return element == null ? null : element.getAsJsonObject();
	} catch (ClassCastException | IllegalStateException ex) {
		throw new JsonException("Unable to get '" + memberName + "' from JsonObject " + jsonObject.toString(), ex);
	}
}
 
Example 16
Source File: MCRWCMSFileBrowserResource.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@GET
@Path("/folder")
public String getFolders() throws IOException, ParserConfigurationException, SAXException {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    File file = new File(MCRLayoutUtilities.getNavigationURL().getPath());
    Document doc = docBuilder.parse(file);
    getallowedPaths(doc.getDocumentElement());

    File dir = MCRWebPagesSynchronizer.getWCMSDataDir();
    JsonObject jsonObj = new JsonObject();
    jsonObj.add("folders", getFolder(dir, false));
    return jsonObj.toString();
}
 
Example 17
Source File: NGSICKANSinkTest.java    From fiware-cygnus with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
public void testNativeTypeColumnBatch() throws CygnusBadConfiguration, CygnusRuntimeError, CygnusPersistenceError, CygnusBadContextData {
    NGSICKANSink ngsickanSink= new NGSICKANSink();
    ngsickanSink.configure(createContextforNativeTypes(null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null));
    NGSIBatch batch = prepaireBatch();
    String destination = "someDestination";
    String entityId = ""; //default
    try {
        batch.startIterator();
        NGSIGenericAggregator aggregator = new NGSIGenericColumnAggregator();
        while (batch.hasNext()) {
            destination = batch.getNextDestination();
            ArrayList<NGSIEvent> events = batch.getNextEvents();
            aggregator.setService(events.get(0).getServiceForNaming(false));
            aggregator.setServicePathForData(events.get(0).getServicePathForData());
            aggregator.setServicePathForNaming(events.get(0).getServicePathForNaming(false, false));
            aggregator.setEntityForNaming(events.get(0).getEntityForNaming(false, false, false));
            aggregator.setEntityType(events.get(0).getEntityTypeForNaming(false, false));
            aggregator.setAttribute(events.get(0).getAttributeForNaming(false));
            aggregator.setEnableUTCRecvTime(true);
            aggregator.setOrgName(ngsickanSink.buildOrgName(aggregator.getService()));
            aggregator.setPkgName(ngsickanSink.buildPkgName(aggregator.getService(), aggregator.getServicePathForNaming(), entityId));
            aggregator.setResName(ngsickanSink.buildResName(aggregator.getEntityForNaming(), entityId));
            aggregator.initialize(events.get(0));
            aggregator.setAttrMetadataStore(true);
            for (NGSIEvent event : events) {
                aggregator.aggregate(event);
            } // for
        }
        ArrayList<JsonObject> jsonObjects = NGSIUtils.linkedHashMapToJsonListWithOutEmptyMD(aggregator.getAggregationToPersist());
        String aggregation = "";
        for (JsonObject jsonObject : jsonObjects) {
            if (aggregation.isEmpty()) {
                aggregation = jsonObject.toString();
            } else {
                aggregation += "," + jsonObject;
            }
        }
        System.out.println(aggregation);
    } catch (Exception e) {
        fail();
    }
}
 
Example 18
Source File: BranchesAndPullRequestsParametersPreprocessor.java    From TeamCity.SonarQubePlugin with Apache License 2.0 4 votes vote down vote up
@Override
public void fixRunBuildParameters(SRunningBuild build, Map<String, String> runParameters, Map<String, String> buildParams) {

    if (build.getBuildFeaturesOfType(BranchesAndPullRequestsBuildFeature.BUILD_FEATURE_TYPE).isEmpty() || buildParams.containsKey(SQS_SYSENV)) {
        // Currently only GitHub is supported => if feature defined, it is for GitHub
        // ParametersPreprocessor is called for each steps (or could be defined manually). So if sysenv already defined, skip process.
        return;
    }

    if (!isTeamCityMinimalVersion(getServerVersionInfo())) {
        build.getBuildLog().message(
                String.format("Build feature '%s' requiers TeamCity 2019.2 or above", BranchesAndPullRequestsBuildFeature.BUILD_FEATURE_NAME),
                Status.ERROR, MessageAttrs.attrs());
        return;
    }

    String branchIsDefault = buildParams.get("teamcity.build.branch.is_default");
    if (StringUtils.isEmpty(branchIsDefault) || Boolean.TRUE.equals(Boolean.valueOf(branchIsDefault))) {
        // No information or default branch, nothing to provide
        return;
    }

    final String type;
    final JsonObject json = new JsonObject();
    final String prNumber = buildParams.get("teamcity.pullRequest.number");
    if (StringUtils.isEmpty(prNumber)) {
        // Branch
        type = "branch";
        final String vcsBranch = buildParams.get("vcsroot.branch");
        json.addProperty("sonar.branch.name", buildParams.get("teamcity.build.branch"));
        json.addProperty("sonar.branch.target", vcsBranch.substring(vcsBranch.indexOf("refs/heads/") + 11));
    } else {
        // Pull Request
        type = "pull-request";
        String repo = buildParams.get("vcsroot.url");
        repo = repo.replaceFirst("^git@.*:", "");
        repo = repo.replaceFirst("^https?://[^/]*/", "");
        repo = repo.replaceFirst("\\.git$", "");

        json.addProperty("sonar.pullrequest.key", prNumber);
        json.addProperty("sonar.pullrequest.branch", buildParams.get("teamcity.pullRequest.title"));
        json.addProperty("sonar.pullrequest.base", buildParams.get("teamcity.pullRequest.target.branch"));
        json.addProperty("sonar.pullrequest.provider", "github");
        json.addProperty("sonar.pullrequest.github.repository", repo);
    }

    final String jsonString = json.toString();
    build.getBuildLog().message(String.format("SonarQube plugin detects %s, '%s' set with '%s'", type, SQS_SYSENV, jsonString), Status.NORMAL,
            MessageAttrs.attrs());
    buildParams.put(SQS_SYSENV, jsonString);
}
 
Example 19
Source File: ClientStateMachine.java    From malmo with MIT License 4 votes vote down vote up
private void sendData()
{
    TCPUtils.LogSection ls = new TCPUtils.LogSection("Sending data");
    Minecraft.getMinecraft().mcProfiler.endStartSection("malmoSendData");
    // Create the observation data:
    String data = "";
    Minecraft.getMinecraft().mcProfiler.startSection("malmoGatherObservationJSON");
    if (currentMissionBehaviour() != null && currentMissionBehaviour().observationProducer != null)
    {
        JsonObject json = new JsonObject();
        currentMissionBehaviour().observationProducer.writeObservationsToJSON(json, currentMissionInit());
        data = json.toString();
    }
    Minecraft.getMinecraft().mcProfiler.endStartSection("malmoSendTCPObservations");

    ClientAgentConnection cac = currentMissionInit().getClientAgentConnection();

    if (data != null && data.length() > 2 && cac != null) // An empty json string will be "{}" (length 2) - don't send these.
    {
        if (AddressHelper.getMissionControlPort() == 0) {
            if (envServer != null) {
                envServer.observation(data);
            }
        } else {
            // Bung the whole shebang off via TCP:
            if (this.observationSocket.sendTCPString(data)) {
                this.failedTCPObservationSendCount = 0;
            } else {
                // Failed to send observation message.
                this.failedTCPObservationSendCount++;
                TCPUtils.Log(Level.WARNING, "Observation signal delivery failure count at " + this.failedTCPObservationSendCount);
                ClientStateMachine.this.getScreenHelper().addFragment("ERROR: Agent missed observation signal", TextCategory.TXT_CLIENT_WARNING, 5000);
            }
        }
    }

    Minecraft.getMinecraft().mcProfiler.endStartSection("malmoGatherRewardSignal");
    // Now create the reward signal:
    if (currentMissionBehaviour() != null && currentMissionBehaviour().rewardProducer != null && cac != null)
    {
        MultidimensionalReward reward = new MultidimensionalReward();
        currentMissionBehaviour().rewardProducer.getReward(currentMissionInit(), reward);
        if (!reward.isEmpty())
        {
            String strReward = reward.getAsSimpleString();
            Minecraft.getMinecraft().mcProfiler.startSection("malmoSendTCPReward");

            ScoreHelper.logReward(strReward);

            if (AddressHelper.getMissionControlPort() == 0) {
                // MalmoEnvServer - reward
                if (envServer != null) {
                    envServer.addRewards(reward.getRewardTotal());
                }
            } else {
                if (this.rewardSocket.sendTCPString(strReward)) {
                    this.failedTCPRewardSendCount = 0; // Reset the count of consecutive TCP failures.
                } else {
                    // Failed to send TCP message - probably because the agent has quit under our feet.
                    // (This happens a lot when developing a Python agent - the developer has no easy way to quit
                    // the agent cleanly, so tends to kill the process.)
                    this.failedTCPRewardSendCount++;
                    TCPUtils.Log(Level.WARNING, "Reward signal delivery failure count at " + this.failedTCPRewardSendCount);
                    ClientStateMachine.this.getScreenHelper().addFragment("ERROR: Agent missed reward signal", TextCategory.TXT_CLIENT_WARNING, 5000);
                }
            }
        }
    }
    Minecraft.getMinecraft().mcProfiler.endSection();

    int maxFailedTCPSendCount = 0;
    for (VideoHook hook : this.videoHooks)
    {
        if (hook.failedTCPSendCount > maxFailedTCPSendCount)
            maxFailedTCPSendCount = hook.failedTCPSendCount;
    }
    if (maxFailedTCPSendCount > 0)
        TCPUtils.Log(Level.WARNING, "Video signal failure count at " + maxFailedTCPSendCount);
    // Check that our messages are getting through:
    int maxFailed = Math.max(this.failedTCPRewardSendCount, maxFailedTCPSendCount);
    maxFailed = Math.max(maxFailed, this.failedTCPObservationSendCount);
    if (maxFailed > FailedTCPSendCountTolerance)
    {
        // They're not - and we've exceeded the count of allowed TCP failures.
        System.out.println("ERROR: TCP messages are not getting through - quitting mission.");
        this.wantsToQuit = true;
        this.quitCode = MalmoMod.AGENT_UNRESPONSIVE_CODE;
    }
    ls.close();
}
 
Example 20
Source File: JsonUtils.java    From kurento-java with Apache License 2.0 3 votes vote down vote up
public static String toJsonMessage(Message message) {

    if (message.getSessionId() != null && INJECT_SESSION_ID) {

      JsonObject jsonObject = JsonUtils.toJsonObject(message);

      JsonObject objectToInjectSessionId;
      if (message instanceof Request) {

        objectToInjectSessionId = convertToObject(jsonObject, PARAMS_PROPERTY);

      } else {

        Response<?> response = (Response<?>) message;
        if (response.getError() == null) {

          objectToInjectSessionId = convertToObject(jsonObject, RESULT_PROPERTY);
        } else {

          objectToInjectSessionId = convertToObject(jsonObject, ERROR_PROPERTY, DATA_PROPERTY);
        }
      }

      objectToInjectSessionId.addProperty(JsonRpcConstants.SESSION_ID_PROPERTY,
          message.getSessionId());

      return jsonObject.toString();
    }

    return JsonUtils.toJson(message);

  }