Example usage for org.json.simple JSONObject toJSONString

List of usage examples for org.json.simple JSONObject toJSONString

Introduction

In this page you can find the example usage for org.json.simple JSONObject toJSONString.

Prototype

public String toJSONString() 

Source Link

Usage

From source file:it.polimi.geinterface.network.MessageUtils.java

/**
 * Method that build a {@link MessageType#SYNC_REQ}, passed a {@link String} representing the topic reply where
 * other entities have to send the corresponding {@link MessageType#SYNC_RESP} message
 *//*from  w  w w.j av a  2s  .  c o  m*/
public static String buildSyncReqMessage(String senderID, String topicReply, ArrayList<Entity> beacons,
        Group group, DistanceRange distance, String logId) {
    JSONObject mesg = new JSONObject();
    JSONObject syncReqMsg = new JSONObject();
    syncReqMsg.put(JsonStrings.SENDER, senderID);
    syncReqMsg.put(JsonStrings.MSG_TYPE, MessageType.SYNC_REQ.name());
    syncReqMsg.put(JsonStrings.TOPIC_REPLY, topicReply);
    syncReqMsg.put(JsonStrings.BEACONS, ((JSONArray) buildBeaconsJsonArray(beacons)));

    JSONObject jsonGroup = new JSONObject();
    jsonGroup.put(JsonStrings.FILTER, (group.getFilter() != null) ? group.getFilter().toString() : "");
    jsonGroup.put(JsonStrings.ENTITY_ID, group.getEntity_id());
    jsonGroup.put(JsonStrings.ENTITY_TYPE, group.getType().name());
    jsonGroup.put(JsonStrings.GROUP_DESCRIPTOR, group.toString());

    syncReqMsg.put(JsonStrings.GROUP, jsonGroup);

    syncReqMsg.put(JsonStrings.DISTANCE_RANGE, distance.name());
    syncReqMsg.put(JsonStrings.LOG_ID, logId);
    mesg.put(JsonStrings.MESSAGE, syncReqMsg);

    return mesg.toJSONString();
}

From source file:app.WebSocketServerHandler.java

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        channels.remove(ctx.channel());/*from   w w w  . j  a  v a 2  s. com*/
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;
    }
    if (frame instanceof PingWebSocketFrame) {
        ctx.write(new PongWebSocketFrame(frame.content().retain()));
        return;
    }
    if (frame instanceof TextWebSocketFrame) {
        JSONObject msg = (JSONObject) JSONValue.parse(((TextWebSocketFrame) frame).text());

        if (msg == null) {
            System.out.println("Unknown message type");
            return;
        }

        switch (msg.get("type").toString()) {
        case "broadcast":
            final TextWebSocketFrame outbound = new TextWebSocketFrame(msg.toJSONString());
            channels.forEach(gc -> gc.writeAndFlush(outbound.duplicate().retain()));
            msg.replace("type", "broadcastResult");
            ctx.writeAndFlush(new TextWebSocketFrame(msg.toJSONString()));
            break;
        case "echo":
            ctx.writeAndFlush(new TextWebSocketFrame(msg.toJSONString()));
            break;
        default:
            System.out.println("Unknown message type");
        }

        return;
    }
}

From source file:com.otisbean.keyring.Item.java

@SuppressWarnings("unchecked")
public void lock() throws GeneralSecurityException, KeyringException {
    if (locked) {
        throw new KeyringException("Locking an already locked record is wrong");
    }//from  www .  ja va  2 s .  co  m
    JSONObject crypted = new JSONObject();
    crypted.put("username", username);
    crypted.put("pass", pass);
    crypted.put("url", url);
    crypted.put("notes", notes);
    encryptedData = ring.encrypt(crypted.toJSONString(), Ring.ITEM_SALT_LENGTH);
    username = pass = url = notes = "";
    locked = true;
}

From source file:at.uni_salzburg.cs.ckgroup.cscpp.mapper.PolygonZone.java

