Example usage for org.json.simple JSONValue parse

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

Introduction

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

Prototype

public static Object parse(String s) 

Source Link

Usage

From source file:de.dailab.plistacontest.client.RecommenderItem.java

/**
 * parse the event notification.//from w w  w . ja  v a2  s  . com
 * 
 * @param _jsonMessageBody
 * @return
 */
public static RecommenderItem parseEventNotification(final String _jsonMessageBody) {

    try {
        final JSONObject jsonObj = (JSONObject) JSONValue.parse(_jsonMessageBody);

        // parse JSON structure to obtain "context.simple"
        JSONObject jsonObjectContext = (JSONObject) jsonObj.get("context");
        JSONObject jsonObjectContextSimple = (JSONObject) jsonObjectContext.get("simple");

        Long domainID = -3L;
        try {
            domainID = Long.valueOf(jsonObjectContextSimple.get("27").toString());
        } catch (Exception ignored) {
            try {
                domainID = Long.valueOf(jsonObj.get("domainID").toString());
            } catch (Exception e) {
                System.err.println("[Exception] no domainID found in " + _jsonMessageBody);
            }
        }

        Long itemID = null;
        try {
            itemID = Long.valueOf(jsonObjectContextSimple.get("25").toString());
        } catch (Exception ignored) {
            try {
                itemID = Long.valueOf(jsonObj.get("itemID").toString());
            } catch (Exception e) {
                System.err.println("[Exception] no itemID found in " + _jsonMessageBody);
            }
        }

        Long userID = -2L;
        try {
            userID = Long.valueOf(jsonObjectContextSimple.get("57").toString());
        } catch (Exception ignored) {
            try {
                userID = Long.valueOf(jsonObj.get("userID").toString());
            } catch (Exception e) {
                System.err.println("[Exception] no userID found in " + _jsonMessageBody);
            }
        }

        // impressionType
        String notificationType = null;
        try {
            notificationType = jsonObj.get("type") + "";
        } catch (Exception e) {
            e.printStackTrace();
        }

        // event_type due to the idomaar data format
        String eventType = null;
        try {
            eventType = jsonObj.get("event_type") + "";
            if (!"null".equals(eventType)) {
                notificationType = eventType;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // list of displayed recs
        List<Long> listOfDisplayedRecs = new ArrayList<Long>(6);
        try {
            Object jsonObjectRecsTmp = jsonObj.get("recs");
            if (jsonObjectRecsTmp == null || !(jsonObjectRecsTmp instanceof JSONObject)) {
                System.err.println("[INFO] impression without recs " + jsonObj);
            } else {
                JSONObject jsonObjectRecs = (JSONObject) jsonObjectRecsTmp;
                JSONObject jsonObjectRecsInt = (JSONObject) jsonObjectRecs.get("ints");
                JSONArray array = (JSONArray) jsonObjectRecsInt.get("3");
                for (Object arrayEntry : array) {
                    listOfDisplayedRecs.add(Long.valueOf(arrayEntry + ""));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("invalid jsonObject: " + jsonObj);
        }

        long timeStamp = 0;
        try {
            timeStamp = (Long) jsonObj.get("created_at") + 0L;
        } catch (Exception ignored) {
            timeStamp = (Long) jsonObj.get("timestamp");
        }

        // create the result and return
        RecommenderItem result = new RecommenderItem(userID, itemID, domainID, timeStamp);
        result.setNotificationType(notificationType);
        result.setListOfDisplayedRecs(listOfDisplayedRecs);

        return result;

    } catch (Throwable t) {
        t.printStackTrace();
        return null;
    }
}

From source file:ch.simas.jtoggl.JToggl.java

/**
 * Update a client./*from   w w  w.  j a  v  a 2  s  . co  m*/
 * 
 * @param clientObject
 * @return updated {@link ch.simas.jtoggl.Client}
 */
public ch.simas.jtoggl.Client updateClient(ch.simas.jtoggl.Client clientObject) {
    Client client = prepareClient();
    String url = CLIENT.replace(PLACEHOLDER, clientObject.getId().toString());
    WebResource webResource = client.resource(url);

    JSONObject object = createClientRequestParameter(clientObject);
    String response = webResource.entity(object.toJSONString(), MediaType.APPLICATION_JSON_TYPE)
            .put(String.class);

    object = (JSONObject) JSONValue.parse(response);
    JSONObject data = (JSONObject) object.get(DATA);
    return new ch.simas.jtoggl.Client(data.toJSONString());
}

From source file:com.flaptor.indextank.index.IndexEngine.java

public static void main(String[] args) throws IOException {
    String log4jConfigPath = com.flaptor.util.FileUtil.getFilePathFromClasspath("log4j.properties");
    if (null != log4jConfigPath) {
        org.apache.log4j.PropertyConfigurator.configureAndWatch(log4jConfigPath);
    } else {/*from   w  w w. j a  v a  2 s.co  m*/
        logger.warn("log4j.properties not found on classpath!");
    }
    // create the parser
    CommandLineParser parser = new PosixParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(getOptions(), args);
        if (line.hasOption("help")) {
            printHelp(getOptions(), null);
            System.exit(1);
        }

        File baseDir = new File(line.getOptionValue("dir"));
        int basePort = Integer.parseInt(line.getOptionValue("port", String.valueOf(DEFAULT_BASE_PORT)));
        int boostsSize = Integer.parseInt(line.getOptionValue("boosts", String.valueOf(1)));
        int rtiSize = Integer.parseInt(line.getOptionValue("rti-size", String.valueOf(DEFAULT_RTI_SIZE)));
        boolean loadState = line.hasOption("load-state");

        SuggestValues suggest;
        if (line.hasOption("suggest")) {
            String value = line.getOptionValue("suggest");
            if (value.equalsIgnoreCase("queries")) {
                suggest = SuggestValues.QUERIES;
            } else if (value.equalsIgnoreCase("documents")) {
                suggest = SuggestValues.DOCUMENTS;
            } else {
                throw new IllegalArgumentException(
                        "Invalid value for suggest: can only be \"queries\" or \"documents\".");
            }
        } else {
            suggest = SuggestValues.NO;
        }

        StorageValues storageValue = StorageValues.RAM;
        int bdbCache = 0;
        if (line.hasOption("storage")) {
            String storageType = line.getOptionValue("storage");
            if ("bdb".equals(storageType)) {
                storageValue = StorageValues.BDB;
                bdbCache = Integer
                        .parseInt(line.getOptionValue("bdb-cache", String.valueOf(DEFAULT_BDB_CACHE)));
            } else if ("cassandra".equals(storageType)) {
                storageValue = StorageValues.CASSANDRA;
            } else if ("ram".equals(storageType)) {
                storageValue = StorageValues.RAM;
            } else {
                throw new IllegalArgumentException(
                        "storage has to be 'cassandra', 'bdb' or 'ram'. '" + storageType + "' given.");
            }
        }

        String functions = null;
        if (line.hasOption("functions")) {
            functions = line.getOptionValue("functions");
        }

        String environment;
        String val = line.getOptionValue("environment-prefix", null);
        if (null != val) {
            environment = val;
        } else {
            environment = "";
        }
        logger.info("Command line option 'environment-prefix' set to " + environment);

        boolean facets = line.hasOption("facets");
        logger.info("Command line option 'facets' set to " + facets);
        String indexCode = line.getOptionValue("index-code");
        logger.info("Command line option 'index-code' set to " + indexCode);

        Map<Object, Object> configuration = Maps.newHashMap();

        String configFile = line.getOptionValue("conf-file", null);
        logger.info("Command line option 'conf-file' set to " + configFile);

        if (configFile != null) {
            configuration = (Map<Object, Object>) JSONValue.parse(FileUtil.readFile(new File(configFile)));
        }
        IndexEngine ie = new IndexEngine(baseDir, basePort, rtiSize, loadState, boostsSize, suggest,
                storageValue, bdbCache, functions, facets, indexCode, environment, configuration);

        BoostingIndexer indexer = ie.getIndexer();
        DocumentSearcher searcher = ie.getSearcher();
        Suggestor suggestor = ie.getSuggestor();
        DocumentStorage storage = ie.getStorage();

        if (line.hasOption("snippets")) {
            // shouldn't this be set based on storageValue? 
            indexer = new DocumentStoringIndexer(indexer, storage);
            ie.setIndexer(indexer);
            searcher = new SnippetSearcher(searcher, storage, ie.getParser());
        }

        if (line.hasOption("didyoumean")) {
            if (suggest != SuggestValues.DOCUMENTS) {
                throw new IllegalArgumentException("didyoumean requires --suggest documents");
            }
            DidYouMeanSuggestor dym = new DidYouMeanSuggestor((TermSuggestor) ie.getSuggestor());
            searcher = new DidYouMeanSearcher(searcher, dym);
        }

        searcher = new TrafficLimitingSearcher(searcher);
        Runtime.getRuntime().addShutdownHook(new ShutdownThread(indexer));

        new SearcherServer(searcher, ie.getParser(), ie.boostsManager, ie.scorer, basePort + 2).start();
        new SuggestorServer(suggestor, basePort + 3).start();
        IndexerServer indexerServer = new IndexerServer(ie, indexer, basePort + 1);
        indexerServer.start();

    } catch (ParseException exp) {
        printHelp(getOptions(), exp.getMessage());
    }

}

From source file:com.mobicage.rogerthat.xmpp.CallBackApiXMPPListener.java

/**
 * Establish an XMPP connection to XmppService and listen for Rogerthat API callbacks.
 *//* w w w  . j a va  2 s.com*/
public void startListening() {

    if (connectionThread != null) {
        throw new RuntimeException("Previous connection has not yet been closed!");
    }

    if (xmppUsername == null || xmppService == null || xmppPassword == null || sik == null)
        throw new RuntimeException("Not enough information present to setup an xmpp connection");

    final ConnectionListener connectionListener = new ConnectionListener() {
        @Override
        public void reconnectionSuccessful() {
            log.info("Reconnection to jabber server succeeded.");
            status = XmppConnectionStatus.Connected;
        }

        @Override
        public void reconnectionFailed(Exception e) {
            log.info("Reconnection to jabber server failed.");
        }

        @Override
        public void reconnectingIn(int seconds) {
            log.info("Reconnecting to jabber in " + seconds + " seconds ...");
            status = XmppConnectionStatus.Reconnecting;
        }

        @Override
        public void connectionClosedOnError(Exception e) {
            log.info("Connection closed to jabber due to " + e.toString());
        }

        @Override
        public void connectionClosed() {
            log.info("Connection to jabber closed.");
        }
    };

    tasks.clear();

    connectionThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                while (true) {
                    Runnable task = tasks.take();
                    task.run();
                }
            } catch (StopListeningException e) {
                disconnect(connectionListener);
                status = XmppConnectionStatus.Closed;
                statusLine = "";
            } catch (Throwable e) {
                disconnect(connectionListener);
                status = XmppConnectionStatus.Closed;
                statusLine = "Connection interrupted.";
            } finally {
                connectionThread = null;
            }
        }
    });
    connectionThread.setName("Rogerthat callback listener");
    connectionThread.setDaemon(true);
    connectionThread.start();

    tasks.add(new Runnable() {
        @Override
        public void run() {
            ConnectionConfiguration conf = new ConnectionConfiguration(xmppService);

            status = XmppConnectionStatus.Connecting;

            log.info("Connecting to jabber server ...");
            conn = new XMPPConnection(conf);
            try {
                conn.connect();
            } catch (XMPPException e) {
                status = XmppConnectionStatus.ConnectionFailed;
                statusLine = "Failed to reach Rogerthat servers.\n" + e.getMessage();
                conn = null;
                connectionThread = null;
                if (onConnectionFailed != null)
                    try {
                        onConnectionFailed.run();
                    } catch (Throwable t) {
                        log.log(Level.WARNING, "Failure in onConnectionFailed handler.", t);
                    }
                throw new RuntimeException(e); // Stop thread.
            }

            if (onConnected != null)
                try {
                    onConnected.run();
                } catch (Throwable t) {
                    log.log(Level.WARNING, "Failure in onConnected handler.", t);
                }

            conn.addConnectionListener(connectionListener);

            SASLAuthentication.supportSASLMechanism("PLAIN", 0);

            PacketFilter filter = new PacketFilter() {
                @Override
                public boolean accept(Packet packet) {
                    boolean accept = packet instanceof Message
                            && ROGERTHAT_CALLBACK_BOT.equals(packet.getFrom());
                    if (!accept)
                        log.info("Dropping packet:\n" + packet.toXML());
                    return accept;
                }
            };

            conn.addPacketListener(new PacketListener() {
                @Override
                public void processPacket(Packet packet) {
                    log.info("Processing packet:\n" + packet.toXML());
                    if (!(packet instanceof Message)) {
                        log.info("Ignoring non message packet.");
                        return;
                    }
                    Message message = (Message) packet;
                    PacketExtension extension = packet.getExtension("call", "mobicage:comm");
                    if (extension == null || !(extension instanceof CallbackRequestExtension)) {
                        log.info("Ignoring incomplete packet.");
                        return;
                    }
                    CallbackRequestExtension call = (CallbackRequestExtension) extension;
                    if (!sik.equals(call.getSik())) {
                        log.info("Ignoring packet with incorrect sik.");
                        return;
                    }
                    String json;
                    try {
                        json = new String(DatatypeConverter.parseBase64Binary(call.getBase64Body()), "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        log.log(Level.WARNING, "Could not decode base64 packet.", e);
                        return;
                    }
                    final JSONObject request = (JSONObject) JSONValue.parse(json);

                    if (logTraffic)
                        log.info(String.format("Incoming Rogerthat API Callback.\nSIK: %s\n\n%s", sik, json));

                    final String id = (String) request.get("id");

                    if (callbackDedup != null) {
                        byte[] response = callbackDedup.getResponse(id);
                        if (response != null) {
                            Message resultMessage = new Message(message.getFrom());
                            resultMessage.setFrom(message.getTo());
                            resultMessage.addExtension(new CallbackResponseExtension(sik,
                                    DatatypeConverter.printBase64Binary(response)));
                            log.info("Sending message:\n" + resultMessage.toXML());
                            conn.sendPacket(resultMessage);
                            return;
                        }
                    }

                    final JSONObject result = new JSONObject();
                    final RequestContext requestContext = new RequestContext(id, sik);
                    try {
                        processor.process(request, result, requestContext);
                    } finally {
                        try {
                            StringWriter writer = new StringWriter();
                            try {
                                result.writeJSONString(writer);
                                writer.flush();
                                json = writer.toString();

                                if (logTraffic)
                                    log.info("Returning result:\n" + json);

                            } finally {
                                writer.close();
                            }
                        } catch (IOException e) {
                            log.log(Level.SEVERE, "Could not write json object to string", e);
                            return;
                        }
                        Message resultMessage = new Message(message.getFrom());
                        resultMessage.setFrom(message.getTo());
                        try {
                            byte[] response = json.getBytes("UTF-8");
                            resultMessage.addExtension(new CallbackResponseExtension(sik,
                                    DatatypeConverter.printBase64Binary(response)));
                            if (callbackDedup != null) {
                                callbackDedup.storeResponse(id, response);
                            }
                        } catch (UnsupportedEncodingException e) {
                            log.log(Level.SEVERE, "Could not add result to message packet", e);
                            return;
                        }
                        log.info("Sending message:\n" + resultMessage.toXML());
                        conn.sendPacket(resultMessage);
                    }

                }
            }, filter);

            try {
                conn.login(xmppUsername, xmppPassword);
            } catch (XMPPException e1) {
                status = XmppConnectionStatus.ConnectionFailed;
                statusLine = "Failed to authenticate jabber connection. Verify your configuration.\n"
                        + e1.getMessage();
                conn = null;
                connectionThread = null;
                if (onAuthenticationFailed != null)
                    try {
                        onAuthenticationFailed.run();
                    } catch (Throwable t) {
                        log.log(Level.WARNING, "Failure in onAuthenticationFailed handler.", t);
                    }
                throw new RuntimeException(); // Stop thread.
            }

            status = XmppConnectionStatus.Connected;

            if (onAuthenticated != null)
                try {
                    onAuthenticated.run();
                } catch (Throwable t) {
                    log.log(Level.WARNING, "Failure in onAuthenticated handler.", t);
                }
        }
    });

}

