Example usage for org.json.simple.parser ContainerFactory ContainerFactory

List of usage examples for org.json.simple.parser ContainerFactory ContainerFactory

Introduction

In this page you can find the example usage for org.json.simple.parser ContainerFactory ContainerFactory.

Prototype

ContainerFactory

Source Link

Usage

From source file:com.appdynamics.monitors.pingdom.communicator.PingdomCommunicator.java

@SuppressWarnings("rawtypes")
private void getChecks(Map<String, Integer> metrics) {

    try {/*from  w ww. j  a va  2s. c  o  m*/
        HttpClient httpclient = new DefaultHttpClient();

        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
        HttpGet httpget = new HttpGet(baseAddress + "/api/2.0/checks");
        httpget.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));
        httpget.addHeader("App-Key", appkey);

        HttpResponse response;
        response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        // reading in the JSON response
        String result = "";
        if (entity != null) {
            InputStream instream = entity.getContent();
            int b;
            try {
                while ((b = instream.read()) != -1) {
                    result += Character.toString((char) b);
                }
            } finally {
                instream.close();
            }
        }

        // parsing the JSON response
        try {

            JSONParser parser = new JSONParser();

            ContainerFactory containerFactory = new ContainerFactory() {

                public List creatArrayContainer() {
                    return new LinkedList();
                }

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

            };

            // retrieving the metrics and populating HashMap
            JSONObject obj = (JSONObject) parser.parse(result);
            if (obj.get("checks") == null) {
                logger.error("Error retrieving data. " + obj);
                return;
            }
            JSONArray array = (JSONArray) parser.parse(obj.get("checks").toString());
            for (Object checkObj : array) {
                JSONObject check = (JSONObject) checkObj;

                Map json = (Map) parser.parse(check.toJSONString(), containerFactory);

                String metricName = "";

                if (json.containsKey("name")) {
                    metricName = "Checks|" + json.get("name") + "|";
                } else {
                    logger.error("Encountered error while parsing metrics for a check: no name found!");
                    continue;
                }

                if (json.containsKey("id")) {
                    try {
                        metrics.put(metricName + "id", Integer.parseInt(json.get("id").toString()));
                    } catch (NumberFormatException e) {
                        logger.error("Error parsing metric value for " + metricName + "id");
                    }
                }

                if (json.containsKey("lastresponsetime")) {
                    try {
                        metrics.put(metricName + "lastresponsetime",
                                Integer.parseInt(json.get("lastresponsetime").toString()));
                    } catch (NumberFormatException e) {
                        logger.error("Error parsing metric value for " + metricName + "lastresponsetime");
                    }
                }

                if (json.containsKey("lasttesttime")) {
                    try {
                        int testTime = Integer.parseInt(json.get("lasttesttime").toString());
                        java.util.Date date = new java.util.Date(testTime);
                        Calendar cal = GregorianCalendar.getInstance();
                        cal.setTime(date);

                        metrics.put(metricName + "lasttesttime", cal.get(Calendar.HOUR_OF_DAY));
                    } catch (NumberFormatException e) {
                        logger.error("Error parsing metric value for " + metricName + "lasttesttime");
                    } catch (Throwable t) {
                        logger.error("Error parsing metric value for " + metricName
                                + "lasttesttime: can't get hour of day");
                    }
                }

                if (json.containsKey("resolution")) {
                    try {
                        metrics.put(metricName + "resolution",
                                Integer.parseInt(json.get("resolution").toString()));
                    } catch (NumberFormatException e) {
                        logger.error("Error parsing metric value for " + metricName + "resolution");
                    }
                }

                if (json.containsKey("status")) {
                    String status = json.get("status").toString();
                    if (status != null) {
                        if (status.equals("down")) {
                            metrics.put(metricName + "status", 0);
                        } else if (status.equals("up")) {
                            metrics.put(metricName + "status", 1);
                        } else if (status.equals("unconfirmed_down")) {
                            metrics.put(metricName + "status", 5);
                        } else if (status.equals("unknown")) {
                            metrics.put(metricName + "status", 20);
                        } else if (status.equals("paused")) {
                            metrics.put(metricName + "status", 50);
                        } else {
                            logger.error("Error parsing metric value for " + metricName
                                    + "status: Unknown status '" + status + "'");
                        }
                    } else {
                        logger.error("Error parsing metric value for " + metricName + "status");
                    }
                }
            }

        } catch (ParseException e) {
            logger.error("JSON Parsing error: " + e.getMessage());
        } catch (Throwable e) {
            logger.error(e.getMessage());
        }

        // parse header in the end to get the Req-Limits
        Header[] responseHeaders = response.getAllHeaders();
        getLimits(metrics, responseHeaders);
    } catch (IOException e1) {
        logger.error(e1.getMessage());
    } catch (Throwable t) {
        logger.error(t.getMessage());
    }

}