@SuppressWarnings("unchecked")
@Override//www. j a v  a 2s  . com
public String toJSONString() {

    JSONObject o = new JSONObject();
    JSONArray a = new JSONArray();
    for (TwoTuple t : vertices) {
        a.add(t);
    }
    o.put("type", "polygon");
    o.put("vertices", a);
    o.put("depot", new TwoTuple(getDepotPosition().getLatitude(), getDepotPosition().getLongitude()));
    return o.toJSONString();
}

From source file:com.modeln.batam.connector.wrapper.Commit.java

@SuppressWarnings("unchecked")
public String toJSONString() {
    JSONObject obj = new JSONObject();
    obj.put("build_id", buildId);
    obj.put("build_name", buildName);
    obj.put("commit_id", commitId);
    obj.put("url", url);
    obj.put("author", author);
    //To json return date_committed as time in ms
    obj.put("date_committed", dateCommitted == null ? null : String.valueOf(dateCommitted.getTime()));

    return obj.toJSONString();
}

From source file:eg.nileu.cis.nilestore.monitor.server.NsMonitorServer.java

/**
 * Dump whole viewto json.//from   www.j  a v  a  2  s .  co m
 * 
 * @return the string
 */
@SuppressWarnings("unchecked")
private synchronized String dumpWholeViewtoJSON() {

    List<String> serversList = new ArrayList<String>();
    List<String> filesList = new ArrayList<String>();
    List<Map<String, Object>> links = new ArrayList<Map<String, Object>>();
    Map<String, String> sslinks = new HashMap<String, String>();

    for (NilestoreAddress peer : view.keySet()) {

        StorageStatusView peerstatus = view.get(peer);
        Map<String, SIStatusItem> statusperSI = peerstatus.getStatusPerSI();
        if (statusperSI.size() == 0)
            continue;

        String peerkey = peer.getNickname();

        String peerurl = String.format("http://%s:%s", peer.getPeerAddress().getIp(), peer.getWebPort());
        sslinks.put(peerkey, peerurl);

        serversList.add(peerkey);
        int serverIndex = serversList.indexOf(peerkey);
        int siIndex = 0;

        for (String si : statusperSI.keySet()) {

            if (!filesList.contains(si))
                filesList.add(si);
            siIndex = filesList.indexOf(si);

            SIStatusItem item = statusperSI.get(si);
            Map<String, Object> elem = new HashMap<String, Object>();

            elem.put("ss", serverIndex);
            elem.put("si", siIndex);
            Object val = item.getCount();

            if (val.equals(deadval)) {
                val = "dead";
            }

            elem.put("val", val);

            if (!links.contains(elem))
                links.add(elem);
        }
    }

    JSONObject obj = new JSONObject();
    obj.put("ss", serversList);
    obj.put("si", filesList);
    obj.put("links", links);
    obj.put("sslinks", sslinks);

    return obj.toJSONString();
}

From source file:de.sjka.logstash.osgi.internal.LogstashSender.java

private void process(LogEntry logEntry) {
    if (logEntry.getLevel() <= getLogLevelConfig()) {
        if (!"true".equals(getConfig(LogstashConfig.ENABLED))) {
            return;
        }//from ww  w .j av a2  s. c  om
        ;
        for (ILogstashFilter logstashFilter : logstashFilters) {
            if (!logstashFilter.apply(logEntry)) {
                return;
            }
        }
        String request = getConfig(LogstashConfig.URL);
        if (!request.endsWith("/")) {
            request += "/";
        }
        HttpURLConnection conn = null;
        try {
            JSONObject values = serializeLogEntry(logEntry);

            String payload = values.toJSONString();
            byte[] postData = payload.getBytes(StandardCharsets.UTF_8);

            String username = getConfig(LogstashConfig.USERNAME);
            String password = getConfig(LogstashConfig.PASSWORD);

            String authString = username + ":" + password;
            byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
            String authStringEnc = new String(authEncBytes);

            URL url = new URL(request);

            conn = (HttpURLConnection) url.openConnection();
            if (request.startsWith("https") && "true".equals(getConfig(LogstashConfig.SSL_NO_CHECK))) {
                if (sslSocketFactory != null) {
                    ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
                    ((HttpsURLConnection) conn).setHostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    });
                }
            }
            conn.setDoOutput(true);
            conn.setInstanceFollowRedirects(false);
            conn.setRequestMethod("PUT");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("charset", "utf-8");
            conn.setReadTimeout(30 * SECONDS);
            conn.setConnectTimeout(30 * SECONDS);
            if (username != null && !"".equals(username)) {
                conn.setRequestProperty("Authorization", "Basic " + authStringEnc);
            }
            conn.setUseCaches(false);
            try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
                wr.write(postData);
                wr.flush();
                wr.close();
            }
            if (conn.getResponseCode() != 200) {
                throw new IOException(
                        "Got response " + conn.getResponseCode() + " - " + conn.getResponseMessage());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

}