From source file:edu.iu.incntre.flowscalestatcollector.StatCollector.java

public void startUp() {

    logger.trace("Startup of StatCollector");
    try {/*  w  w w. j a va 2 s. co m*/
        if (isQuery) {

            // initiate sqlite database

            try {

                Class.forName(databaseClass);
                conn = DriverManager.getConnection(databaseDriver, dbUsername, dbPassword);

            } catch (ClassNotFoundException e2) {

                logger.error("{}", e2);
            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                logger.error("{}", e1);
            }

            // end initiate database

            // start up thread

            statThread = new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        logger.trace("Starting Thread ..");
                        logger.trace("Getting flows from switch every {} seconds", intervalTime);

                        List<OFStatistics> portStats;
                        List<OFStatistics> flowStats;
                        List<OFPhysicalPort> portStatus;
                        SwitchDevice swd = null;
                        String[] datapathIdStringElements = datapathIdStrings.split(",");
                        try {

                            while (statThread != null) {
                                calendar = Calendar.getInstance();
                                logger.trace("getting flows from switches");

                                //check if conn is null if it is, reset connection 
                                if (conn == null) {
                                    conn = DriverManager.getConnection(databaseDriver, dbUsername, dbPassword);
                                }

                                for (String datapathIdString : datapathIdStringElements) {

                                    try {

                                        swd = flowscaleController.getSwitchDevices()
                                                .get(HexString.toLong(datapathIdString));

                                        if (swd == null) {
                                            logger.info("switch {} does not exist, is it connected?",
                                                    datapathIdString);
                                            continue;
                                        }

                                        logger.info("Getting flows from switch {} with ID {}",
                                                swd.getSwitchName(), datapathIdString);

                                        try {
                                            portStats = flowscaleController
                                                    .getSwitchStatisticsFromInterface(datapathIdString, "port");

                                            flowStats = flowscaleController
                                                    .getSwitchStatisticsFromInterface(datapathIdString, "flow");

                                            portStatus = swd.getPortStates();

                                            if (flowStats != null && portStats != null) {

                                                String flowStatsJSON = JSONConverter.toStat(flowStats, "flow")
                                                        .toJSONString();
                                                String portStatsJSON = JSONConverter.toStat(portStats, "port")
                                                        .toJSONString();
                                                String portStatusJSON = JSONConverter.toPortStatus(portStatus)
                                                        .toJSONString();

                                                // initialize or set hashmaps

                                                HashMap<Long, Long> tempPortStatTransmitted;
                                                HashMap<Long, Long> tempPortStatReceived;
                                                HashMap<String, Long> tempFlowStat;

                                                long datapathId = HexString.toLong(datapathIdString);
                                                if (tempPortStatTransmittedHashMap.get(datapathId) == null) {

                                                    tempPortStatTransmitted = new HashMap<Long, Long>();
                                                    tempPortStatTransmittedHashMap.put(datapathId,
                                                            tempPortStatTransmitted);
                                                } else {
                                                    tempPortStatTransmitted = tempPortStatTransmittedHashMap
                                                            .get(datapathId);

                                                }

                                                if (tempPortStatReceivedHashMap.get(datapathId) == null) {
                                                    tempPortStatReceived = new HashMap<Long, Long>();
                                                    tempPortStatReceivedHashMap.put(datapathId,
                                                            tempPortStatReceived);
                                                } else {
                                                    tempPortStatReceived = tempPortStatReceivedHashMap
                                                            .get(datapathId);
                                                }
                                                if (tempFlowStatHashMap.get(datapathId) == null) {
                                                    tempFlowStat = new HashMap<String, Long>();
                                                    tempFlowStatHashMap.put(datapathId, tempFlowStat);
                                                } else {

                                                    tempFlowStat = tempFlowStatHashMap.get(datapathId);
                                                }

                                                storeSwitchDetails(HexString.toLong(datapathIdString),
                                                        portStatsJSON, flowStatsJSON, portStatusJSON,
                                                        tempPortStatTransmitted, tempPortStatReceived,
                                                        tempFlowStat);
                                            } else {
                                                logger.error(
                                                        "Switch {} returned a null result possibility because the switch is not connected to the controller",
                                                        datapathIdString);
                                            }
                                        } catch (NoSwitchException e1) {
                                            // TODO Auto-generated catch block
                                            logger.error("Switch {} with ID {} is not connected aborting",
                                                    swd.getSwitchName(), datapathIdString);
                                        } catch (IOException e1) {
                                            logger.error("IOException {}", e1);

                                        } catch (InterruptedException e1) {
                                            logger.error("Thread Interrupted {}", e1);
                                            killThread();
                                        } catch (ExecutionException e1) {
                                            logger.error("Execution Exception {}", e1);
                                        } catch (TimeoutException e1) {
                                            logger.error("Switch Timeout Exception {}", e1);
                                            killThread();

                                        }

                                    } catch (Exception e) {
                                        logger.error("unchecked exception here {}", e);

                                        killThread();
                                        shutDown();
                                        Thread.yield();

                                    }

                                }

                                try {

                                    Thread.sleep(intervalTime);

                                } catch (InterruptedException e) {

                                    logger.error("{}", e);

                                    break;
                                }

                            }
                        } catch (Exception e) {
                            logger.error("exception in while {}", e);
                            shutDown();

                        }

                        try {
                            conn.close();
                        } catch (SQLException e) {
                            // TODO Auto-generated catch block
                            logger.error("{}", e);
                        }

                    } catch (Exception generalException) {
                        logger.error("General Exception throws {} ", generalException);

                    }
                }

                /**
                 * insert details into database, 3 tables will be populated: flow_stats, port_stats ,and port_status
                 * 
                 * @param datapathId
                 * @param portStats
                 * @param flowStats
                 * @param portStatus
                 * @param tempPortStatTransmitted
                 * @param tempPortStatReceived
                 * @param tempFlowStat
                 */
                private void storeSwitchDetails(long datapathId, String portStats, String flowStats,
                        String portStatus, HashMap<Long, Long> tempPortStatTransmitted,
                        HashMap<Long, Long> tempPortStatReceived, HashMap<String, Long> tempFlowStat) {

                    Object obj = JSONValue.parse(portStats);
                    JSONArray jsonArray = (JSONArray) obj;

                    for (int i = 0; i < jsonArray.size(); i++) {

                        JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                        long transmittedPackets = (Long) jsonObject.get("transmit_packets");
                        long receivedPackets = (Long) jsonObject.get("receive_packets");

                        long portId = (Long) jsonObject.get("port_id");

                        // logger.info("the port is {}", portId);
                        // logger.info("{} packets transmitted and {} packets received",
                        // receivedPackets,transmittedPackets);

                        PreparedStatement prep = null;
                        try {
                            prep = null;
                            if (conn != null) {
                                prep = conn.prepareStatement("insert into port_stats values (?,?,?,?,?);");

                            } else {

                                logger.error("no connection object instantiated aborting .. ");
                                return;
                            }

                            prep.setLong(1, datapathId);
                            prep.setLong(2, calendar.getTimeInMillis());

                            if (tempPortStatTransmitted.get(portId) != null) {

                                long currentTransmittedPackets = transmittedPackets
                                        - tempPortStatTransmitted.get(portId);

                                if (currentTransmittedPackets < 0) {

                                    prep.setLong(5, transmittedPackets);
                                } else {

                                    prep.setLong(5, currentTransmittedPackets);
                                }
                            } else {

                                prep.setLong(5, transmittedPackets);
                            }

                            tempPortStatTransmitted.put(portId, transmittedPackets);

                            // take care of port received

                            if (tempPortStatReceived.get(portId) != null) {

                                long currentReceivedPackets = receivedPackets
                                        - tempPortStatReceived.get(portId);

                                if (currentReceivedPackets < 0) {

                                    prep.setLong(4, receivedPackets);
                                } else {

                                    prep.setLong(4, currentReceivedPackets);
                                }
                            } else {

                                prep.setLong(4, receivedPackets);
                            }

                            tempPortStatReceived.put(portId, receivedPackets);

                            prep.setLong(3, portId);
                            prep.addBatch();

                            conn.setAutoCommit(false);
                            prep.executeBatch();
                            conn.setAutoCommit(true);
                        } catch (SQLRecoverableException sqlRecoverableException) {

                            logger.error("{}", sqlRecoverableException);
                            //exit function since there is a timeout
                            return;
                        } catch (SQLException e) {

                            logger.error("{}", e);
                        } finally {
                            if (prep != null) {
                                try {
                                    prep.close();
                                } catch (SQLException e) {
                                    // TODO Auto-generated catch block
                                    logger.error("{}", e);
                                }
                            }
                        }
                    }

                    Object flowJSONobj = JSONValue.parse(flowStats);
                    JSONArray flowJsonArray = (JSONArray) flowJSONobj;

                    for (int i = 0; i < flowJsonArray.size(); i++) {

                        JSONObject jsonObject = (JSONObject) flowJsonArray.get(i);
                        long packets = (Long) jsonObject.get("packet_count");
                        String matchString = (String) jsonObject.get("match");
                        String action = (String) jsonObject.get("actions");
                        long priority = (Long) jsonObject.get("priority");

                        PreparedStatement prep = null;

                        try {
                            prep = conn.prepareStatement("insert  into flow_stats values (?,?,?,?,?,?);");
                            String insertString = datapathId + "," + calendar.getTimeInMillis() + ","
                                    + matchString + "," + action;
                            logger.debug("flow_stat values to insert are {}", insertString);
                            prep.setLong(1, datapathId);
                            prep.setLong(2, calendar.getTimeInMillis());

                            if (tempFlowStat.get(matchString) != null) {

                                long packetsReceived = packets - tempFlowStat.get(matchString);

                                if (packetsReceived < 0) {

                                    prep.setLong(5, packets);
                                } else {

                                    prep.setLong(5, packetsReceived);
                                }
                            } else {

                                prep.setLong(5, packets);
                            }

                            tempFlowStat.put(matchString, packets);

                            prep.setString(3, matchString);
                            prep.setString(4, action);

                            prep.setShort(6, (short) priority);
                            prep.addBatch();

                            conn.setAutoCommit(false);
                            prep.executeBatch();
                            conn.setAutoCommit(true);
                        } catch (SQLException e) {
                            // TODO Auto-generated catch block
                            logger.error("error when insert flow {} in switch {}", matchString, datapathId);
                            logger.error("{}", e);
                        } finally {
                            if (prep != null) {
                                try {
                                    prep.close();
                                } catch (SQLException e) {
                                    // TODO Auto-generated catch block
                                    logger.error("{}", e);
                                }
                            }
                        }

                    }

                    Object portStatusJSONobj = JSONValue.parse(portStatus);
                    JSONArray portStatusJsonArray = (JSONArray) portStatusJSONobj;

                    for (int i = 0; i < portStatusJsonArray.size(); i++) {
                        byte portStatusValue = 0;
                        JSONObject jsonObject = (JSONObject) portStatusJsonArray.get(i);
                        long portId = (Long) jsonObject.get("port_id");
                        String portAddress = (String) jsonObject.get("port_address");
                        try {
                            portStatusValue = (byte) (Integer.parseInt(jsonObject.get("state").toString()) % 2);
                        } catch (NumberFormatException nfe) {
                            logger.error("{}", nfe);
                            continue;
                        }
                        PreparedStatement prep = null;
                        try {
                            prep = conn.prepareStatement("insert into port_status    values (?,?,?,?,?);");
                            prep.setLong(1, datapathId);
                            prep.setLong(2, calendar.getTimeInMillis());
                            prep.setLong(3, portId);

                            prep.setString(4, portAddress);

                            prep.setByte(5, portStatusValue);
                            prep.addBatch();

                            conn.setAutoCommit(false);
                            prep.executeBatch();

                            conn.setAutoCommit(true);
                        } catch (SQLException e) {
                            // TODO Auto-generated catch block
                            logger.error("{}", e);
                        } finally {
                            if (prep != null) {
                                try {
                                    prep.close();
                                } catch (SQLException e) {
                                    // TODO Auto-generated catch block
                                    logger.error("{}", e);
                                }
                            }
                        }

                    }

                }

            }, "Switch Stat Collector");
            statThread.start();

        }
    } catch (Exception e) {
        logger.error("general excecption thrown {}", e);
    }
}

