Example usage for org.json.simple JSONObject put

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

Introduction

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

Prototype

V put(K key, V value);

Source Link

Document

Associates the specified value with the specified key in this map (optional operation).

Usage

From source file:com.intbit.dao.ScheduleSocialPostDAO.java

public static JSONArray getScheduledActionstwitter(int userid) throws SQLException {
    JSONObject json_action_facebook = new JSONObject();
    JSONArray json_array_twitter = new JSONArray();
    String query = "Select * from tbl_scheduled_entity_list" + " where entity_id=?" + " and entity_type =?"
            + " and user_id = ?";

    try (Connection conn = connectionManager.getConnection();
            PreparedStatement ps = conn.prepareStatement(query)) {
        ps.setInt(1, 0);/*from w  w w  .  j a  va  2s  . c  om*/
        ps.setString(2, "twitter");
        ps.setInt(3, userid);

        try (ResultSet result_set = ps.executeQuery()) {
            while (result_set.next()) {

                JSONObject json_object = new JSONObject();
                Integer id = result_set.getInt("id");
                String schedule_title = result_set.getString("schedule_title");
                String schedule_desc = result_set.getString("schedule_desc");
                Timestamp scheduleTimestamp = result_set.getTimestamp("schedule_time");
                long scheduleTime = scheduleTimestamp.getTime();

                json_object.put("id", id);
                json_object.put("schedule_title", schedule_title);
                json_object.put("schedule_desc", schedule_desc);
                json_object.put("schedule_time", scheduleTime);

                json_array_twitter.add(json_object);
            }
        }
    }
    return json_array_twitter;
}

From source file:net.modsec.ms.connector.ConnRequestHandler.java

/**
 * Writes the modified modsecurity configurations to configuration file.
 * @param json contains modsecurity configurations as json object.
 *///ww w  . j  a  v  a 2  s.  c o  m
@SuppressWarnings("unchecked")
public static void onWriteMSConfig(JSONObject json) {

    log.info("onWriteMSConfig called.. : " + json.toJSONString());

    MSConfig serviceCfg = MSConfig.getInstance();
    JSONObject jsonResp = new JSONObject();
    String fileName = serviceCfg.getConfigMap().get("MSConfigFile");
    String modifiedStr = "";

    InputStream ins = null;
    FileOutputStream out = null;
    BufferedReader br = null;

    try {

        File file = new File(fileName);
        DataInputStream in;

        @SuppressWarnings("resource")
        FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
        FileLock lock = channel.lock();

        try {

            ins = new FileInputStream(file);
            in = new DataInputStream(ins);
            br = new BufferedReader(new InputStreamReader(in));

            String line = "";
            boolean check;

            while ((line = br.readLine()) != null) {

                check = true;
                //log.info("Line :" + line);
                for (ModSecConfigFields field : ModSecConfigFields.values()) {

                    if (line.startsWith(field.toString())) {
                        if (line.trim().split(" ")[0].equals(field.toString())) {
                            if (json.containsKey(field.toString())) {

                                if (((String) json.get(field.toString())).equals("")
                                        || json.get(field.toString()) == null) {

                                    log.info("---------- Log Empty value ----:"
                                            + (String) json.get(field.toString()));
                                    json.remove(field.toString());
                                    check = false;
                                    continue;

                                } else {

                                    modifiedStr += field.toString() + " " + json.remove(field.toString())
                                            + "\n";
                                    check = false;

                                }

                            }
                        }
                    }

                }

                if (check) {
                    modifiedStr += line + "\n";
                }

            }

            for (ModSecConfigFields field : ModSecConfigFields.values()) {
                if (json.containsKey(field.toString())) {

                    if (json.get(field.toString()) == null
                            || ((String) json.get(field.toString())).equals("")) {

                        log.info("---------- Log Empty value ----:" + (String) json.get(field.toString()));
                        json.remove(field.toString());
                        check = false;
                        continue;

                    } else {
                        modifiedStr += field.toString() + " " + json.remove(field.toString()) + "\n";
                    }

                }

            }

            //modified string writing to modsecurity configurations
            log.info("Writing File :" + modifiedStr);
            out = new FileOutputStream(fileName);
            out.write(modifiedStr.getBytes());

            log.info("ModSecurity Configurations configurations Written ... ");

        } finally {

            lock.release();

        }

        br.close();
        in.close();
        ins.close();
        out.close();

        //For Restarting modsecurity so that modified configuration can be applied
        JSONObject restartJson = new JSONObject();
        restartJson.put("action", "restart");

        String cmd = serviceCfg.getConfigMap().get("MSRestart");

        executeShScript(cmd, restartJson);

        jsonResp.put("action", "writeMSConfig");
        jsonResp.put("status", "0");
        jsonResp.put("message", "Configurations updated!");

    } catch (FileNotFoundException e1) {

        jsonResp.put("action", "writeMSConfig");
        jsonResp.put("status", "1");
        jsonResp.put("message", "Internal Service is down!");
        e1.printStackTrace();

    } catch (IOException | NullPointerException e) {

        jsonResp.put("action", "writeMSConfig");
        jsonResp.put("status", "0");
        jsonResp.put("message", "Unable to modify configurations. Sorry of inconvenience");
        e.printStackTrace();

    }

    log.info("Sending Json :" + jsonResp.toJSONString());
    ConnectorService.getConnectorProducer().send(jsonResp.toJSONString());
    jsonResp.clear();
}