From source file:eumetsat.pn.elasticsearch.ElasticsearchFeeder.java

protected void indexDirContent(Path aSrcDir) {
    log.info("Indexing dir content {}", aSrcDir);

    JSONParser parser = new JSONParser();

    YamlNode endpointConfig = this.config.get("endpoint");

    log.info("Endpoint configuration: {}", endpointConfig);

    Settings settings = ImmutableSettings.settingsBuilder()
            .put("cluster.name", endpointConfig.get("cluster.name").asTextValue()).build();

    try (TransportClient client = new TransportClient(settings);) {
        client.addTransportAddress(new InetSocketTransportAddress(endpointConfig.get("host").asTextValue(),
                endpointConfig.get("port").asIntValue()));
        int cpt = 0;
        Collection<File> inputFiles = FileUtils.listFiles(aSrcDir.toFile(), new String[] { "json" }, false);
        log.info("Indexing {} files...", inputFiles.size());

        for (File file : inputFiles) {

            try {
                String jsonStr = FileUtils.readFileToString(file);
                JSONObject jsObj = (JSONObject) parser.parse(jsonStr);

                String index = endpointConfig.get("index").asTextValue();
                String type = endpointConfig.get("type").asTextValue();

                String id = (String) jsObj.get(FILE_IDENTIFIER_PROPERTY);
                log.debug("Adding {} (type: {}) to {}", id, type, index);
                IndexResponse response = client.prepareIndex(index, type, id).setSource(jsObj.toJSONString())
                        .execute().actionGet();

                cpt++;//from   w  w  w .j  a va  2  s  .  co m

                if (response.isCreated()) {
                    log.trace("Response: {} | version: {}", response.getId(), response.getVersion());
                } else {
                    log.warn("NOT created! ResponseResponse: {}", response.getId());
                }
            } catch (IOException | ParseException e) {
                log.error("Error with json file ", file, e);
            }
        }

        log.info("Indexed {} of {} files.", cpt, inputFiles.size());
    } catch (RuntimeException e) {
        log.error("Error indexing json files.", e);
    }
}

From source file:de.hstsoft.sdeep.NoteManager.java

@SuppressWarnings("unchecked")
private void saveNotes() {
    JSONObject envelope = new JSONObject();
    envelope.put("version", VERSION);

    JSONArray jsonArray = new JSONArray();
    for (Note n : notes) {
        jsonArray.add(n.toJson());//from   www.  j  a  v  a 2s. co m
    }

    envelope.put("notes", jsonArray);

    try {
        File file = new File(directory + FILENAME);
        FileWriter fileWriter = new FileWriter(file);
        fileWriter.append(envelope.toJSONString());
        fileWriter.flush();
        fileWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.paladin.action.SearchAction.java

/**
 * Search blog ,code and motto/*  w  ww  .ja  v  a2 s.c  om*/
 */
public void doSearch(final RequestContext _reqCtxt)
        throws IOException, ParseException, InvalidTokenOffsetsException {
    HttpServletRequest request = _reqCtxt.request();
    String key = Tools.compressBlank(_reqCtxt.param("q"));

    if (!Strings.isNullOrEmpty(key)) {
        key = Tools.ISO885912UTF8(key).trim();
        log.info("Let's search: key = " + key);
        //request.setAttribute("q", key);
        JSONObject json_obj = new JSONObject();

        _search(json_obj, request, key, "blog");
        //_search(json_obj, request, t_key, "code");
        //_search(json_obj, request, t_key, "motto");

        //  JSON   ?(python)
        _reqCtxt.response().getWriter().write(json_obj.toJSONString());
    }
}