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

The following examples show how to use com.google.gson.JsonArray#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: SolrWaveIndexerImpl.java    From swellrt with Apache License 2.0 7 votes vote down vote up
private void postUpdateToSolr(ReadableWaveletData wavelet, JsonArray docsJson) {
  PostMethod postMethod =
      new PostMethod(solrBaseUrl + "/update/json?commit=true");
  try {
    RequestEntity requestEntity =
        new StringRequestEntity(docsJson.toString(), "application/json", "UTF-8");
    postMethod.setRequestEntity(requestEntity);

    HttpClient httpClient = new HttpClient();
    int statusCode = httpClient.executeMethod(postMethod);
    if (statusCode != HttpStatus.SC_OK) {
      throw new IndexException(wavelet.getWaveId().serialise());
    }
  } catch (IOException e) {
    throw new IndexException(String.valueOf(wavelet.getWaveletId()), e);
  } finally {
    postMethod.releaseConnection();
  }
}
 
Example 2
Source File: SolrWaveIndexerImpl.java    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
private void postUpdateToSolr(ReadableWaveletData wavelet, JsonArray docsJson) {
  PostMethod postMethod =
      new PostMethod(solrBaseUrl + "/update/json?commit=true");
  try {
    RequestEntity requestEntity =
        new StringRequestEntity(docsJson.toString(), "application/json", "UTF-8");
    postMethod.setRequestEntity(requestEntity);

    HttpClient httpClient = new HttpClient();
    int statusCode = httpClient.executeMethod(postMethod);
    if (statusCode != HttpStatus.SC_OK) {
      throw new IndexException(wavelet.getWaveId().serialise());
    }
  } catch (IOException e) {
    throw new IndexException(String.valueOf(wavelet.getWaveletId()), e);
  } finally {
    postMethod.releaseConnection();
  }
}
 
Example 3
Source File: CDRRestController.java    From openvidu with Apache License 2.0 6 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<String> listCdrFiles() {

	log.info("REST API: GET /cdr");

	String cdrPath = openviduConfig.getOpenviduCdrPath();
	JsonArray cdrFiles = new JsonArray();

	try (Stream<Path> walk = Files.walk(Paths.get(cdrPath))) {
		List<String> result = walk.filter(Files::isRegularFile).map(x -> x.getFileName().toString())
				.collect(Collectors.toList());
		result.forEach(fileName -> cdrFiles.add(fileName));
	} catch (IOException e) {
		log.error("Error listing CDR files in path {}: {}", cdrPath, e.getMessage());
	}

	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setContentType(MediaType.APPLICATION_JSON);
	return new ResponseEntity<>(cdrFiles.toString(), responseHeaders, HttpStatus.OK);
}
 
Example 4
Source File: ATLASUtil.java    From Criteria2Query with Apache License 2.0 6 votes vote down vote up
public static String getRecordCount(JsonArray array)
		throws UnsupportedEncodingException, IOException, ClientProtocolException {
	HttpPost httppost = new HttpPost(recordcounturl);
	httppost.setHeader("Content-Type", "application/json");
	StringEntity se = new StringEntity(array.toString());
	httppost.setEntity(se);
	startTime = System.currentTimeMillis();
	HttpResponse httpresponse = new DefaultHttpClient().execute(httppost);
	endTime = System.currentTimeMillis();
	System.out.println("statusCode:" + httpresponse.getStatusLine().getStatusCode());
	System.out.println("Call API time (unit:millisecond):" + (endTime - startTime));

	if (httpresponse.getStatusLine().getStatusCode() == 200) {
		String strResult = EntityUtils.toString(httpresponse.getEntity());
		return strResult;
	} else {
		return null;
	}
}
 
Example 5
Source File: AdminThemes.java    From fenixedu-cms with GNU Lesser General Public License v3.0 6 votes vote down vote up
@RequestMapping(value = "{type}/listFiles", method = RequestMethod.GET)
@ResponseBody
public String listFiles(Model model, @PathVariable(value = "type") String type) {
    CmsSettings.getInstance().ensureCanManageThemes();
    CMSTheme theme = CMSTheme.forType(type);
    Collection<CMSThemeFile> totalFiles = theme.getFiles().getFiles();
    JsonArray result = new JsonArray();
    for (CMSThemeFile file : totalFiles) {
        JsonObject obj = new JsonObject();
        obj.addProperty("name", file.getFileName());
        obj.addProperty("path", file.getFullPath());
        obj.addProperty("size", file.getFileSize());
        obj.addProperty("contentType", file.getContentType());
        obj.addProperty("modified", file.getLastModified().toString());
        result.add(obj);
    }

    return result.toString();
}
 
