Example usage for org.json.simple JSONValue toJSONString

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

Introduction

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

Prototype

public static String toJSONString(Object value) 

Source Link

Usage

From source file:be.appfoundry.custom.google.android.gcm.server.Sender.java

private String makeGcmHttpRequest(Map<Object, Object> jsonRequest) throws InvalidRequestException {
    String requestBody = JSONValue.toJSONString(jsonRequest);
    logger.finest("JSON request: " + requestBody);
    HttpURLConnection conn;//from w  w w  .jav a2s.  c o m
    int status;
    try {
        conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody);
        status = conn.getResponseCode();
    } catch (IOException e) {
        logger.log(Level.FINE, "IOException posting to GCM", e);
        return null;
    }
    String responseBody;
    if (status != 200) {
        try {
            responseBody = getAndClose(conn.getErrorStream());
            logger.finest("JSON error response: " + responseBody);
        } catch (IOException e) {
            // ignore the exception since it will thrown an InvalidRequestException
            // anyways
            responseBody = "N/A";
            logger.log(Level.FINE, "Exception reading response: ", e);
        }
        throw new InvalidRequestException(status, responseBody);
    }
    try {
        responseBody = getAndClose(conn.getInputStream());
    } catch (IOException e) {
        logger.log(Level.WARNING, "IOException reading response", e);
        return null;
    }
    logger.finest("JSON response: " + responseBody);
    return responseBody;
}

From source file:au.org.paperminer.main.UserFilter.java

/**
 * Returns requesting user's stored query data as JSON array of associative arrays using DB table columns as keys.
 * @param req/*from  w w  w .jav a 2  s.  c om*/
 * @param resp
 */
private void getQueryData(HttpServletRequest req, HttpServletResponse resp) {
    UserHelper helper = getUserHelper(req);
    if (helper == null) {
        req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e104");
    } else {
        try {
            m_logger.debug("Fetching queries for "
                    + CookieHelper.getCookieValue(req, PaperMinerConstants.PMC_USER_ID));
            ArrayList<HashMap<String, String>> list = helper.getSavedQueries();
            m_logger.debug("Fetchied " + list.size());
            m_logger.debug("stored query count = " + list.size());
            String jsonStr = JSONValue.toJSONString(list);
            m_logger.debug("query string = " + jsonStr);
            resp.setContentType("text/json");
            PrintWriter pm = resp.getWriter();
            pm.write(jsonStr);
            pm.close();
        } catch (IOException ex) {
            req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e114");
        } catch (PaperMinerException ex) {
            req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e114");
        }
    }
}

From source file:bbdn.lti2.LTI2Servlet.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void handleResultRequest(HttpServletRequest request, HttpServletResponse response, String sourcedid)
        throws java.io.IOException {
    IMSJSONRequest jsonRequest = null;/*from w w  w.j a  v  a2 s .c  o m*/
    String retval = null;
    if ("GET".equals(request.getMethod())) {
        String grade = (String) PERSIST.get("grade");
        String comment = (String) PERSIST.get("comment");

        Map jsonResponse = new TreeMap();
        Map resultScore = new TreeMap();

        jsonResponse.put(LTI2Constants.CONTEXT, StandardServices.RESULT_CONTEXT);
        jsonResponse.put(LTI2Constants.TYPE, StandardServices.RESULT_TYPE);
        resultScore.put(LTI2Constants.TYPE, LTI2Constants.GRADE_TYPE_DECIMAL);
        jsonResponse.put(LTI2Constants.COMMENT, grade);
        resultScore.put(LTI2Constants.VALUE, comment);
        jsonResponse.put(LTI2Constants.RESULTSCORE, resultScore);
        response.setContentType(StandardServices.RESULT_FORMAT);
        response.setStatus(HttpServletResponse.SC_OK);
        String jsonText = JSONValue.toJSONString(jsonResponse);
        M_log.debug(jsonText);
        PrintWriter out = response.getWriter();
        out.println(jsonText);
        return;
    } else if ("PUT".equals(request.getMethod())) {
        retval = "Error parsing input data";
        try {
            jsonRequest = new IMSJSONRequest(request);
            // System.out.println(jsonRequest.getPostBody());
            JSONObject requestData = (JSONObject) JSONValue.parse(jsonRequest.getPostBody());
            String comment = (String) requestData.get(LTI2Constants.COMMENT);
            JSONObject resultScore = (JSONObject) requestData.get(LTI2Constants.RESULTSCORE);
            String sGrade = (String) resultScore.get(LTI2Constants.VALUE);
            Double dGrade = new Double(sGrade);

            PERSIST.put("comment", comment);
            PERSIST.put("grade", dGrade + "");
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        } catch (Exception e) {
            retval = "Error: " + e.getMessage();
        }
    } else {
        retval = "Unsupported operation:" + request.getMethod();
    }

    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    doErrorJSON(request, response, jsonRequest, (String) retval, null);
}