From source file:com.iitb.cse.Utils.java

@SuppressWarnings("unchecked")
static String getServerConfiguration(String serverIP, String serverPORT, String connectionPORT) {
    JSONObject obj = new JSONObject();
    obj.put(Constants.action, "action_changeServer");
    //        hbDuration

    if (serverIP != null && !serverIP.trim().equalsIgnoreCase("")) {
        obj.put("serverip", serverIP);
    } else {//from ww w .  j  a  v  a  2 s  .  c  o  m
        obj.put("serverip", "");
    }

    if (serverPORT != null && !serverPORT.trim().equalsIgnoreCase("")) {
        obj.put("serverport", serverPORT);
    } else {
        obj.put("serverport", "");
    }

    if (connectionPORT != null && !connectionPORT.trim().equalsIgnoreCase("")) {
        obj.put("connectionport", connectionPORT);
    } else {
        obj.put("connectionport", "");
    }

    String jsonString = obj.toJSONString();
    System.out.println(jsonString);
    return jsonString;
}

From source file:anotadorderelacoes.model.UtilidadesPacotes.java

/**
 * Converte um arquivo de sada do parser PALAVRAS para o formato JSON
 * aceito pela ARS./*w  ww.java  2s .c  om*/
 *
 * @param arquivoPalavras Arquivo resultante do parser PALAVRAS
 * @param arquivoSaida Arquivo de texto convertido para o formato JSON
 */