Example 6
Source File: DockerAccessWithHcClientTest.java    From docker-maven-plugin with Apache License 2.0 6 votes vote down vote up
private void givenImageIdRepoTagPairs(Pair<String, String>... idRepoTagPairs) throws IOException {
    final JsonArray array = new JsonArray();
    for(Pair<String, String> idNamePair : idRepoTagPairs) {
        JsonObject imageObject = new JsonObject();
        imageObject.addProperty(ImageDetails.ID, idNamePair.getLeft());
        JsonArray repoTags = new JsonArray();
        repoTags.add(idNamePair.getRight());
        imageObject.add(ImageDetails.REPO_TAGS, repoTags);
        array.add(imageObject);
    }

    new Expectations() {{
        mockDelegate.get(anyString, 200);
        result = array.toString();
    }};
}
 
Example 7
Source File: SwiftSegmentService.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create the appropriate manifest structure for a static large object (SLO).
 * The number of object segments is limited to a configurable amount, default 1000. Each segment,
 * except for the final one, must be at least 1 megabyte (configurable).
 *
 * @param objects Ordered list of segments
 * @return ETag returned by the simple upload total size of segment uploaded path of segment
 */
public String manifest(final String container, final List<StorageObject> objects) {
    JsonArray manifestSLO = new JsonArray();
    for(StorageObject s : objects) {
        JsonObject segmentJSON = new JsonObject();
        // this is the container and object name in the format {container-name}/{object-name}
        segmentJSON.addProperty("path", String.format("/%s/%s", container, s.getName()));
        // MD5 checksum of the content of the segment object
        segmentJSON.addProperty("etag", s.getMd5sum());
        segmentJSON.addProperty("size_bytes", s.getSize());
        manifestSLO.add(segmentJSON);
    }
    return manifestSLO.toString();
}
 
Example 8
Source File: DockerAccessWithHcClientTest.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
private void givenContainerIdImagePairs(Pair<String, String>... idNamePairs) throws IOException {
    final JsonArray array = new JsonArray();
    for(Pair<String, String> idNamePair : idNamePairs) {
        JsonObject idNameObject = new JsonObject();
        idNameObject.addProperty(ContainersListElement.ID, idNamePair.getLeft());
        idNameObject.addProperty(ContainersListElement.IMAGE, idNamePair.getRight());
        array.add(idNameObject);
    }

    new Expectations() {{
        mockDelegate.get(anyString, 200);
        result = array.toString();
    }};
}
 
Example 9
Source File: ClusterComputeResourceService.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
/**
 * @param clusterConfigInfoEx
 * @return
 */
private String getVmRestartPriority(ClusterConfigInfoEx clusterConfigInfoEx) {
    JsonArray resultArray = new JsonArray();
    List<ClusterDasVmConfigInfo> dasVmConfig = clusterConfigInfoEx.getDasVmConfig();
    for (ClusterDasVmConfigInfo clusterDasVmConfigInfo : dasVmConfig) {
        JsonObject vmRestartPriority = new JsonObject();
        vmRestartPriority.addProperty(VM_ID, clusterDasVmConfigInfo.getKey().getValue());
        vmRestartPriority.addProperty(RESTART_PRIORITY, clusterDasVmConfigInfo.getDasSettings().getRestartPriority());
        resultArray.add(vmRestartPriority);
    }
    return resultArray.toString();
}
 