From source file:com.bigdata.dastor.thrift.server.DastorThriftServer.java

public String get_string_property(String propertyName) {
    if (propertyName.equals("cluster name")) {
        return DatabaseDescriptor.getClusterName();
    } else if (propertyName.equals("config file")) {
        String filename = DatabaseDescriptor.getConfigFileName();
        try {/*from  ww  w . j  a va  2 s .  com*/
            StringBuilder fileData = new StringBuilder(8192);
            BufferedInputStream stream = new BufferedInputStream(new FileInputStream(filename));
            byte[] buf = new byte[1024];
            int numRead;
            while ((numRead = stream.read(buf)) != -1) {
                String str = new String(buf, 0, numRead);
                fileData.append(str);
            }
            stream.close();
            return fileData.toString();
        } catch (IOException e) {
            return "file not found!";
        }
    } else if (propertyName.equals(TOKEN_MAP)) {
        return JSONValue.toJSONString(storageService.getStringEndpointMap());
    } else if (propertyName.equals("version")) {
        return Constants.VERSION;
    } else {
        return "?";
    }
}

From source file:com.mobicage.rogerthat.registration.ContentBrandingRegistrationActivity.java

private String getMobileInfo() {
    T.REGISTRATION();
    MobileInfo info = SystemPlugin.gatherMobileInfo(mService);
    String json = JSONValue.toJSONString(info.toJSONMap());
    return json;
}

From source file:com.server.xmpp.Sender.java

/**
 * Sends a message without retrying in case of service unavailability. See
 * {@link #send(Message, List, int)} for more info.
 *
 * @return multicast results if the message was sent successfully,
 *         {@literal null} if it failed but could be retried.
 *
 * @throws IllegalArgumentException if registrationIds is {@literal null} or
 *         empty.//  w ww  .j  av  a  2  s .c  o  m
 * @throws InvalidRequestException if GCM didn't returned a 200 status.
 * @throws IOException if there was a JSON parsing error
* @throws org.json.simple.parser.ParseException 
 */
public MulticastResult sendNoRetry(Message message, List<String> registrationIds)
        throws IOException, org.json.simple.parser.ParseException, ParseException {
    if (nonNull(registrationIds).isEmpty()) {
        throw new IllegalArgumentException("registrationIds cannot be empty");
    }
    Map<Object, Object> jsonRequest = new HashMap<Object, Object>();
    setJsonField(jsonRequest, PARAM_TIME_TO_LIVE, message.getTimeToLive());
    setJsonField(jsonRequest, PARAM_COLLAPSE_KEY, message.getCollapseKey());
    setJsonField(jsonRequest, PARAM_RESTRICTED_PACKAGE_NAME, message.getRestrictedPackageName());
    setJsonField(jsonRequest, PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle());
    setJsonField(jsonRequest, PARAM_DRY_RUN, message.isDryRun());
    jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds);
    Map<String, String> payload = message.getData();
    if (!payload.isEmpty()) {
        jsonRequest.put(JSON_PAYLOAD, payload);
    }
    String requestBody = JSONValue.toJSONString(jsonRequest);
    logger.finest("JSON request: " + requestBody);

    HttpURLConnection conn;
    int status;
    try {

        conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody);
        status = conn.getResponseCode();

        logger.info("SendNoRetry,Response code:" + status);

    } catch (IOException e) {
        logger.log(Level.FINE, "IOException posting to GCM", e);
        return null;
    }
    String responseBody;
    if (status != 200) {
        try {
            responseBody = getAndClose(conn.getErrorStream());
            logger.info("JSON error response: " + responseBody);
        } catch (IOException e) {
            // ignore the exception since it will thrown an InvalidRequestException
            // anyways
            responseBody = "N/A";
            logger.log(Level.FINE, "Exception reading response: ", e);
        }
        throw new InvalidRequestException(status, responseBody);
    }
    try {
        responseBody = getAndClose(conn.getInputStream());
    } catch (IOException e) {
        logger.info("IOException reading response");
        return null;
    }
    logger.finest("JSON response: " + responseBody);
    JSONParser parser = new JSONParser();
    JSONObject jsonResponse;
    try {
        jsonResponse = (JSONObject) parser.parse(responseBody);
        int success = getNumber(jsonResponse, JSON_SUCCESS).intValue();
        int failure = getNumber(jsonResponse, JSON_FAILURE).intValue();
        int canonicalIds = getNumber(jsonResponse, JSON_CANONICAL_IDS).intValue();
        long multicastId = getNumber(jsonResponse, JSON_MULTICAST_ID).longValue();
        MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds,
                multicastId);
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> results = (List<Map<String, Object>>) jsonResponse.get(JSON_RESULTS);
        if (results != null) {
            for (Map<String, Object> jsonResult : results) {
                String messageId = (String) jsonResult.get(JSON_MESSAGE_ID);
                String canonicalRegId = (String) jsonResult.get(TOKEN_CANONICAL_REG_ID);
                String error = (String) jsonResult.get(JSON_ERROR);
                Result result = new Result.Builder().messageId(messageId)
                        .canonicalRegistrationId(canonicalRegId).errorCode(error).build();
                builder.addResult(result);
            }
        }
        MulticastResult multicastResult = builder.build();
        return multicastResult;
    } catch (CustomParserException e) {
        throw newIoException(responseBody, e);
    }
}