public static void conveterPalavrasJson(File arquivoPalavras, File arquivoSaida) {

    BufferedReader br;
    BufferedWriter bw;
    String linha;
    int contadorSentencas = 1;

    JSONObject sentenca = new JSONObject();
    JSONArray tokens = new JSONArray();

    sentenca.put("id", contadorSentencas++);
    sentenca.put("texto", "");
    sentenca.put("comentarios", "");

    sentenca.put("termos", new JSONArray());
    sentenca.put("relacoes", new JSONArray());
    sentenca.put("anotadores", new JSONArray());

    sentenca.put("anotada", false);
    sentenca.put("ignorada", false);

    try {

        //br = new BufferedReader( new FileReader( arquivoPalavras ) );
        br = new BufferedReader(new InputStreamReader(new FileInputStream(arquivoPalavras), "UTF-8"));
        //bw = new BufferedWriter( new FileWriter( arquivoSaida ) );
        bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(arquivoSaida), "UTF-8"));

        bw.write("# Arquivo \"" + arquivoPalavras.getName() + "\" convertido para o formato JSON\n");
        bw.write("===\n");

        while ((linha = br.readLine()) != null) {

            //System.out.println( "DEBUG: " + linha );

            // Fim de uma sentena
            if (linha.equals("</s>")) {

                String texto = "";
                for (Object token : tokens)
                    texto += ((JSONObject) token).get("t") + " ";
                texto = texto.substring(0, texto.length() - 1);
                sentenca.put("texto", texto);

                sentenca.put("tokens", tokens);
                bw.write(sentenca.toString() + "\n");

                sentenca = new JSONObject();
                tokens = new JSONArray();
                sentenca.put("id", contadorSentencas++);
                sentenca.put("texto", "");
                sentenca.put("comentarios", "");
                sentenca.put("termos", new JSONArray());
                sentenca.put("relacoes", new JSONArray());
                sentenca.put("anotadores", new JSONArray());
                sentenca.put("anotada", false);
                sentenca.put("ignorada", false);

            }

            // Lendo uma sentena
            // Transformaes adaptadas do script "criar-pacotes.pl"
            else {

                linha = linha.replace("", "<<");
                linha = linha.replace("", ">>");
                linha = linha.replace("", "o");

                Matcher matcher;

                // Apenas para tratar as sentenas que tm "secretaria" (e.g. 96524)
                if (linha.matches("(.*\\t.*)\\t.*")) {
                    matcher = Pattern.compile("(.*\\t.*)\\t.*").matcher(linha);
                    matcher.find();
                    linha = matcher.group(1);
                }

                //if ( linha.matches( "<s id=\"(\\d+)\">" ) ) {
                if (patterns[0].matcher(linha).find()) {
                    matcher = Pattern.compile("<s id=\"(\\d+)\">").matcher(linha);
                    matcher.find();
                    sentenca.put("id", matcher.group(1));
                } else if (linha.startsWith("$,")) {
                    tokens.add(novoToken(",", ",", null, null));
                }
                //else if ( linha.matches( "^\\$(.)$" ) ) {
                else if (patterns[1].matcher(linha).find()) {
                    matcher = Pattern.compile("^\\$(.)$").matcher(linha);
                    matcher.find();
                    tokens.add(novoToken(matcher.group(1), matcher.group(1), null, null));
                }
                //                    else if ( linha.matches( "^\\$(..)" ) ) {
                else if (patterns[2].matcher(linha).find()) {
                    matcher = Pattern.compile("^\\$(..)").matcher(linha);
                    matcher.find();
                    tokens.add(novoToken(matcher.group(1), matcher.group(1), null, null));
                }
                //                    else if ( linha.matches( "^\\$(%)" ) ) {
                else if (patterns[3].matcher(linha).find()) {
                    matcher = Pattern.compile("^\\$(%)").matcher(linha);
                    matcher.find();
                    tokens.add(novoToken(matcher.group(1), matcher.group(1), null, null));
                }
                // Linha normal
                //                    else if ( linha.matches( "^(.*)\\t ?\\[([^\\]]+)\\] ([^@]+) (@.*)$" ) ) {
                else if (patterns[4].matcher(linha).find()) {
                    matcher = Pattern.compile("^(.*)\\t ?\\[([^\\]]+)\\] ([^@]+) (@.*)$").matcher(linha);
                    matcher.find();
                    tokens.add(
                            novoToken(matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(4)));
                }
                // Alguns tokens no tm a tag sinttica
                //                    else if ( linha.matches( "^(.*)\\t ?\\[([^\\]]+)\\] ([^@]+)$" ) ) {
                else if (patterns[5].matcher(linha).find()) {
                    matcher = Pattern.compile("^(.*)\\t ?\\[([^\\]]+)\\] ([^@]+)$").matcher(linha);
                    matcher.find();
                    tokens.add(novoToken(matcher.group(1), matcher.group(2), matcher.group(3), null));
                }
                // E alguns no tm o lema
                //                    else if ( linha.matches( "^(.*)\\t ?([^@]+) (@.*)$" ) ) {
                else if (patterns[6].matcher(linha).find()) {
                    matcher = Pattern.compile("^(.*)\\t ?([^@]+) (@.*)$").matcher(linha);
                    matcher.find();
                    tokens.add(novoToken(matcher.group(1), null, matcher.group(2), matcher.group(3)));
                }
                // s vezes tem alguns tokens que vm sem nada, so tratados como pontuao
                //                    else if ( linha.matches( "^(.*)$" ) ) {
                else if (patterns[7].matcher(linha).find()) {
                    matcher = Pattern.compile("^(.*)$").matcher(linha);
                    matcher.find();
                    tokens.add(novoToken(matcher.group(1), matcher.group(2), null, null));
                } else {
                    System.out.println("PROBLEMA!");
                    System.out.println(linha);
                }

            }
        }

        String texto = "";
        for (Object token : tokens)
            texto += ((JSONObject) token).get("t") + " ";
        texto = texto.substring(0, texto.length() - 1);
        sentenca.put("texto", texto);

        sentenca.put("tokens", tokens);
        bw.write(sentenca.toString() + "\n");

        bw.close();
        br.close();

        Logger.getLogger("ARS logger").log(Level.INFO, "Arquivo JSON \"{0}\" gravado.",
                arquivoSaida.getAbsolutePath());

    } catch (FileNotFoundException ex) {
        Logger.getLogger("ARS logger").log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger("ARS logger").log(Level.SEVERE, null, ex);
    }

}

From source file:hoot.services.controllers.job.JobResource.java