Example 10
Source File: KcaFleetViewService.java    From kcanotify with GNU General Public License v3.0 5 votes vote down vote up
private void sendReport(Exception e, int type) {
    error_flag = true;
    String data_str;
    dbHelper = new KcaDBHelper(getApplicationContext(), null, KCANOTIFY_DB_VERSION);
    JsonArray data = dbHelper.getJsonArrayValue(DB_KEY_DECKPORT);
    if (data == null) {
        data_str = "data is null";
    } else {
        data_str = data.toString();
    }
    if (mView != null) mView.setVisibility(GONE);

    KcaDBHelper helper = new KcaDBHelper(getApplicationContext(), null, KCANOTIFY_DB_VERSION);
    helper.recordErrorLog(ERROR_TYPE_FLEETVIEW, "fleetview", "FV_".concat(String.valueOf(type)), data_str, getStringFromException(e));
}
 
Example 11
Source File: UCChannel.java    From UltimateChat with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String toString() {
    JsonArray array = new JsonArray();
    for (Entry<Object, Object> prop : properties.entrySet()) {
        JsonObject json = new JsonObject();
        json.addProperty((String) prop.getKey(), prop.getValue().toString());
        array.add(json);
    }
    return array.toString();
}
 
Example 12
Source File: MCRWCMSNavigationResource.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a json object containing all available templates. 
 */
@GET
@Path("templates")
@Produces(MediaType.APPLICATION_JSON)
public String getTemplates(@Context ServletContext servletContext) throws Exception {
    // templates of navigation.xml
    Document xml = MCRWCMSNavigationUtils.getNavigationAsXML();
    List<Element> elementList = TEMPLATE_PATH.evaluate(xml);
    HashSet<String> entries = elementList.stream()
        .map(e -> e.getAttributeValue("template"))
        .collect(Collectors.toCollection(HashSet::new));

    // templates by folder
    String templatePath = MCRConfiguration2.getString("MCR.WCMS2.templatePath").orElse("/templates/master/");
    Set<String> resourcePaths = servletContext.getResourcePaths(templatePath);
    if (resourcePaths != null) {
        for (String resourcepath : resourcePaths) {
            String newResourcepath = resourcepath.substring(templatePath.length(), resourcepath.length() - 1);
            entries.add(newResourcepath);
        }
    }

    // create returning json
    JsonArray returnArr = new JsonArray();
    for (String entry : entries) {
        returnArr.add(new JsonPrimitive(entry));
    }
    return returnArr.toString();
}
 
Example 13
Source File: AlumniInformationAction.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
private String createJsonArray(Map<Long, Integer> registrationsByDay) {
    JsonArray data = new JsonArray();
    for (Entry<Long, Integer> entry : registrationsByDay.entrySet()) {
        JsonArray dataEntry = new JsonArray();
        dataEntry.add(new JsonPrimitive(entry.getKey()));
        dataEntry.add(new JsonPrimitive(entry.getValue()));
        data.add(dataEntry);
    }
    return data.toString();
}
 