From source file:kms.prolog.comms.TransportServlet.java

public ContainerFactory getJsonContainerFactory() {
    ContainerFactory jsonContainerFactory = new ContainerFactory() {
        public List<Object> creatArrayContainer() {
            return new LinkedList<Object>();
        }/* w ww . j a  v a2  s .com*/

        public Map<String, Object> createObjectContainer() {
            return new LinkedHashMap<String, Object>();
        }

    };
    return jsonContainerFactory;
}

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

static void handleConnection(Socket sock, Session session, int tid) {

    System.out.println("\n\n\n---------------->>>>>>>>>[" + tid + "]");

    try {//w  ww. j a  v a2 s.c o m
        int count = 0;
        boolean newConnection = true;
        String ip_add = sock.getInetAddress().toString();
        String[] _ip_add = ip_add.split("/");

        String macAddress = "";
        DeviceInfo myDevice = null;
        InputStream in = sock.getInputStream();
        OutputStream out = sock.getOutputStream();
        DataInputStream dis = new DataInputStream(in);
        DataOutputStream dos = new DataOutputStream(out);

        while (true) {

            System.out.println("\n[" + tid + "] My Socket : " + sock);

            String receivedData = ClientConnection.readFromStream(sock, dis, dos).trim();
            if (receivedData.equals("") || receivedData == null) {
                System.out.println("\n[Empty/Null Data][" + tid + "]");

            } else {

                System.out.println("\nReceived : " + receivedData);

                Map<String, String> jsonMap = null;
                JSONParser parser = new JSONParser();

                ContainerFactory containerFactory = new ContainerFactory() {

                    @SuppressWarnings("rawtypes")
                    @Override
                    public List creatArrayContainer() {
                        return new LinkedList();
                    }

                    @SuppressWarnings("rawtypes")
                    @Override
                    public Map createObjectContainer() {
                        return new LinkedHashMap();
                    }
                };

                try {
                    jsonMap = (Map<String, String>) parser.parse(receivedData, containerFactory);

                    if (jsonMap != null) {

                        String action = jsonMap.get(Constants.action);

                        if (action.compareTo(Constants.heartBeat) == 0
                                || action.compareTo(Constants.heartBeat1) == 0
                                || action.compareTo(Constants.heartBeat2) == 0) {

                            macAddress = jsonMap.get(Constants.macAddress);
                            // heartbeat    
                            System.out.println("\n [" + tid + "] HeartBeat Received : " + (++count));

                            DeviceInfo device = session.connectedClients.get(jsonMap.get(Constants.macAddress));
                            if (device == null) { // first time from this device. ie new connection

                                System.out.println("<<<== 1 ==>>>");
                                DeviceInfo newDevice = new DeviceInfo();
                                newDevice.setIp(jsonMap.get(Constants.ip));
                                newDevice.setPort(Integer.parseInt(jsonMap.get(Constants.port)));
                                newDevice.setMacAddress(jsonMap.get(Constants.macAddress));
                                newDevice.setBssid(jsonMap.get(Constants.bssid));
                                newDevice.setSsid(jsonMap.get(Constants.ssid));
                                // newDevice.setSsid(jsonMap.get(Constants.bssidList));

                                /* String apInfo = jsonMap.get(Constants.bssidList);
                                        
                                if (apInfo != null || !apInfo.equals("")) {
                                  System.out.println("\nInside Bssid List1");
                                String[] bssidInfo = apInfo.split(";");
                                NeighbourAccessPointDetails[] obj = new NeighbourAccessPointDetails[bssidInfo.length];
                                        
                                for (int i = 0; i < bssidInfo.length; i++) {
                                    String[] info = bssidInfo[i].split(",");
                                    obj[i].setBssid(info[0]);
                                    obj[i].setRssi(info[1]);
                                    obj[i].setRssi(info[2]);
                                }
                                newDevice.setBssidList(obj);
                                }*/
                                Date date = Utils.getCurrentTimeStamp();
                                newDevice.setLastHeartBeatTime(date);
                                newDevice.setInpStream(dis);
                                newDevice.setOutStream(dos);
                                newDevice.setConnectionStatus(true);
                                newDevice.setThread(Thread.currentThread());
                                newDevice.setSocket(sock);
                                newDevice.setGetlogrequestsend(false);

                                /*
                                remaining parameters needs to be added!!!
                                 */
                                session.connectedClients.put(jsonMap.get(Constants.macAddress), newDevice);

                            } else // subsequent heartbeats /  reconnection from same client
                            if (newConnection) { // reconnection from same client

                                System.out.println("<<<== 2 ==>>>");
                                if (device.thread != null) {
                                    device.thread.interrupt();
                                    System.out.println("\n@#1[" + tid + "] Interrupting old thread");
                                }

                                DeviceInfo newDevice = new DeviceInfo();
                                newDevice.setIp(jsonMap.get(Constants.ip));
                                newDevice.setPort(Integer.parseInt(jsonMap.get(Constants.port)));
                                newDevice.setMacAddress(jsonMap.get(Constants.macAddress));

                                newDevice.setBssid(jsonMap.get(Constants.bssid));
                                newDevice.setSsid(jsonMap.get(Constants.ssid));

                                /* String apInfo = jsonMap.get(Constants.bssidList);
                                if (apInfo != null || !apInfo.equals("")) {
                                    System.out.println("\nInside Bssid List");
                                                    
                                    String[] bssidInfo = apInfo.split(";");
                                    NeighbourAccessPointDetails[] obj = new NeighbourAccessPointDetails[bssidInfo.length];
                                    for (int i = 0; i < bssidInfo.length; i++) {
                                        String[] info = bssidInfo[i].split(",");
                                        obj[i].setBssid(info[0]);
                                        obj[i].setRssi(info[1]);
                                        obj[i].setRssi(info[2]);
                                    }
                                    newDevice.setBssidList(obj);
                                }*/
                                Date date = Utils.getCurrentTimeStamp();
                                newDevice.setLastHeartBeatTime(date);
                                newDevice.setInpStream(dis);
                                newDevice.setOutStream(dos);
                                newDevice.setSocket(sock);

                                newDevice.setThread(Thread.currentThread());
                                newDevice.setConnectionStatus(true);
                                newDevice.setGetlogrequestsend(false);
                                /*
                                remaining parameters needs to be added!!!
                                 */
                                session.connectedClients.remove(device.macAddress);
                                session.connectedClients.put(jsonMap.get(Constants.macAddress), newDevice);

                                if (session.filteredClients.contains(device)) {
                                    session.filteredClients.remove(device);
                                    session.filteredClients.add(newDevice);
                                }

                            } else { // heartbeat

                                System.out.println("<<<== 3 ==>>>");

                                Date date = Utils.getCurrentTimeStamp();
                                device.setLastHeartBeatTime(date);
                                device.setSocket(sock);
                                device.setConnectionStatus(true);
                            }

                        } else if (action.compareTo(Constants.experimentOver) == 0) {

                            macAddress = jsonMap.get(Constants.macAddress);

                            System.out.println("\n[" + tid + "] Experiment Over Mesage received");
                            // experiment over
                            // i need mac address from here
                            // ip and port also preferred
                            DeviceInfo device = session.connectedClients.get(jsonMap.get(Constants.macAddress));

                            if (device == null) { // new connection

                                System.out.println("<<<== 4 ==>>>");

                                DeviceInfo newDevice = new DeviceInfo();
                                newDevice.setIp(jsonMap.get(Constants.ip));
                                newDevice.setPort(Integer.parseInt(jsonMap.get(Constants.port)));
                                newDevice.setMacAddress(jsonMap.get(Constants.macAddress));
                                //Date date = Utils.getCurrentTimeStamp();
                                //newDevice.setLastHeartBeatTime(date);
                                newDevice.setInpStream(dis);
                                newDevice.setOutStream(dos);
                                newDevice.setSocket(sock);
                                newDevice.setThread(Thread.currentThread());
                                newDevice.setGetlogrequestsend(false);
                                newDevice.setConnectionStatus(true);

                                newDevice.setExpOver(1); //

                                if (DBManager.updateExperimentOverStatus(
                                        Integer.parseInt(jsonMap.get(Constants.experimentNumber)),
                                        newDevice.getMacAddress())) {
                                    System.out.println("\nDB Update ExpOver Success");
                                } else {
                                    System.out.println("\nDB Update ExpOver Failed");
                                }

                                /*
                                remaining parameters needs to be added!!!
                                 */
                                session.connectedClients.put(jsonMap.get(Constants.macAddress), newDevice);

                            } else if (newConnection) { // reconnction from the same client

                                System.out.println("<<<== 5 ==>>>");

                                if (device.thread != null) {
                                    device.thread.interrupt();
                                    System.out.println("\n@#2[" + tid + "] Interrupting old thread");
                                }

                                DeviceInfo newDevice = new DeviceInfo();
                                newDevice.setIp(jsonMap.get(Constants.ip));
                                newDevice.setPort(Integer.parseInt(jsonMap.get(Constants.port)));
                                newDevice.setMacAddress(jsonMap.get(Constants.macAddress));
                                //Date date = Utils.getCurrentTimeStamp();
                                //newDevice.setLastHeartBeatTime(date);
                                newDevice.setInpStream(dis);
                                newDevice.setOutStream(dos);
                                newDevice.setSocket(sock);

                                newDevice.setThread(Thread.currentThread());
                                newDevice.setGetlogrequestsend(false);
                                newDevice.setConnectionStatus(true);

                                /*
                                remaining parameters needs to be added!!!
                                 */
                                newDevice.setExpOver(1); //

                                if (DBManager.updateExperimentOverStatus(
                                        Integer.parseInt(jsonMap.get(Constants.experimentNumber)),
                                        newDevice.getMacAddress())) {
                                    System.out.println("\nDB Update ExpOver Success");
                                } else {
                                    System.out.println("\nDB Update ExpOver Failed");
                                }

                                session.connectedClients.remove(device.macAddress);
                                session.connectedClients.put(jsonMap.get(Constants.macAddress), newDevice);

                                if (session.filteredClients.contains(device)) {
                                    session.filteredClients.remove(device);
                                    session.filteredClients.add(newDevice);
                                }

                            } else {

                                System.out.println("<<<== 6 ==>>>");

                                // alread connected client
                                // device.setExpOver(jsonMap.get(Constants.macAddress))
                                device.setConnectionStatus(true);
                                device.setSocket(sock);
                                device.setExpOver(1); //

                                if (DBManager.updateExperimentOverStatus(
                                        Integer.parseInt(jsonMap.get(Constants.experimentNumber)),
                                        device.getMacAddress())) {
                                    System.out.println("\nDB Update ExpOver Success");
                                } else {
                                    System.out.println("\nDB Update ExpOver Failed");
                                }

                            }

                        } else if (action.compareTo(Constants.acknowledgement) == 0) {

                            System.out.println("\nAcknowledgement Received -->");
                            int expNumber = Integer.parseInt(jsonMap.get(Constants.experimentNumber));
                            System.out.println("\nExperiment number : " + expNumber);
                            //int sessionId = Utils.getCurrentSessionID();
                            int expId = 1;
                            ///important                                int expId =1;// Utils.getCurrentExperimentID(Integer.toString(1));
                            System.out.println("\nExperiment number : " + expNumber + "== " + expId);

                            //            if (expNumber == expId) {
                            if (macAddress != null && !macAddress.equals("")) {
                                DeviceInfo device = session.connectedClients.get(macAddress);
                                session.actualFilteredDevices.add(device);
                                System.out.println("\n Ack : " + expNumber + " Acknowledgement Received!!!");

                                if (DBManager.updateControlFileSendStatus(expNumber, macAddress, 1,
                                        "Successfully sent Control File")) {
                                    System.out.println("\n Ack : " + expNumber + " DB updated Successfully");
                                } else {
                                    System.out.println("\n Ack : " + expNumber + " DB updation Failed");
                                }
                                ///important                                        Utils.addExperimentDetails(expId, device, false);
                            }
                            //              }
                            // update the db.
                        } else {
                            System.out.println("\n[" + tid + "] Some Other Operation...");
                        }
                        newConnection = false;
                    }
                } catch (Exception ex) {
                    System.out.println("Json Ex : " + ex.toString());
                }
            }

            try {
                Thread.sleep(5000); // wait for interrupt
            } catch (InterruptedException ex) {
                System.out.println("\n[" + tid + "] InterruptedException 1 : " + ex.toString() + "\n");

                try {
                    sock.close();
                } catch (IOException ex1) {
                    System.out.println("\n[" + tid + "] IOException5 : " + ex1.toString() + "\n");
                }
                break; //
            }
        }

    } catch (IOException ex) {
        System.out.println("\n [" + tid + "] IOException1 : " + ex.toString() + "\n");
        try {
            sock.close();
            //    session.connectedClients.remove(conn);
        } catch (IOException ex1) {
            System.out.println("\n[" + tid + "] IOException2 : " + ex1.toString() + "\n");
        }
    } catch (Exception ex) {
        System.out.println("\n[" + tid + "] IOException3 : " + ex.toString() + "\n");
        try {
            sock.close();
            //    session.connectedClients.remove(conn);
        } catch (IOException ex1) {
            System.out.println("\n[" + tid + "] IOException4 : " + ex1.toString() + "\n");
        }
    }

}