private static JSONObject processJob(String jobId, JSONObject command) throws NativeInterfaceException {
    logger.debug("processing Job: {}", jobId);
    command.put("jobId", jobId);

    String resourceName = command.get("caller").toString();
    JobFieldsValidator validator = new JobFieldsValidator(resourceName);

    Map<String, String> paramsMap = paramsToMap(command);

    List<String> missingList = new ArrayList<>();
    if (!validator.validateRequiredExists(paramsMap, missingList)) {
        logger.error("Missing following required field(s): {}", missingList);
    }/*from  w  w w .ja va 2 s  .c  o m*/

    logger.debug("calling native request Job: {}", jobId);

    return jobExecMan.exec(command);
}

From source file:co.aikar.timings.TimingsExport.java

private static JSONObject mapAsJSON(ConfigurationSection config, String parentKey) {

    JSONObject object = new JSONObject();
    for (String key : config.getKeys(false)) {
        String fullKey = (parentKey != null ? parentKey + "." + key : key);
        if (fullKey.equals("database") || fullKey.equals("settings.bungeecord-addresses")
                || TimingsManager.hiddenConfigs.contains(fullKey)) {
            continue;
        }/*  w  w  w  . j  a v a  2s  . c o m*/
        final Object val = config.get(key);

        object.put(key, valAsJSON(val, fullKey));
    }
    return object;
}

From source file:com.iitb.cse.Utils.java

/**
 * genetated and returns the String in Json format. String contains
 * information that the experiment has been stopped by experimenter This
 * string is later sent to filtered devices.
 *///from ww w. j  a v a2  s.c om
@SuppressWarnings("unchecked")
static String getLogFilesJson(int expID) {
    JSONObject obj = new JSONObject();
    //{action:getLogFile}
    obj.put(Constants.action, Constants.getLogFiles);
    obj.put(Constants.expID, Integer.toString(expID));

    String jsonString = obj.toJSONString();
    System.out.println(jsonString);
    return jsonString;
}

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