Example 14
Source File: StoreController.java    From java-trader with Apache License 2.0 5 votes vote down vote up
@RequestMapping(path=URL_PREFIX+"/store/keys/",
method=RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public String getStoreKeys(){
    KVStoreIterator storeIterator = kvStoreService.getStore(null).iterator();
    JsonArray array = new JsonArray();
    while(storeIterator.hasNext()) {
        String key = storeIterator.next();
        if ( StringUtil.isEmpty(key)) {
            break;
        }
        array.add(key);
    }
    return array.toString();
}
 
Example 15
Source File: KeyStoreCipher.java    From adamant-android with GNU General Public License v3.0 5 votes vote down vote up
private String encryptLargeBlock(String alias, CharSequence sequence) throws Exception {
    alias = KEY_ALIAS_PREFIX + alias;

    KeyPair securityKeyPair = getKeyPair(alias);

    final Cipher cipher = Cipher.getInstance(TRANSFORMATION);
    cipher.init(Cipher.ENCRYPT_MODE, securityKeyPair.getPublic());

    JsonArray blocks = new JsonArray();

    int index = 0;
    int maxChars = MAX_BLOCK_SIZE >>> 1;

    while (index < sequence.length()) {
        int count = maxChars;
        int endPosition = index + count;

        if (endPosition >= sequence.length() - 1) {
            count = sequence.length()  - index;
            endPosition = index + count;
        }

        CharSequence charSequence = sequence.subSequence(index, endPosition);
        blocks.add(
                Base64.encodeToString(
                        cipher.doFinal(
                                charSequence.toString().getBytes()
                        ),
                        Base64.NO_PADDING | Base64.NO_WRAP
                )
        );

        index += count;
    }

    return blocks.toString();
}
 
Example 16
Source File: KcaFleetViewService.java    From kcanotify_h5-master with GNU General Public License v3.0 5 votes vote down vote up
private void sendReport(Exception e, int type) {
    error_flag = true;
    String data_str;
    dbHelper = new KcaDBHelper(getApplicationContext(), null, KCANOTIFY_DB_VERSION);
    JsonArray data = dbHelper.getJsonArrayValue(DB_KEY_DECKPORT);
    if (data == null) {
        data_str = "data is null";
    } else {
        data_str = data.toString();
    }
    if (mView != null) mView.setVisibility(GONE);

    KcaDBHelper helper = new KcaDBHelper(getApplicationContext(), null, KCANOTIFY_DB_VERSION);
    helper.recordErrorLog(ERROR_TYPE_FLEETVIEW, "fleetview", "FV_".concat(String.valueOf(type)), data_str, getStringFromException(e));
}
 
Example 17
Source File: CommonUtils.java    From search-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
public static String toString(Object[] args) {
    if (args == null || args.length == 0) {
        return "[]";
    } else {
        JsonArray out = new JsonArray();
        for (int i = 0; i < args.length; i++) {
            Object value = args[i];
            if (value == null) {
                out.add("null");
            } else {
                if (value instanceof String) {
                    String text = (String) value;
                    if (text.length() > 100) {
                        out.add(text.substring(0, 97) + "...");
                    } else {
                        out.add(text);
                    }
                } else if (value instanceof Number) {
                    out.add((Number) value);
                } else if (value instanceof Date) {
                    String str = DateUtils.formatDateTime((Date) value);
                    out.add(str);
                } else if (value instanceof Boolean) {
                    out.add((Boolean) value);
                } else if (value instanceof InputStream) {
                    out.add("<InputStream>");
                } else if (value instanceof NClob) {
                    out.add("<NClob>");
                } else if (value instanceof Clob) {
                    out.add("<Clob>");
                } else if (value instanceof Blob) {
                    out.add("<Blob>");
                } else {
                    out.add('<' + value.getClass().getName() + '>');
                }
            }
        }
        return out.toString();
    }
}
 
Example 18
Source File: JsonUtil.java    From camunda-bpm-identity-keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the String value at a specific index from a given JsonArray.
 * @param jsonArray the JsonArray
 * @param i the index
 * @return the String value at the given index
 * @throws JsonException in case of errors including the case that no element exists at the specified index
 */
public static String getJsonStringAtIndex(JsonArray jsonArray, int i) throws JsonException {
	try {
		return jsonArray.get(i).getAsString();
	} catch (IndexOutOfBoundsException | ClassCastException | IllegalStateException ex) {
		throw new JsonException("Unable to get index " + i + " from JsonArray " + jsonArray.toString(), ex);
	}
}
 
Example 19
Source File: ESProductListSyncHandler.java    From elastic-rabbitmq with MIT License 4 votes vote down vote up
/**
 *  build body like below
 *  action_and_meta_data\n
    optional_source\n
    action_and_meta_data\n
    optional_source\n
 ....
 * @param hits
 * @param channelId
 * @param productId
 * @param action
 * @return
 */
private String buildBulkUpdateBody(List<Hits> hits, Long channelId, Long productId, OperateAction action) {
    JsonArray updateActionArray = new JsonArray();
    JsonArray updateDocArray = new JsonArray();

    for (Hits hit : hits) {
        JsonObject source = hit.getSource();
        Long skuId = source.get("id").getAsLong();
        JsonArray channels = source.get(CHANNELIDS_KEY) == null ? null : source.get(CHANNELIDS_KEY).getAsJsonArray();
        JsonArray result = doUpdateChannelIds(channelId, channels, action);
        if (result == null) {
            //nothing update
            continue;
        } else {
            // searchcommand meta data
            JsonObject innerMeta = new JsonObject();
            innerMeta.addProperty("_id", skuId.toString());
            innerMeta.addProperty("parent", productId.toString());
            JsonObject outerObj = new JsonObject();
            outerObj.add("update", innerMeta);
            updateActionArray.add(outerObj);
            // optional source
            JsonObject innerSource = new JsonObject();
            innerSource.add(CHANNELIDS_KEY, result);

            boolean doc_as_upsert = false;
            if (source.get("needInsert") != null && source.get("needInsert").getAsBoolean()) {
                innerSource.addProperty("id", skuId);
                innerSource.addProperty("version", 0);
                innerSource.addProperty("parentId", productId);
                doc_as_upsert = true;
            }
            JsonObject outerSource = new JsonObject();
            outerSource.add("doc", innerSource);
            if (doc_as_upsert) {
                outerSource.addProperty("doc_as_upsert", true);
            }
            updateDocArray.add(outerSource);
        }
    }

    if (updateActionArray.size() != updateDocArray.size()) {
        //illegal state happen, mess message
        throw new IllegalStateException("bulk illegal state on body:" + updateDocArray.toString());
    }

    if (updateActionArray.size() == 0) {
        // nothing update
        return null;
    }

    StringBuilder body = new StringBuilder(50);
    for (int i = 0; i < updateActionArray.size(); ++i) {
        body.append(updateActionArray.get(i).toString());
        body.append("\r\n");
        body.append(updateDocArray.get(i).toString());
        body.append("\r\n");
    }

    return body.toString();
}
 
Example 20
Source File: CtpTxnSession.java    From java-trader with Apache License 2.0 4 votes vote down vote up
public String syncQryOrders() throws Exception
{
    CThostFtdcQryOrderField f = new CThostFtdcQryOrderField();
    CThostFtdcOrderField[] orderFields = traderApi.SyncAllReqQryOrder(f);
    JsonArray result = new JsonArray();
    for(CThostFtdcOrderField orderField:orderFields) {
        JsonObject json = new JsonObject();
        json.addProperty("ref", orderField.OrderRef);
        json.addProperty("direction", CtpUtil.ctp2orderDirection(orderField.Direction).name());
        json.addProperty("limitPrice", orderField.LimitPrice);
        json.addProperty("priceType", CtpUtil.ctp2orderPriceType(orderField.OrderPriceType).name());
        if (orderField.CombOffsetFlag.length()>0) {
            json.addProperty("offsetFlag", CtpUtil.ctp2orderOffsetFlag(orderField.CombOffsetFlag.charAt(0)).name());
        }
        json.addProperty("volumeCondition", CtpUtil.ctp2orderVolumeCondition(orderField.VolumeCondition).name());

        JsonObject stateJson = new JsonObject();
        stateJson.addProperty("submitState", CtpUtil.ctp2orderSubmitState(orderField.OrderSubmitStatus).name());
        stateJson.addProperty("state", CtpUtil.ctp2orderState(orderField.OrderStatus, orderField.OrderSubmitStatus).name());
        stateJson.addProperty("timestamp", System.currentTimeMillis());
        stateJson.addProperty("stateMessage", orderField.StatusMsg);
        json.add("lastState", stateJson);
        JsonArray stateTuples = new JsonArray();
        stateTuples.add(stateJson);
        json.add("stateTuples", stateTuples);
        //计算时间
        String time = orderField.InsertTime;
        if ( !CtpUtil.isEmptyTime(orderField.UpdateTime) ) {
            time = orderField.UpdateTime;
        }
        if ( !CtpUtil.isEmptyTime(orderField.SuspendTime) ) {
            time = orderField.SuspendTime;
        }
        if ( !StringUtil.isEmpty(orderField.CancelTime)) {
            time = orderField.CancelTime;
        }

        JsonObject attrs = new JsonObject();
        attrs.addProperty(Order.ODRATR_CTP_SYS_ID, orderField.OrderSysID);
        attrs.addProperty(Order.ODRATR_CTP_STATUS, orderField.OrderStatus);
        attrs.addProperty(Order.ODRATR_CTP_FRONT_ID, orderField.FrontID);
        attrs.addProperty(Order.ODRATR_CTP_SESSION_ID, orderField.SessionID);
        json.add("attrs", attrs);
    }

    return result.toString();
}