From source file:com.netbase.insightapi.clientlib.InsightAPIQuery.java

/**
 * May be overridden to use a different JSON Parser than the one included in
 * this library.//from w w w  .j ava  2s.  c om
 */
public void parseResponseContent() {
    parsedContent = JSONValue.parse(responseContent);
}

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

private void registerWithOauthCode(final String code, final String state) {
    final String timestamp = "" + mWiz.getTimestamp();
    final String deviceId = mWiz.getDeviceId();
    final String registrationId = mWiz.getRegistrationId();
    final String installId = mWiz.getInstallationId();
    // Make call to Rogerthat
    final ProgressDialog progressDialog = UIUtils.showProgressDialog(OauthRegistrationActivity.this, null,
            getString(R.string.loading), true, false);
    final SafeRunnable showErrorDialog = new SafeRunnable() {
        @Override//  www  . j a v  a  2 s  .com
        protected void safeRun() throws Exception {
            T.UI();
            progressDialog.dismiss();
            UIUtils.showDialog(OauthRegistrationActivity.this, null, R.string.registration_error);
        }
    };

    runOnWorker(new SafeRunnable() {
        @Override
        protected void safeRun() throws Exception {
            T.REGISTRATION();
            String version = "3";
            String signature = SecurityUtils.sha256(version + " " + installId + " " + timestamp + " " + deviceId
                    + " " + registrationId + " " + code + state + CloudConstants.REGISTRATION_MAIN_SIGNATURE);

            HttpPost httppost = HTTPUtil.getHttpPost(mService,
                    CloudConstants.REGISTRATION_OAUTH_REGISTERED_URL);
            try {
                List<NameValuePair> nameValuePairs = HTTPUtil.getRegistrationFormParams(mService);
                nameValuePairs.add(new BasicNameValuePair("version", version));
                nameValuePairs.add(new BasicNameValuePair("registration_time", timestamp));
                nameValuePairs.add(new BasicNameValuePair("device_id", deviceId));
                nameValuePairs.add(new BasicNameValuePair("registration_id", registrationId));
                nameValuePairs.add(new BasicNameValuePair("signature", signature));
                nameValuePairs.add(new BasicNameValuePair("install_id", installId));
                nameValuePairs.add(new BasicNameValuePair("code", code));
                nameValuePairs.add(new BasicNameValuePair("state", state));
                nameValuePairs.add(new BasicNameValuePair("GCM_registration_id", getGCMRegistrationId()));

                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                HttpResponse response = mHttpClient.execute(httppost);

                int statusCode = response.getStatusLine().getStatusCode();
                HttpEntity entity = response.getEntity();

                if (entity == null) {
                    runOnUI(new SafeRunnable() {
                        @Override
                        protected void safeRun() throws Exception {
                            mErrorTextView.setText(R.string.registration_error);
                            showErrorDialog.run();
                        }
                    });
                    return;
                }

                @SuppressWarnings("unchecked")
                final Map<String, Object> responseMap = (Map<String, Object>) JSONValue
                        .parse(new InputStreamReader(entity.getContent()));

                if (statusCode != 200 || responseMap == null) {
                    if (statusCode == 500 && responseMap != null) {
                        final String errorMessage = (String) responseMap.get("error");
                        if (errorMessage != null) {
                            progressDialog.dismiss();
                            runOnUI(new SafeRunnable() {
                                @Override
                                protected void safeRun() throws Exception {
                                    T.UI();
                                    mErrorTextView.setText(errorMessage);
                                    UIUtils.showDialog(OauthRegistrationActivity.this, null, errorMessage);
                                }
                            });
                            return;
                        }
                    }
                    runOnUI(new SafeRunnable() {
                        @Override
                        protected void safeRun() throws Exception {
                            mErrorTextView.setText(R.string.registration_error);
                            showErrorDialog.run();
                        }
                    });
                    return;
                }

                Boolean hasDevices = (Boolean) responseMap.get("has_devices");
                final String email = (String) responseMap.get("email");
                if (hasDevices) {
                    final JSONArray deviceNames = (JSONArray) responseMap.get("device_names");
                    runOnUI(new SafeRunnable() {
                        @Override
                        protected void safeRun() throws Exception {
                            T.UI();
                            mErrorTextView.setText(R.string.authenticate_first);
                            progressDialog.dismiss();
                            mWiz.setEmail(email);
                            mWiz.setDeviceNames(deviceNames);
                            mWiz.proceedToNextPage();
                        }
                    });
                } else {
                    JSONObject account = (JSONObject) responseMap.get("account");
                    setAgeAndGenderSet((Boolean) responseMap.get("age_and_gender_set"));
                    final RegistrationInfo info = new RegistrationInfo(email,
                            new Credentials((String) account.get("account"), (String) account.get("password")));
                    runOnUI(new SafeRunnable() {
                        @Override
                        protected void safeRun() throws Exception {
                            T.UI();
                            mWiz.setEmail(email);
                            mWiz.save();
                            tryConnect(progressDialog, 1, getString(R.string.registration_establish_connection,
                                    email, getString(R.string.app_name)) + " ", info);
                        }
                    });
                }

            } catch (Exception e) {
                L.d(e);
                runOnUI(new SafeRunnable() {
                    @Override
                    protected void safeRun() throws Exception {
                        mErrorTextView.setText(R.string.registration_error);
                        showErrorDialog.run();
                    }
                });
            }
        }
    });
}