From source file:com.larryTheCoder.schematic.IslandBlock.java

/**
 * Sets this block's sign data//ww  w. j a va2s.com
 *
 * @param tileData
 */
public void setSign(Map<String, Tag> tileData) {
    signText = new ArrayList<>();
    List<String> text = new ArrayList<>();
    for (int i = 1; i < 5; i++) {
        String line = ((StringTag) tileData.get("Text" + String.valueOf(i))).getValue();
        // This value can actually be a string that says null sometimes.
        if (line.equalsIgnoreCase("null")) {
            line = "";
        }
        //System.out.println("DEBUG: line " + i + " = '"+ line + "' of length " + line.length());
        text.add(line);
    }

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

        @Override
        public Map createObjectContainer() {
            return new LinkedHashMap<>();
        }

    };
    // This just removes all the JSON formatting and provides the raw text
    for (int line = 0; line < 4; line++) {
        String lineText = "";
        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) + "'");
            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));
                    if (list != null) {
                        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 += TextFormat.valueOf(value.toUpperCase());
                                        } catch (Exception noColor) {
                                            Utils.ConsoleMsg("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 += TextFormat.OBFUSCATED;
                                    } else if (key.equalsIgnoreCase("underlined")
                                            && value.equalsIgnoreCase("true")) {
                                        lineText += TextFormat.UNDERLINE;
                                    } else {
                                        // The rest of the formats
                                        try {
                                            lineText += TextFormat.valueOf(key.toUpperCase());
                                        } catch (Exception noFormat) {
                                            // Ignore
                                            //System.out.println("DEBUG3:" + key + "=>" + value);
                                            Utils.ConsoleMsg("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 += TextFormat.RESET + format.substring(format.indexOf('"') + 1,
                                            format.lastIndexOf('"'));
                                }
                            }
                        }
                    } else {
                        // No extra tag
                        json = (Map) parser.parse(text.get(line), containerFactory);
                        String value = (String) json.get("text");
                        //System.out.println("DEBUG text only?:" + value);
                        lineText += value;
                    }
                } 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) {
                try {
                    lineText = text.get(line).substring(text.get(line).indexOf('"') + 1,
                            text.get(line).lastIndexOf('"'));
                } catch (Exception e) {
                    //There may not be those "'s, so just use the raw line
                    lineText = text.get(line);
                }
            } else {
                // just in case it isn't - show the raw line
                lineText = text.get(line);
            }
            //Bukkit.getLogger().info("Line " + line + " is " + lineText);
        }
        signText.add(lineText);
    }
}