public static String addLogField(String message, String logId) {
    JSONParser parser = new JSONParser();
    try {//from   w  ww  .j  av  a  2  s  .c om
        JSONObject msg = (JSONObject) parser.parse(message);
        JSONObject m = (JSONObject) msg.get(JsonStrings.MESSAGE);
        MessageType msgType = MessageType.valueOf((String) m.get(JsonStrings.MSG_TYPE));
        if (msgType.equals(MessageType.CHECK_OUT)) {
            m.put(JsonStrings.LOG_ID, logId);
            JSONObject newJsonMsg = new JSONObject();
            newJsonMsg.put(JsonStrings.MESSAGE, m);
            return newJsonMsg.toJSONString();
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return message;
}

From source file:hoot.services.controllers.job.JobResource.java

private static void setJobInfo(JSONObject jobInfo, JSONObject child, JSONArray children, String stat,
        String detail) {/*from w  ww.j  av  a  2s .  c  o  m*/
    for (Object aChildren : children) {
        JSONObject c = (JSONObject) aChildren;
        if (c.get("id").toString().equals(child.get("id").toString())) {
            c.put("status", stat);
            c.put("detail", detail);
            return;
        }
    }

    child.put("status", stat);
    child.put("detail", detail);
    children.add(child);
    jobInfo.put("children", children);
}

From source file:com.justgiving.raven.kissmetrics.utils.KissmetricsRowParser.java

/***
 * Used to parse, escape and enrich Kissmetircs Json records
 * //  w w  w . j  a v  a 2s .  c  o  m
 * @param rawJsonRow
 * @param fileNameInputToMapper
 * @return
 */
public static KeyRowWrapper parseJsonRowToValidJson(Text rawJsonRow, String fileNameInputToMapper,
        String filePath) {

    String jsonString = "";
    boolean wasOctalParsingNeeded = false;

    try {
        System.setProperty("file.encoding", "UTF-8");
        s = rawJsonRow.toString();
        Charset charSet = Charset.forName("UTF-8");
        byte[] encoded = s.getBytes(charSet);
        decodedStrRaw = new String(encoded, charSet);

        // Test new Apache Lang3
        // decodedStr = StringEscapeUtils.unescapeJava(decodedStr);

        //Replace any remaining Octal encoded Characters
        decodedStrParsed = replaceOctalUft8Char(decodedStrRaw);
        if (decodedStrParsed.compareTo(decodedStrRaw) == 0) {
            wasOctalParsingNeeded = false;
        } else {
            wasOctalParsingNeeded = true;
        }

        if (decodedStrParsed != null && decodedStrParsed != "") {
            JSONObject jsonObject = (JSONObject) jsonParser.parse(decodedStrParsed);

            // get email and user_id
            if (jsonObject.get("_p2") != null) {
                p2 = jsonObject.get("_p2").toString().toLowerCase();
                if (p2.contains("@")) {
                    jsonObject.put("user_email", p2);
                    jsonObject.put("user_email_back", p2);
                } else if (p2 != null && p2.length() > 0) {
                    jsonObject.put("user_km_id", p2);
                }
            }
            // get email and user_id
            if (jsonObject.get("_p") != null) {
                p = jsonObject.get("_p").toString().toLowerCase();
                if (p.contains("@")) {
                    jsonObject.put("user_email", p);
                    jsonObject.put("user_email_back", p);
                } else if (p != null && p.length() > 0) {
                    jsonObject.put("user_km_id", p);
                }
            }

            // Add Event
            if (jsonObject.get("_n") != null) {
                event = jsonObject.get("_n").toString();
                if (event != null) {
                    jsonObject.put("event", event);
                }
            }

            // add unix timestamp and datetime
            long currentDateTime = System.currentTimeMillis();
            Date currentDate = new Date(currentDateTime);
            if (jsonObject.get("_t") == null) {
                return (new KeyRowWrapper(jsonString, null, TRACKING_COUNTER.INVALID_JSON_ROW,
                        TRACKING_COUNTER.INVALID_DATE));
            }
            long kmTimeDateMilliSeconds;
            long kmTimeDateMilliSecondsMobile;
            try {
                tTimestampValue = (String) jsonObject.get("_t").toString();

                //See if new record with server timestamp
                if (jsonObject.get("_server_timestamp") != null) {
                    serverTimestampValue = (String) jsonObject.get("_server_timestamp").toString();
                } else {
                    serverTimestampValue = "0";
                }

                //Deal with mobile timedate cases
                if (jsonObject.get("_c") != null) {
                    if (serverTimestampValue.equals("0")) {
                        timestampValueOutput = tTimestampValue;
                        kmTimeDateMilliSecondsMobile = 0;
                    } else {
                        timestampValueOutput = serverTimestampValue;
                        mobileTimestampValueOutput = tTimestampValue;
                        jsonObject.put("km_timestamp_mobile", mobileTimestampValueOutput);
                        kmTimeDateMilliSecondsMobile = Long.parseLong(mobileTimestampValueOutput) * 1000;
                    }
                } else {//Ignore server time
                        //TODO Need a way to resolve mobile identify events
                    serverTimestampValue = "0";
                    timestampValueOutput = tTimestampValue;
                    kmTimeDateMilliSecondsMobile = 0;
                }

                jsonObject.put("km_timestamp", timestampValueOutput);
                kmTimeDateMilliSeconds = Long.parseLong(timestampValueOutput) * 1000;
            } catch (Exception e) {
                return (new KeyRowWrapper(jsonString, timestampValueOutput, TRACKING_COUNTER.INVALID_JSON_ROW,
                        TRACKING_COUNTER.INVALID_DATE));
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(kmTimeDateMilliSeconds);
            String event_timedate = dateFormatter.format(calendar.getTime());
            jsonObject.put("event_timedate", event_timedate);

            if (kmTimeDateMilliSecondsMobile > 0) {
                calendar.setTimeInMillis(kmTimeDateMilliSecondsMobile);
                String event_timedate_mobile = dateFormatter.format(calendar.getTime());
                jsonObject.put("event_timedate_mobile", event_timedate_mobile);
            }

            // add Map Reduce json_filename
            jsonObject.put("filename", fileNameInputToMapper);
            jsonString = jsonObject.toString();

            //Add bucket path
            jsonObject.put("bucket", filePath);
            jsonString = jsonObject.toString();

            // TODO add the time the record was processed by Mapper:
            //jsonObject.put("capturedDate", capturedDate);
            //jsonString = jsonObject.toString();

            return (new KeyRowWrapper(jsonString, timestampValueOutput, TRACKING_COUNTER.VALID_JSON_ROW,
                    wasOctalParsingNeeded ? null : TRACKING_COUNTER.OCTAL_PARSING_NEEDED));

        }

    } catch (Exception e) {
        // System.err.println(e.getMessage());
        // e.printStackTrace();
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        logger.error(errors.toString());

        logger.error("log - file " + fileNameInputToMapper);
        System.out.println("file " + fileNameInputToMapper);

        logger.error("log - row content: " + rawJsonRow.toString().replace("\t", ""));
        System.err.println("row content: " + rawJsonRow.toString().replace("\t", ""));

        System.err.println("Error skipping row");
        logger.error("Log - Error skipping row");
    }
    return null;
}