From source file:com.searchbox.collection.oppfin.TopicCollection.java

public ItemReader<JSONObject> topicReader() {
    return new ItemReader<JSONObject>() {

        String topicList = loadFromUrl(env.getProperty(TOPIC_LIST_URL, TOPIC_LIST_URL_DEFAULT));

        // Topic list is a json list and we are interested in topicData =>
        // Topics => all
        Object obj = JSONValue.parse(topicList);

        JSONObject jsonObject = (JSONObject) obj;
        JSONObject topicData = (JSONObject) jsonObject.get("topicData");
        JSONArray topics = (JSONArray) topicData.get("Topics");

        // loop array
        Iterator<JSONObject> iterator = topics.iterator();

        public JSONObject read() {
            if (iterator.hasNext()) {
                return iterator.next();
            }/*from   ww  w  .ja  va2 s. c om*/
            return null;
        }
    };
}

From source file:com.shuffle.mock.MockCoin.java

public static MockCoin fromJSON(Reader jsonObject) throws IllegalArgumentException {

    JSONObject json = null;/*  w w  w  .j  av a  2 s  .c o m*/
    JSONArray outputs = null;
    JSONArray transactions = null;
    try {
        json = (JSONObject) JSONValue.parse(jsonObject);
        if (json == null) {
            throw new IllegalArgumentException("could not parse json object.");
        }

        outputs = (JSONArray) json.get("outputs");
        if (outputs == null) {
            throw new IllegalArgumentException("Missing field \"outputs\".");
        }

        transactions = (JSONArray) json.get("transactions");
        if (transactions == null) {
            throw new IllegalArgumentException("Missing field \"transactions\".");
        }
    } catch (ClassCastException e) {
        throw new IllegalArgumentException("could not parse json object.");
    }

    MockCoin mock = new MockCoin();

    Map<Long, Output> outList = new HashMap<>();
    for (int i = 1; i <= outputs.size(); i++) {
        JSONObject o = null;
        try {
            o = (JSONObject) outputs.get(i - 1);
        } catch (ClassCastException e) {
            throw new IllegalArgumentException("Could not read " + outputs.get(i - 1) + " as json object.");
        }

        Object address = o.get("address");
        Long amount = (Long) o.get("amount");
        if (address == null) {
            throw new IllegalArgumentException("Output missing field \"address\".");
        }
        if (amount == null) {
            throw new IllegalArgumentException("Output missing field \"amount\".");
        }

        Output bo = null;
        if (address instanceof String) {
            bo = new Output(new MockAddress((String) address), amount);
        } else if (address instanceof Long) {
            bo = new Output(new MockAddress((Long) address), amount);
        } else {
            throw new IllegalArgumentException("Could not read " + address + " as address");
        }

        outList.put((long) i, bo);
        mock.blockchain.put(bo.address, bo);
    }

    for (Object t : transactions) {

        JSONObject trans = (JSONObject) t;
        JSONArray in = (JSONArray) trans.get("inputs");
        JSONArray out = (JSONArray) trans.get("outputs");
        List<Output> tout = new LinkedList<>();
        List<Output> tin = new LinkedList<>();

        for (Object i : in) {
            Output o = outList.get(i);
            if (o == null) {
                throw new IllegalArgumentException("Missing output " + o);
            }
            tin.add(outList.get(i));
        }

        for (Object i : out) {
            Output o = outList.get(i);
            if (o == null) {
                throw new IllegalArgumentException("Missing output " + o);
            }
            tout.add(outList.get(i));
        }

        MockTransaction tr;
        Long z = null;
        Object zz = trans.get("z");
        try {

            if (zz == null) {
                tr = new MockTransaction(tin, tout, mock);
            } else {
                z = (Long) zz;
                tr = new MockTransaction(tin, tout, z.intValue(), mock, new HashMap<Output, VerificationKey>());
            }
        } catch (ClassCastException e) {
            throw new IllegalArgumentException("Could not read z value " + zz + " as long.");
        }
    }

    return mock;
}

From source file:com.tremolosecurity.provisioning.core.providers.SugarCRM.java

private String sugarLogin() throws NoSuchAlgorithmException, Exception, UnsupportedEncodingException,
        IOException, ClientProtocolException {

    MessageDigest md = MessageDigest.getInstance("MD5");
    SugarLogin login = new SugarLogin();

    login.setUser_name(this.userName);
    login.setPassword(getHexString(md.digest(this.password.getBytes("UTF-8"))));

    UserAuth userAuth = new UserAuth();
    userAuth.setUser_auth(login);/*from w  w w .  ja  v  a  2  s.co  m*/

    Gson gson = new Gson();
    String jsonLogin = gson.toJson(userAuth);

    String respJSON = execJson(jsonLogin, "login");
    JSONObject jsonObj = (JSONObject) JSONValue.parse(respJSON);
    return jsonObj.get("id").toString();
}