From source file:com.turt2live.xmail.mail.Mail.java

/**
 * Creates a new mail object from a JSON string
 *
 * @param map the json string/*from   ww  w. j  a v  a2  s . c  o m*/
 *
 * @return the NewMail object or null if the json is invalid
 */
public static Mail fromJSON(Map<String, Object> map) {
    boolean debug = true; // Internal debug flag

    // Startup variables
    String to, from, sentFrom;
    boolean unread;
    long time;
    List<String> tags;
    int uuid = 0;

    // Do null and instance checks on EVERYTHING we need
    Object o = map.get("to");
    if (o == null || !(o instanceof String)) {
        if (debug) {
            System.out.println("[xMail] Err 1");
        }
        return null;
    }
    to = (String) o;

    o = map.get("from");
    if (o == null || !(o instanceof String)) {
        if (debug) {
            System.out.println("[xMail] Err 2");
        }
        return null;
    }
    from = (String) o;

    o = map.get("sent-from");
    if (o == null || !(o instanceof String)) {
        if (debug) {
            System.out.println("[xMail] Err 3");
        }
        return null;
    }
    sentFrom = (String) o;

    o = map.get("date");
    if (o == null) { // Gson casts Long->Double
        if (debug) {
            System.out.println("[xMail] Err 4");
        }
        return null;
    }
    if (o instanceof String) {
        try {
            o = Double.parseDouble((String) o);
        } catch (NumberFormatException e) {
            if (debug) {
                System.out.println("[xMail] Err 4-1");
            }
            return null;
        }
    }

    time = ((Double) o).longValue();

    o = map.get("unread");
    if (o == null || !(o instanceof Boolean)) {
        if (debug) {
            System.out.println("[xMail] Err 5");
        }
        return null;
    }
    unread = (Boolean) o;

    o = map.get("attachments");
    if (o == null || !(o instanceof List)) {
        if (debug) {
            System.out.println("[xMail] Err 6");
        }
        return null;
    }
    List<?> list = (List<?>) o;

    // We have to convert the list to a list of Strings
    List<String> list2 = new ArrayList<String>();
    List<Attachment> a2 = new ArrayList<Attachment>();
    for (Object o2 : list) {
        // Attachments will not be String lists, they will be <String, Object> maps because of Gson
        if (o2 instanceof Map) {
            Map<?, ?> item = (Map<?, ?>) o2; // Safe cast technique
            String jVal = JSONValue.toJSONString(item); // Put it back in JSON for Attachments class
            Attachment a = Attachments.getAttachment(jVal); // Generate the attachment
            if (a != null) {
                a2.add(a); // Add the attachment to the list
            }
        }
    }

    o = map.get("tags");
    if (o == null || !(o instanceof List)) {
        if (debug) {
            System.out.println("[xMail] Err 7");
        }
        return null;
    }
    list = (List<?>) o;

    o = map.get("uuid");
    if (o == null) {
        if (debug) {
            System.out.println("[xMail] Err 8");
        }
        return null;
    } else if (o instanceof String) {
        try {
            o = Integer.parseInt((String) o);
        } catch (NumberFormatException e) {
            if (debug) {
                System.out.println("[xMail] Err 8-1");
            }
            return null;
        }
    } else if (!(o instanceof Integer)) {
        if (debug) {
            System.out.println("[xMail] Err 9");
        }
        return null;
    }
    uuid = (Integer) o;

    // We have to convert the list to a list of Strings
    list2 = new ArrayList<String>();
    for (Object o2 : list) {
        if (o2 instanceof String) {
            list2.add((String) o2);
        }
    }
    tags = new ArrayList<String>(list2);

    // Now construct the mail object
    Mail mail = new Mail(to, from, a2);
    mail.setServerSender(sentFrom);
    mail.setTimestamp(time);
    mail.setUUID(uuid);
    if (unread) {
        mail.markUnread();
    } else {
        mail.markRead();
    }
    for (String tag : tags) {
        mail.addTag(tag);
    }

    // Throw it back
    return mail;
}