From source file:net.mybox.mybox.Common.java

/**
 * Turn the json input string into a HashMap
 * @param input//from w  w w  .ja  va 2s . c  o m
 * @return
 */
public static HashMap jsonDecode(String input) {

    // TODO: make this recursive for nested JSON objects and perhaps arrays as well

    HashMap result = new HashMap();

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

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

    try {
        Map json = (Map) parser.parse(input, containerFactory);
        Iterator iter = json.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            result.put(entry.getKey(), entry.getValue());
        }
    } catch (Exception pe) {
        System.out.println(pe);
    }

    return result;
}

From source file:com.turt2live.xmail.engine.connection.PHPConnection2A.java

@SuppressWarnings("unchecked")
@Override// ww  w  . j  a  v  a  2  s .c o m
public void init() {
    ServerResponse response = attemptRequest(RequestType.REQUEST_AUTH); // Start a request for auth
    if (response.getErrorCode() == 403) {
        throw new IllegalAccessError("xMail server denied authentication request");
    } else if (response.getErrorCode() < 0) {
        throw new IllegalAccessError("xMail server cannot be reached");
    }
    List<String> lines = attemptRequest(RequestType.INFORMATION).getLines();
    for (String line : lines) {
        JSONParser parser = new JSONParser();
        ContainerFactory containerFactory = new ContainerFactory() {
            @Override
            public List<Object> creatArrayContainer() {
                return new LinkedList<Object>();
            }

            @Override
            public Map<String, Object> createObjectContainer() {
                return new LinkedHashMap<String, Object>();
            }

        };

        Map<String, Object> map = new HashMap<String, Object>();

        try {
            Map<?, ?> json = (Map<?, ?>) parser.parse(line, containerFactory);
            Iterator<?> iter = json.entrySet().iterator();

            // Type check
            while (iter.hasNext()) {
                Entry<?, ?> entry = (Entry<?, ?>) iter.next();
                if (!(entry.getKey() instanceof String)) {
                    throw new IllegalArgumentException("Not in <String, Object> format");
                }
            }

            map = (Map<String, Object>) json;
        } catch (ParseException e) {
            e.printStackTrace();
            return;
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return;
        }
        if (map.containsKey("password-policy")) {
            // It will be a <String, Object>
            Map<String, Object> pw = (Map<String, Object>) map.get("password-policy");
            String method = (String) pw.get("method");
            // It will be a <String, Object>
            Map<String, Object> saltOpts = (Map<String, Object>) pw.get("salt");
            String salt = (String) saltOpts.get("salt");
            String format = (String) saltOpts.get("format");
            super.generatePasswordPolicy(PasswordPolicy.Method.getMethod(method), salt, format);
        }
        if (map.containsKey("time")) {
            Object time = map.get("time");
            if (time instanceof Double) {
                long t = ((Double) time).longValue();
                super.connectionTime.reportedTime = t;
                super.connectionTime.requestedTime = System.currentTimeMillis() / 1000;
            }
        }
    }
    if (super.getPasswordPolicy() != null) {
        String testHash = super.getPasswordPolicy().hashPassword("test-xmail-password");
        if (testHash == null) {
            super.generatePasswordPolicy(Method.SHA1, "", "P"); // Default
        }
    } else {
        super.generatePasswordPolicy(Method.SHA1, "", "P"); // Default
    }
}