From source file:com.auto.solution.TestManager.TESTRAILTestManager.java

private Object sendRequest(String method, String uri, Object data)
        throws MalformedURLException, IOException, APIException {
    URL url = new URL(this.m_url + uri);

    // Create the connection object and set the required HTTP method
    // (GET/POST) and headers (content type and basic auth).
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.addRequestProperty("Content-Type", "application/json");

    String auth = getAuthorization(this.m_user, this.m_password);
    conn.addRequestProperty("Authorization", "Basic " + auth);

    if (method == "POST") {
        // Add the POST arguments, if any. We just serialize the passed
        // data object (i.e. a dictionary) and then add it to the
        // request body.
        if (data != null) {
            byte[] block = JSONValue.toJSONString(data).getBytes("UTF-8");

            conn.setDoOutput(true);/*  w  w w .j ava  2 s .  c om*/
            OutputStream ostream = conn.getOutputStream();
            ostream.write(block);
            ostream.flush();
        }
    }

    // Execute the actual web request (if it wasn't already initiated
    // by getOutputStream above) and record any occurred errors (we use
    // the error stream in this case).
    int status = conn.getResponseCode();

    InputStream istream;
    if (status != 200) {
        istream = conn.getErrorStream();
        if (istream == null) {
            throw new APIException(
                    "TestRail API return HTTP " + status + " (No additional error message received)");
        }
    } else {
        istream = conn.getInputStream();
    }

    // Read the response body, if any, and deserialize it from JSON.
    String text = "";
    if (istream != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(istream, "UTF-8"));

        String line;
        while ((line = reader.readLine()) != null) {
            text += line;
            text += System.getProperty("line.separator");
        }

        reader.close();
    }

    Object result;
    if (text != "") {
        result = JSONValue.parse(text);
    } else {
        result = new JSONObject();
    }

    // Check for any occurred errors and add additional details to
    // the exception message, if any (e.g. the error message returned
    // by TestRail).
    if (status != 200) {
        String error = "No additional error message received";
        if (result != null && result instanceof JSONObject) {
            JSONObject obj = (JSONObject) result;
            if (obj.containsKey("error")) {
                error = '"' + (String) obj.get("error") + '"';
            }
        }

        throw new APIException("TestRail API returned HTTP " + status + "(" + error + ")");
    }

    return result;
}

From source file:com.wasteofplastic.acidisland.schematics.Schematic.java

/**
 * This method pastes a schematic and returns a location where a cow (or other entity)
 * could be placed. Actually, the location should be that of a grass block.
 * @param world//  w  ww  .j  a v  a 2  s  . c om
 * @param loc
 * @param player
 * @return Location of highest grass block
 */