From source file:com.wasteofplastic.askyblock.schematics.IslandBlock.java

/**
 * Sets this block's sign data// w  ww .  j a v  a2  s . com
 * @param tileData
 */
public void setSign(Map<String, Tag> tileData) {
    signText = new ArrayList<String>();
    List<String> text = new ArrayList<String>();
    for (int i = 1; i < 5; i++) {
        String line = ((StringTag) tileData.get("Text" + String.valueOf(i))).getValue();
        // This value can actually be a string that says null sometimes.
        if (line.equalsIgnoreCase("null")) {
            line = "";
        }
        //System.out.println("DEBUG: line " + i + " = '"+ line + "' of length " + line.length());
        text.add(line);
    }

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

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

    };
    // This just removes all the JSON formatting and provides the raw text
    for (int line = 0; line < 4; line++) {
        String lineText = "";
        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) + "'");
            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));
                    if (list != null) {
                        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
                                                //System.out.println("DEBUG3:" + key + "=>" + value);
                                                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('"'));
                                }
                            }
                        }
                    } else {
                        // No extra tag
                        json = (Map) parser.parse(text.get(line), containerFactory);
                        String value = (String) json.get("text");
                        //System.out.println("DEBUG text only?:" + value);
                        lineText += value;
                    }
                } 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) {
                    try {
                        lineText = text.get(line).substring(text.get(line).indexOf('"') + 1,
                                text.get(line).lastIndexOf('"'));
                    } catch (Exception e) {
                        //There may not be those "'s, so just use the raw line
                        lineText = text.get(line);
                    }
                } else {
                    // just in case it isn't - show the raw line
                    lineText = text.get(line);
                }
            }
            //Bukkit.getLogger().info("Line " + line + " is " + lineText);
        }
        signText.add(lineText);
    }
}

From source file:com.ooyala.api.OoyalaAPI.java

/**
 * Executes the request//  w  w  w  .  j  a  v a  2 s. c om
 * @param method The class containing the type of request (HttpGet, HttpDelete, etc)
 * @return The response from the server as an object of class Object. Must be casted to either a LinkedList<String> or an HashMap<String, Object>
 * @throws ClientProtocolException
 * @throws IOException
 * @throws HttpStatusCodeException 
 */
private Object executeRequest(HttpRequestBase method)
        throws ClientProtocolException, IOException, HttpStatusCodeException {
    HttpClient httpclient = new DefaultHttpClient();
    String response = httpclient.execute(method, createResponseHandler());
    if (!isResponseOK())
        throw new HttpStatusCodeException(response, getResponseCode());

    if (response.isEmpty())
        return null;

    JSONParser parser = new JSONParser();

    ContainerFactory containerFactory = new ContainerFactory() {
        @SuppressWarnings("rawtypes")
        public List creatArrayContainer() {
            return new LinkedList();
        }

        @SuppressWarnings("rawtypes")
        public java.util.Map createObjectContainer() {
            return new LinkedHashMap();
        }
    };

    //HashMap<String, Object> json = null;
    Object json = null;

    try {
        json = parser.parse(response, containerFactory);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    log.d("Response: " + json.toString());
    return json;
}

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/*from w w w  . ja va  2  s.c  o m*/
 * @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.turt2live.xmail.mail.Mail.java

/**
 * Creates a new mail object from a JSON string
 *
 * @param json the json string/*  ww w. j a v  a 2 s.  co  m*/
 *
 * @return the NewMail object or null if the json is invalid
 */
@SuppressWarnings("unchecked")
public static Mail fromJSON(String json) {
    // Construct map from JSON
    JSONParser parser = new JSONParser();
    ContainerFactory containerFactory = new ContainerFactory() {
        @Override
        public List<Object> creatArrayContainer() {
            return new LinkedList<Object>();
        }

        @Override
        public Map<String, Object> createObjectContainer() {
            return new LinkedHashMap<String, Object>();
        }

    };

    Map<String, Object> map = new HashMap<String, Object>();

    try {
        Map<?, ?> jsonMap = (Map<?, ?>) parser.parse(json, containerFactory);
        Iterator<?> iter = jsonMap.entrySet().iterator();

        // Type check
        while (iter.hasNext()) {
            Entry<?, ?> entry = (Entry<?, ?>) iter.next();
            if (!(entry.getKey() instanceof String)) {
                throw new IllegalArgumentException("Not in <String, Object> format");
            }
        }

        map = (Map<String, Object>) jsonMap;
    } catch (ParseException e) {
        e.printStackTrace();
        return null;
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        return null;
    }
    return fromJSON(map);
}