@SuppressWarnings("deprecation")
public void pasteSchematic(final Location loc, final Player player) {
    // If this is not a file schematic, paste the default island
    if (this.file == null) {
        if (Settings.GAMETYPE == GameType.ACIDISLAND) {
            generateIslandBlocks(loc, player);
        } else {
            loc.getBlock().setType(Material.BEDROCK);
            ASkyBlock.getPlugin().getLogger().severe("Missing schematic - using bedrock block only");
        }
        return;
    }
    World world = loc.getWorld();
    Map<BlockVector, Map<String, Tag>> tileEntitiesMap = this.getTileEntitiesMap();
    // Bukkit.getLogger().info("World is " + world.getName() +
    // "and schematic size is " + schematic.getBlocks().length);
    // Bukkit.getLogger().info("DEBUG Location to place island is:" +
    // loc.toString());
    // Find top most bedrock - this is the key stone
    // Find top most chest
    // Find top most grass
    Location bedrock = null;
    Location chest = null;
    Location welcomeSign = null;
    Set<Vector> grassBlocks = new HashSet<Vector>();
    for (int x = 0; x < width; ++x) {
        for (int y = 0; y < height; ++y) {
            for (int z = 0; z < length; ++z) {
                int index = y * width * length + z * width + x;
                // Bukkit.getLogger().info("DEBUG " + index +
                // " changing to ID:"+blocks[index] + " data = " +
                // blockData[index]);
                if (blocks[index] == 7) {
                    // Last bedrock
                    if (bedrock == null || bedrock.getY() < y) {
                        bedrock = new Location(world, x, y, z);
                        //Bukkit.getLogger().info("DEBUG higher bedrock found:" + bedrock.toString());
                    }
                } else if (blocks[index] == 54) {
                    // Last chest
                    if (chest == null || chest.getY() < y) {
                        chest = new Location(world, x, y, z);
                        // Bukkit.getLogger().info("Island loc:" +
                        // loc.toString());
                        // Bukkit.getLogger().info("Chest relative location is "
                        // + chest.toString());
                    }
                } else if (blocks[index] == 63) {
                    // Sign
                    if (welcomeSign == null || welcomeSign.getY() < y) {
                        welcomeSign = new Location(world, x, y, z);
                        // Bukkit.getLogger().info("DEBUG higher sign found:"
                        // + welcomeSign.toString());
                    }
                } else if (blocks[index] == 2) {
                    // Grass
                    grassBlocks.add(new Vector(x, y, z));
                }
            }
        }
    }
    if (bedrock == null) {
        Bukkit.getLogger().severe("Schematic must have at least one bedrock in it!");
        return;
    }
    if (chest == null) {
        Bukkit.getLogger().severe("Schematic must have at least one chest in it!");
        return;
    }
    /*
     * These are now optional
     * if (welcomeSign == null) {
     * Bukkit.getLogger().severe(
     * "ASkyBlock: Schematic must have at least one sign post in it!");
     * return null;
     * }
     */
    if (grassBlocks.isEmpty()) {
        Bukkit.getLogger().severe("Schematic must have at least one grass block in it!");
        return;
    }
    // Center on the last bedrock location
    //Bukkit.getLogger().info("DEBUG bedrock is:" + bedrock.toString());
    // Bukkit.getLogger().info("DEBUG loc is before subtract:" +
    // loc.toString());
    Location blockLoc = new Location(world, loc.getX(), loc.getY(), loc.getZ());
    blockLoc.subtract(bedrock);
    // Bukkit.getLogger().info("DEBUG loc is after subtract:" +
    // loc.toString());
    //Bukkit.getLogger().info("DEBUG blockloc is:" + blockLoc.toString());
    // Bukkit.getLogger().info("DEBUG there are " + tileEntitiesMap.size() +
    // " tile entities in the schematic");
    // Bukkit.getLogger().info("Placing blocks...");
    for (int x = 0; x < width; ++x) {
        for (int y = 0; y < height; ++y) {
            for (int z = 0; z < length; ++z) {
                int index = y * width * length + z * width + x;
                Block block = new Location(world, x, y, z).add(blockLoc).getBlock();
                try {
                    // Do not post torches because they fall off every so often
                    // May have to include banners too
                    if (blocks[index] != Material.TORCH.getId()) {
                        block.setTypeIdAndData(blocks[index], data[index], this.usePhysics);
                    }
                } catch (Exception e) {
                    // Do some 1.7.9 helping for the built-in schematic
                    if (blocks[index] == 179) {
                        // Red sandstone - use red sand instead
                        block.setTypeIdAndData(12, (byte) 1, this.usePhysics);
                    } else {
                        Bukkit.getLogger().info("Could not set (" + x + "," + y + "," + z + ") block ID:"
                                + blocks[index] + " block data = " + data[index]);
                    }
                }
            }
        }
    }

    // Second pass
    for (int x = 0; x < width; ++x) {
        for (int y = 0; y < height; ++y) {
            for (int z = 0; z < length; ++z) {
                int index = y * width * length + z * width + x;
                Block block = new Location(world, x, y, z).add(blockLoc).getBlock();
                try {
                    block.setTypeIdAndData(blocks[index], data[index], this.usePhysics);
                } catch (Exception e) {
                    // Do some 1.7.9 helping for the built-in schematic
                    if (blocks[index] == 179) {
                        // Red sandstone - use red sand instead
                        block.setTypeIdAndData(12, (byte) 1, this.usePhysics);
                    } else {
                        Bukkit.getLogger().info("Could not set (" + x + "," + y + "," + z + ") block ID:"
                                + blocks[index] + " block data = " + data[index]);
                    }
                }
                if (tileEntitiesMap.containsKey(new BlockVector(x, y, z))) {
                    String ver = Bukkit.getServer().getBukkitVersion();
                    int major = Integer.valueOf(ver.substring(0, 1));
                    int minor = Integer.valueOf(ver.substring(ver.indexOf(".") + 1, ver.indexOf(".") + 2));
                    if (major >= 1 && minor >= 8) {
                        if (block.getType() == Material.STANDING_BANNER
                                || block.getType() == Material.WALL_BANNER) {
                            BannerBlock.set(block, tileEntitiesMap.get(new BlockVector(x, y, z)));
                        }
                    }
                    if ((block.getType() == Material.SIGN_POST) || (block.getType() == Material.WALL_SIGN)) {
                        Sign sign = (Sign) block.getState();
                        Map<String, Tag> tileData = tileEntitiesMap.get(new BlockVector(x, y, z));

                        // for (String key : tileData.keySet()) {
                        // Bukkit.getLogger().info("DEBUG: key = " + key +
                        // " : " + tileData.get(key));
                        // //StringTag st = (StringTag) tileData.get(key);
                        // Bukkit.getLogger().info("DEBUG: key = " + key +
                        // " : " + st.getName() + " " + st.getValue());
                        // }
                        List<String> text = new ArrayList<String>();
                        text.add(((StringTag) tileData.get("Text1")).getValue());
                        text.add(((StringTag) tileData.get("Text2")).getValue());
                        text.add(((StringTag) tileData.get("Text3")).getValue());
                        text.add(((StringTag) tileData.get("Text4")).getValue());
                        // TODO Parse sign text formatting, colors and ULR's using JSON - this does not work right now

                        JSONParser parser = new JSONParser();
                        ContainerFactory containerFactory = new ContainerFactory() {
                            public List creatArrayContainer() {
                                return new LinkedList();
                            }

                            public Map createObjectContainer() {
                                return new LinkedHashMap();
                            }

                        };
                        /*
                        for (int line = 0; line < 4; line++) {
                        if (!text.get(line).equals("\"\"")) {
                           try{
                          Bukkit.getLogger().info("Text: '" + text.get(line) + "'");
                          Map json = (Map)parser.parse(text.get(line), containerFactory);
                          Iterator iter = json.entrySet().iterator();
                          System.out.println("==iterate result==");
                          while(iter.hasNext()){
                              Map.Entry entry = (Map.Entry)iter.next();
                              if (entry.getValue().toString().equals("extra")) {
                             List content = (List)parser.parse(entry)
                              }
                              System.out.println(entry.getKey() + "=>" + entry.getValue());
                          }
                                
                          System.out.println("==toJSONString()==");
                          System.out.println(JSONValue.toJSONString(json));
                           }
                           catch(ParseException pe){
                          System.out.println(pe);
                           }
                        }
                         */
                        // This just removes all the JSON formatting and provides the raw text
                        for (int line = 0; line < 4; line++) {
                            if (!text.get(line).equals("\"\"") && !text.get(line).isEmpty()) {
                                //String lineText = text.get(line).replace("{\"extra\":[\"", "").replace("\"],\"text\":\"\"}", "");
                                //Bukkit.getLogger().info("DEBUG: sign text = '" + text.get(line) + "'");
                                String lineText = "";
                                if (text.get(line).startsWith("{")) {
                                    // JSON string
                                    try {

                                        Map json = (Map) parser.parse(text.get(line), containerFactory);
                                        List list = (List) json.get("extra");
                                        //System.out.println("DEBUG1:" + JSONValue.toJSONString(list));
                                        Iterator iter = list.iterator();
                                        while (iter.hasNext()) {
                                            Object next = iter.next();
                                            String format = JSONValue.toJSONString(next);
                                            //System.out.println("DEBUG2:" + format);
                                            // This doesn't see right, but appears to be the easiest way to identify this string as JSON...
                                            if (format.startsWith("{")) {
                                                // JSON string
                                                Map jsonFormat = (Map) parser.parse(format, containerFactory);
                                                Iterator formatIter = jsonFormat.entrySet().iterator();
                                                while (formatIter.hasNext()) {
                                                    Map.Entry entry = (Map.Entry) formatIter.next();
                                                    //System.out.println("DEBUG3:" + entry.getKey() + "=>" + entry.getValue());
                                                    String key = entry.getKey().toString();
                                                    String value = entry.getValue().toString();
                                                    if (key.equalsIgnoreCase("color")) {
                                                        try {
                                                            lineText += ChatColor.valueOf(value.toUpperCase());
                                                        } catch (Exception noColor) {
                                                            Bukkit.getLogger().warning("Unknown color " + value
                                                                    + " in sign when pasting schematic, skipping...");
                                                        }
                                                    } else if (key.equalsIgnoreCase("text")) {
                                                        lineText += value;
                                                    } else {
                                                        // Formatting - usually the value is always true, but check just in case
                                                        if (key.equalsIgnoreCase("obfuscated")
                                                                && value.equalsIgnoreCase("true")) {
                                                            lineText += ChatColor.MAGIC;
                                                        } else if (key.equalsIgnoreCase("underlined")
                                                                && value.equalsIgnoreCase("true")) {
                                                            lineText += ChatColor.UNDERLINE;
                                                        } else {
                                                            // The rest of the formats
                                                            try {
                                                                lineText += ChatColor
                                                                        .valueOf(key.toUpperCase());
                                                            } catch (Exception noFormat) {
                                                                // Ignore
                                                                Bukkit.getLogger().warning("Unknown format "
                                                                        + value
                                                                        + " in sign when pasting schematic, skipping...");
                                                            }
                                                        }
                                                    }
                                                }
                                            } else {
                                                // This is unformatted text. It is included in "". A reset is required to clear
                                                // any previous formatting
                                                if (format.length() > 1) {
                                                    lineText += ChatColor.RESET + format.substring(
                                                            format.indexOf('"') + 1, format.lastIndexOf('"'));
                                                }
                                            }
                                        }
                                    } catch (ParseException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                } else {
                                    // This is unformatted text (not JSON). It is included in "".
                                    if (text.get(line).length() > 1) {
                                        lineText = text.get(line).substring(text.get(line).indexOf('"') + 1,
                                                text.get(line).lastIndexOf('"'));
                                    } else {
                                        // ust in case it isn't - show the raw line
                                        lineText = text.get(line);
                                    }
                                }
                                //Bukkit.getLogger().info("Line " + line + " is " + lineText);

                                // Set the line
                                sign.setLine(line, lineText);
                            }
                        }
                        sign.update();
                    }
                    if (block.getType().equals(Material.CHEST)) {
                        Chest chestBlock = (Chest) block.getState();
                        // Bukkit.getLogger().info("Chest tile entity found");
                        Map<String, Tag> tileData = tileEntitiesMap.get(new BlockVector(x, y, z));
                        try {
                            ListTag chestItems = (ListTag) tileData.get("Items");
                            if (chestItems != null) {
                                for (Tag item : chestItems.getValue()) {
                                    // Format for chest items is:
                                    // id = short value of item id
                                    // Damage = short value of item damage
                                    // Count = the number of items
                                    // Slot = the slot in the chest
                                    // inventory
                                    if (item instanceof CompoundTag) {
                                        try {
                                            // Id is a number
                                            short itemType = (Short) ((CompoundTag) item).getValue().get("id")
                                                    .getValue();
                                            short itemDamage = (Short) ((CompoundTag) item).getValue()
                                                    .get("Damage").getValue();
                                            byte itemAmount = (Byte) ((CompoundTag) item).getValue()
                                                    .get("Count").getValue();
                                            byte itemSlot = (Byte) ((CompoundTag) item).getValue().get("Slot")
                                                    .getValue();
                                            ItemStack chestItem = new ItemStack(itemType, itemAmount,
                                                    itemDamage);
                                            chestBlock.getInventory().setItem(itemSlot, chestItem);
                                        } catch (ClassCastException ex) {
                                            // Id is a material
                                            String itemType = (String) ((CompoundTag) item).getValue().get("id")
                                                    .getValue();
                                            try {
                                                // Get the material
                                                if (itemType.startsWith("minecraft:")) {
                                                    String material = itemType.substring(10).toUpperCase();
                                                    // Special case for non-standard material names
                                                    // REEDS, that is sugar
                                                    // cane
                                                    if (material.equalsIgnoreCase("REEDS")) {
                                                        material = "SUGAR_CANE";
                                                    }
                                                    if (material.equalsIgnoreCase("MYCELIUM")) {
                                                        material = "MYCEL";
                                                    }
                                                    if (material.equalsIgnoreCase("COOKED_PORKCHOP")) {
                                                        material = "GRILLED_PORK";
                                                    }
                                                    Material itemMaterial = Material.valueOf(material);
                                                    short itemDamage = (Short) ((CompoundTag) item).getValue()
                                                            .get("Damage").getValue();
                                                    byte itemAmount = (Byte) ((CompoundTag) item).getValue()
                                                            .get("Count").getValue();
                                                    byte itemSlot = (Byte) ((CompoundTag) item).getValue()
                                                            .get("Slot").getValue();
                                                    ItemStack chestItem = new ItemStack(itemMaterial,
                                                            itemAmount, itemDamage);
                                                    chestBlock.getInventory().setItem(itemSlot, chestItem);
                                                    // Bukkit.getLogger().info("Adding "
                                                    // +
                                                    // chestItem.toString()
                                                    // + " to chest");
                                                }
                                            } catch (Exception exx) {
                                                // Bukkit.getLogger().info(item.toString());
                                                // Bukkit.getLogger().info(((CompoundTag)item).getValue().get("id").getName());
                                                Bukkit.getLogger()
                                                        .severe("Could not parse item ["
                                                                + itemType.substring(10).toUpperCase()
                                                                + "] in schematic - skipping!");
                                                // Bukkit.getLogger().severe(item.toString());
                                                // exx.printStackTrace();
                                            }

                                        }

                                        // Bukkit.getLogger().info("Set chest inventory slot "
                                        // + itemSlot + " to " +
                                        // chestItem.toString());
                                    }
                                }
                            }
                        } catch (Exception e) {
                            Bukkit.getLogger().severe("Could not parse schematic file item, skipping!");
                            // e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
    // Go through all the grass blocks and try to find a safe one
    // Sort by height
    List<Vector> sorted = new ArrayList<Vector>();
    for (Vector v : grassBlocks) {
        v.subtract(bedrock.toVector());
        v.add(loc.toVector());
        v.add(new Vector(0.5D, 1.1D, 0.5D)); // Center of block
        //if (GridManager.isSafeLocation(v.toLocation(world))) {
        // Add to sorted list
        boolean inserted = false;
        for (int i = 0; i < sorted.size(); i++) {
            if (v.getBlockY() > sorted.get(i).getBlockY()) {
                sorted.add(i, v);
                inserted = true;
                break;
            }
        }
        if (!inserted) {
            // just add to the end of the list
            sorted.add(v);
        }
        //}
    }
    final Location grass = sorted.get(0).toLocation(world);
    //Bukkit.getLogger().info("DEBUG cow location " + grass.toString());
    Block blockToChange = null;
    // world.spawnEntity(grass, EntityType.COW);
    // Place a helpful sign in front of player
    if (welcomeSign != null) {
        // Bukkit.getLogger().info("DEBUG welcome sign schematic relative is:"
        // + welcomeSign.toString());
        welcomeSign.subtract(bedrock);
        // Bukkit.getLogger().info("DEBUG welcome sign relative to bedrock is:"
        // + welcomeSign.toString());
        welcomeSign.add(loc);
        // Bukkit.getLogger().info("DEBUG welcome sign actual position is:"
        // + welcomeSign.toString());
        blockToChange = welcomeSign.getBlock();
        blockToChange.setType(Material.SIGN_POST);
        Sign sign = (Sign) blockToChange.getState();
        sign.setLine(0, ASkyBlock.getPlugin().myLocale(player.getUniqueId()).signLine1.replace("[player]",
                player.getName()));
        sign.setLine(1, ASkyBlock.getPlugin().myLocale(player.getUniqueId()).signLine2.replace("[player]",
                player.getName()));
        sign.setLine(2, ASkyBlock.getPlugin().myLocale(player.getUniqueId()).signLine3.replace("[player]",
                player.getName()));
        sign.setLine(3, ASkyBlock.getPlugin().myLocale(player.getUniqueId()).signLine4.replace("[player]",
                player.getName()));
        // BlockFace direction = ((org.bukkit.material.Sign)
        // sign.getData()).getFacing();
        ((org.bukkit.material.Sign) sign.getData()).setFacingDirection(BlockFace.NORTH);
        sign.update();
    }
    chest.subtract(bedrock);
    chest.add(loc);
    // Place the chest - no need to use the safe spawn function because we
    // know what this island looks like
    blockToChange = chest.getBlock();
    // Bukkit.getLogger().info("Chest block = " + blockToChange);
    // blockToChange.setType(Material.CHEST);
    // Bukkit.getLogger().info("Chest item settings = " +
    // Settings.chestItems[0]);
    // Bukkit.getLogger().info("Chest item settings length = " +
    // Settings.chestItems.length);
    if (useDefaultChest && Settings.chestItems[0] != null) {
        // Fill the chest
        if (blockToChange.getType() == Material.CHEST) {
            final Chest islandChest = (Chest) blockToChange.getState();
            final Inventory inventory = islandChest.getInventory();
            inventory.clear();
            inventory.setContents(Settings.chestItems);
        }
    }
    if (Settings.islandCompanion != null) {
        Bukkit.getServer().getScheduler().runTaskLater(ASkyBlock.getPlugin(), new Runnable() {
            @Override
            public void run() {
                spawnCompanion(player, grass);
            }
        }, 40L);
    }
}

From source file:com.bigdata.dastor.db.CompactionManager.java

public String getColumnFamilyInProgress() {
    if (DatabaseDescriptor.isConcCompactionEnabled()) {
        List<String> cfNames = new ArrayList<String>();
        for (Map.Entry<ColumnFamilyStore, CompactionExecutor> e : cfsExecutorMap.entrySet()) {
            String cfName = e.getValue().getColumnFamilyName();
            if (cfName != null)
                cfNames.add(cfName);// w w  w  . j a  v a 2s.  co  m
        }
        return JSONValue.toJSONString(cfNames);
    } else {
        return executor.getColumnFamilyName();
    }
}