Example usage for org.json.simple JSONObject toString

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

Introduction

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

Prototype

@Override
    public String toString() 

Source Link

Usage

From source file:org.mozilla.android.sync.SyncCryptographer.java

public CryptoStatusBundle generateCryptoKeysWBOPayload() {

    // Generate the keys and save for later use
    KeyBundle cryptoKeys = Cryptographer.generateKeys();
    setKeys(Base64.encodeBase64String(cryptoKeys.getEncryptionKey()),
            Base64.encodeBase64String(cryptoKeys.getHmacKey()));

    // Generate json
    JSONArray keysArray = new JSONArray();
    Utils.asAList(keysArray).add(new String(Base64.encodeBase64(cryptoKeys.getEncryptionKey())));
    Utils.asAList(keysArray).add(new String(Base64.encodeBase64(cryptoKeys.getHmacKey())));
    JSONObject json = new JSONObject();
    Utils.asMap(json).put(KEY_ID, ID_CRYPTO_KEYS);
    Utils.asMap(json).put(KEY_COLLECTION, CRYPTO_KEYS_COLLECTION);
    Utils.asMap(json).put(KEY_COLLECTIONS, "{}");
    Utils.asMap(json).put(KEY_DEFAULT_COLLECTION, keysArray);

    // Get the keys to encrypt the crypto keys bundle
    KeyBundle cryptoKeysBundleKeys;/*from  w  ww .  j  av  a  2 s .  c  om*/
    try {
        cryptoKeysBundleKeys = getCryptoKeysBundleKeys();
    } catch (Exception e) {
        return new CryptoStatusBundle(CryptoStatus.MISSING_SYNCKEY_OR_USER, "");
    }

    return encrypt(json.toString(), cryptoKeysBundleKeys);
}

From source file:org.mozilla.android.sync.SyncCryptographer.java

private String createJSONBundle(CryptoInfo info) {
    JSONObject json = new JSONObject();
    Utils.asMap(json).put(KEY_CIPHER_TEXT, new String(Base64.encodeBase64(info.getMessage())));
    Utils.asMap(json).put(KEY_HMAC, Utils.byte2hex(info.getHmac()));
    Utils.asMap(json).put(KEY_IV, new String(Base64.encodeBase64(info.getIv())));
    return json.toString();
}

From source file:org.myperl.MathService.java

@POST
@Path("/")
@Produces(MediaType.APPLICATION_JSON)//from w w  w  .j a  va 2s  .c o m
@Consumes(MediaType.APPLICATION_JSON)
public String post(String payload) throws ScriptException, ParseException {
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject = (JSONObject) jsonParser.parse(payload);
    String expression = (String) jsonObject.get("exper");
    ScriptEngine engine = manager.getEngineByName("nashorn");
    JSONObject result = new JSONObject();
    result.put("result", engine.eval(expression).toString());
    return result.toString();
}

From source file:org.opencastproject.adminui.endpoint.AbstractEventEndpoint.java

@GET
@Path("{eventId}/access.json")
@SuppressWarnings("unchecked")
@Produces(MediaType.APPLICATION_JSON)//from   ww w . j  a v  a  2s.c o  m
@RestQuery(name = "getEventAccessInformation", description = "Get the access information of an event", returnDescription = "The access information", pathParameters = {
        @RestParameter(name = "eventId", isRequired = true, description = "The event identifier", type = RestParameter.Type.STRING) }, reponses = {
                @RestResponse(responseCode = SC_BAD_REQUEST, description = "The required form params were missing in the request."),
                @RestResponse(responseCode = SC_NOT_FOUND, description = "If the event has not been found."),
                @RestResponse(responseCode = SC_OK, description = "The access information ") })
public Response getEventAccessInformation(@PathParam("eventId") String eventId) throws Exception {
    Opt<Event> optEvent = getEvent(eventId);
    if (optEvent.isNone())
        return notFound("Cannot find an event with id '%s'.", eventId);

    // Add all available ACLs to the response
    JSONArray systemAclsJson = new JSONArray();
    List<ManagedAcl> acls = getAclService().getAcls();
    for (ManagedAcl acl : acls) {
        systemAclsJson.add(AccessInformationUtil.serializeManagedAcl(acl));
    }

    // Get the episode ACL
    final TransitionQuery q = TransitionQuery.query().withId(eventId).withScope(AclScope.Episode);
    List<EpisodeACLTransition> episodeTransistions;
    JSONArray transitionsJson = new JSONArray();
    try {
        episodeTransistions = getAclService().getTransitions(q).getEpisodeTransistions();
        for (EpisodeACLTransition trans : episodeTransistions) {
            transitionsJson.add(AccessInformationUtil.serializeEpisodeACLTransition(trans));
        }
    } catch (AclServiceException e) {
        logger.error(
                "There was an error while trying to get the ACL transitions for series '{}' from the ACL service: {}",
                eventId, ExceptionUtils.getStackTrace(e));
        return RestUtil.R.serverError();
    }

    AccessControlList activeAcl = new AccessControlList();
    try {
        activeAcl = AccessControlParser.parseAcl(optEvent.get().getAccessPolicy());
    } catch (Exception e) {
        logger.error("Unable to parse access policy because: {}", ExceptionUtils.getStackTrace(e));
    }
    Option<ManagedAcl> currentAcl = AccessInformationUtil.matchAcls(acls, activeAcl);

    JSONObject episodeAccessJson = new JSONObject();
    episodeAccessJson.put("current_acl", currentAcl.isSome() ? currentAcl.get().getId() : 0L);
    episodeAccessJson.put("acl", AccessControlParser.toJsonSilent(activeAcl));
    episodeAccessJson.put("privileges", AccessInformationUtil.serializePrivilegesByRole(activeAcl));
    episodeAccessJson.put("transitions", transitionsJson);
    if (StringUtils.isNotBlank(optEvent.get().getWorkflowState())
            && WorkflowUtil.isActive(WorkflowState.valueOf(optEvent.get().getWorkflowState())))
        episodeAccessJson.put("locked", true);

    JSONObject jsonReturnObj = new JSONObject();
    jsonReturnObj.put("episode_access", episodeAccessJson);
    jsonReturnObj.put("system_acls", systemAclsJson);

    return Response.ok(jsonReturnObj.toString()).build();
}

From source file:org.opencastproject.adminui.endpoint.SeriesEndpoint.java

@GET
@Path("{seriesId}/access.json")
@SuppressWarnings("unchecked")
@Produces(MediaType.APPLICATION_JSON)//  w w w  . ja  v a  2 s  . c o  m
@RestQuery(name = "getseriesaccessinformation", description = "Get the access information of a series", returnDescription = "The access information", pathParameters = {
        @RestParameter(name = "seriesId", isRequired = true, description = "The series identifier", type = Type.STRING) }, reponses = {
                @RestResponse(responseCode = SC_BAD_REQUEST, description = "The required form params were missing in the request."),
                @RestResponse(responseCode = SC_NOT_FOUND, description = "If the series has not been found."),
                @RestResponse(responseCode = SC_OK, description = "The access information ") })
public Response getSeriesAccessInformation(@PathParam("seriesId") String seriesId) throws NotFoundException {
    if (StringUtils.isBlank(seriesId))
        return RestUtil.R.badRequest("Path parameter series ID is missing");

    boolean hasProcessingEvents = hasProcessingEvents(seriesId);

    // Add all available ACLs to the response
    JSONArray systemAclsJson = new JSONArray();
    List<ManagedAcl> acls = getAclService().getAcls();
    for (ManagedAcl acl : acls) {
        systemAclsJson.add(AccessInformationUtil.serializeManagedAcl(acl));
    }

    final TransitionQuery q = TransitionQuery.query().withId(seriesId).withScope(AclScope.Series);
    List<SeriesACLTransition> seriesTransistions;
    JSONArray transitionsJson = new JSONArray();
    try {
        seriesTransistions = getAclService().getTransitions(q).getSeriesTransistions();
        for (SeriesACLTransition trans : seriesTransistions) {
            transitionsJson.add(AccessInformationUtil.serializeSeriesACLTransition(trans));
        }
    } catch (AclServiceException e) {
        logger.error(
                "There was an error while trying to get the ACL transitions for serie '{}' from the ACL service: {}",
                seriesId, e);
        return RestUtil.R.serverError();
    }

    JSONObject seriesAccessJson = new JSONObject();
    try {
        AccessControlList seriesAccessControl = seriesService.getSeriesAccessControl(seriesId);
        Option<ManagedAcl> currentAcl = AccessInformationUtil.matchAcls(acls, seriesAccessControl);
        seriesAccessJson.put("current_acl", currentAcl.isSome() ? currentAcl.get().getId() : 0);
        seriesAccessJson.put("privileges",
                AccessInformationUtil.serializePrivilegesByRole(seriesAccessControl));
        seriesAccessJson.put("acl", AccessControlParser.toJsonSilent(seriesAccessControl));
        seriesAccessJson.put("transitions", transitionsJson);
        seriesAccessJson.put("locked", hasProcessingEvents);
    } catch (SeriesException e) {
        logger.error("Unable to get ACL from series {}: {}", seriesId, ExceptionUtils.getStackTrace(e));
        return RestUtil.R.serverError();
    }

    JSONObject jsonReturnObj = new JSONObject();
    jsonReturnObj.put("system_acls", systemAclsJson);
    jsonReturnObj.put("series_access", seriesAccessJson);

    return Response.ok(jsonReturnObj.toString()).build();
}

From source file:org.opencastproject.adminui.endpoint.ServerEndpoint.java

@GET
@Path("servers.json")
@Produces(MediaType.APPLICATION_JSON)//from w w  w. jav a  2 s  .  com
@RestQuery(description = "Returns the list of servers", name = "servers", restParameters = {
        @RestParameter(name = "limit", description = "The maximum number of items to return per page", isRequired = false, type = INTEGER),
        @RestParameter(name = "offset", description = "The offset", isRequired = false, type = INTEGER),
        @RestParameter(name = "online", isRequired = false, description = "Filter results by server current online status", type = BOOLEAN),
        @RestParameter(name = "offline", isRequired = false, description = "Filter results by server current offline status", type = BOOLEAN),
        @RestParameter(name = "maintenance", isRequired = false, description = "Filter results by server current maintenance status", type = BOOLEAN),
        @RestParameter(name = "q", isRequired = false, description = "Filter results by free text query", type = STRING),
        @RestParameter(name = "types", isRequired = false, description = "Filter results by sevices types registred on the server", type = STRING),
        @RestParameter(name = "ipaddress", isRequired = false, description = "Filter results by the server ip address", type = STRING),
        @RestParameter(name = "cores", isRequired = false, description = "Filter results by the number of cores", type = INTEGER, defaultValue = "-1"),
        @RestParameter(name = "memory", isRequired = false, description = "Filter results by the server memory available in bytes", type = INTEGER),
        @RestParameter(name = "path", isRequired = false, description = "Filter results by the server path", type = STRING),
        @RestParameter(name = "maxjobs", isRequired = false, description = "Filter results by the maximum of jobs that can be run at the same time", type = INTEGER, defaultValue = "-1"),
        @RestParameter(name = "sort", isRequired = false, description = "The sort order.  May include any "
                + "of the following: STATUS, NAME, CORES, COMPLETED (jobs), RUNNING (jobs), QUEUED (jobs), QUEUETIME (mean for jobs), MAINTENANCE, RUNTIME (mean for jobs)."
                + "Add '_DESC' to reverse the sort order (e.g. NAME_DESC).", type = STRING) }, reponses = {
                        @RestResponse(description = "Returns the list of jobs from Matterhorn", responseCode = HttpServletResponse.SC_OK) }, returnDescription = "The list ")
public Response getServers(@QueryParam("limit") final int limit, @QueryParam("offset") final int offset,
        @QueryParam("online") boolean fOnline, @QueryParam("offline") boolean fOffline,
        @QueryParam("q") String fText, @QueryParam("maintenance") boolean fMaintenance,
        @QueryParam("types") List<String> fTypes, @QueryParam("ipaddress") String ipAddress,
        @QueryParam("cores") Integer fCores, @QueryParam("memory") Integer fMemory,
        @QueryParam("path") String fPath, @QueryParam("maxjobs") int fMaxJobs, @QueryParam("sort") String sort,
        @Context HttpHeaders headers) throws Exception {

    JSONArray jsonList = new JSONArray();
    List<HostRegistration> allServers = serviceRegistry.getHostRegistrations();
    List<JSONObject> sortedServers = new ArrayList<JSONObject>();

    int i = 0;
    for (HostRegistration server : allServers) {
        if (i++ < offset) {
            continue;
        } else if (limit != 0 && sortedServers.size() == limit) {
            break;
        } else {

            // Get all the services statistics pro host
            // TODO improve the service registry to get service statistics by host
            List<ServiceStatistics> servicesStatistics = serviceRegistry.getServiceStatistics();
            int jobsCompleted = 0;
            int jobsRunning = 0;
            int jobsQueued = 0;
            int sumMeanRuntime = 0;
            int sumMeanQueueTime = 0;
            int totalServiceOnHost = 0;
            Set<String> serviceTypes = new HashSet<String>();
            for (ServiceStatistics serviceStat : servicesStatistics) {
                if (server.getBaseUrl().equals(serviceStat.getServiceRegistration().getHost())) {
                    totalServiceOnHost++;
                    jobsCompleted += serviceStat.getFinishedJobs();
                    jobsRunning += serviceStat.getRunningJobs();
                    jobsQueued += serviceStat.getQueuedJobs();
                    sumMeanRuntime += serviceStat.getMeanRunTime();
                    sumMeanQueueTime += serviceStat.getQueuedJobs();
                    serviceTypes.add(serviceStat.getServiceRegistration().getServiceType());
                }
            }
            int meanRuntime = sumMeanRuntime / totalServiceOnHost;
            int meanQueueTime = sumMeanQueueTime / totalServiceOnHost;

            boolean vOnline = server.isOnline();
            boolean vMaintenance = server.isMaintenanceMode();
            String vName = server.getBaseUrl();
            int vCores = server.getCores();
            int vRunning = jobsRunning;
            int vQueued = jobsQueued;
            int vCompleted = jobsCompleted;

            if (fOffline && vOnline)
                continue;
            if (fOnline && !vOnline)
                continue;
            if (fMaintenance && !vMaintenance)
                continue;
            if (fMaxJobs > 0 && fMaxJobs < (vRunning + vQueued + vCompleted))
                continue;
            if (fCores != null && fCores > 0 && fCores != vCores)
                continue;
            if (fMemory != null && fMemory > 0 && ((Integer) fMemory).longValue() != server.getMemory())
                continue;
            if (StringUtils.isNotBlank(fPath) && !vName.toLowerCase().contains(fPath.toLowerCase()))
                continue;
            if (StringUtils.isNotBlank(fText) && !vName.toLowerCase().contains(fText.toLowerCase())) {
                String allString = vName.toLowerCase().concat(server.getIpAddress().toLowerCase());
                if (!allString.contains(fText.toLowerCase()))
                    continue;
            }

            JSONObject jsonServer = new JSONObject();
            jsonServer.put(KEY_ONLINE, server.isOnline());
            jsonServer.put(KEY_MAINTENANCE, server.isMaintenanceMode());
            jsonServer.put(KEY_NAME, server.getBaseUrl());
            jsonServer.put(KEY_CORES, server.getCores());
            jsonServer.put(KEY_RUNNING, jobsRunning);
            jsonServer.put(KEY_QUEUED, jobsQueued);
            jsonServer.put(KEY_COMPLETED, jobsCompleted);
            jsonServer.put(KEY_MEAN_RUN_TIME, meanRuntime);
            jsonServer.put(KEY_MEAN_QUEUE_TIME, meanQueueTime);
            sortedServers.add(jsonServer);
        }
    }

    // Sorting
    SORT sortKey = SORT.HOSTNAME;
    Boolean ascending = true;
    if (StringUtils.isNotBlank(sort)) {
        // Parse the sort field and direction
        Sort sortField = null;
        if (sort.endsWith(DESCENDING_SUFFIX)) {
            ascending = false;
            String enumKey = sort.substring(0, sort.length() - DESCENDING_SUFFIX.length()).toUpperCase();
            try {
                sortKey = SORT.valueOf(enumKey);
            } catch (IllegalArgumentException e) {
                logger.warn("No sort enum matches '{}'", enumKey);
            }
        } else {
            try {
                sortKey = SORT.valueOf(sort);
            } catch (IllegalArgumentException e) {
                logger.warn("No sort enum matches '{}'", sort);
            }
        }
    }
    Collections.sort(sortedServers, new ServerComparator(sortKey, ascending));

    jsonList.addAll(sortedServers);

    JSONObject response = new JSONObject();
    response.put("results", jsonList);
    response.put("count", jsonList.size());
    response.put("offset", offset);
    response.put("limit", limit);
    response.put("total", allServers.size());

    return Response.ok(response.toString()).build();
}

From source file:org.opendaylight.openflowplugin.pyretic.ODLHandlerSimpleImpl.java

public synchronized void onPacketReceived(PacketReceived notification) {
    //LOG.debug("-----New packet arrived");

    byte[] etherType = PacketUtils.extractEtherType(notification.getPayload());
    byte[] dstMacRaw = PacketUtils.extractDstMac(notification.getPayload());
    byte[] srcMacRaw = PacketUtils.extractSrcMac(notification.getPayload());

    MacAddress dstMac = PacketUtils.rawMacToMac(dstMacRaw);
    MacAddress srcMac = PacketUtils.rawMacToMac(srcMacRaw);

    /* LOG.debug("srcmac init");
     LOG.debug(srcMac.getValue());//from  w  w w  . jav  a  2  s .c om
     LOG.debug("dstmac init");
     LOG.debug(dstMac.getValue());*/

    NodeConnectorKey ingressKey = InstanceIdentifierUtils
            .getNodeConnectorKey(notification.getIngress().getValue());
    String path = ingressKey.getId().getValue();

    String[] msg = null;
    String switch_s = null;
    String inport = null;
    if (path.contains(":")) {
        msg = path.split(":");
        switch_s = msg[1];
        inport = msg[2];

        List<Integer> raw = new ArrayList<Integer>();
        for (byte b : notification.getPayload()) {
            int aux = (int) b;
            if (aux < 0) {
                aux = 256 + aux;
            }
            raw.add(aux);
        }

        /*LOG.debug("Ethertype: " ); // + etherType.toString());
        for(int i = 0; i < etherType.length; i++) {
        LOG.debug("%02x ",0xff & etherType[i]);
        }
        LOG.debug("");*/

        if (Arrays.equals(ETH_TYPE_IPV4, etherType)) {
            //LOG.debug("IPV4 packet arrived");

            JSONObject json = new JSONObject();
            json.put("switch", Integer.parseInt(switch_s));
            json.put("inport", Integer.parseInt(inport));
            json.put("raw", raw);

            List<String> p = new ArrayList<String>();
            p.add("\"packet\"");
            p.add(json.toString());
            // LOG.debug("" + p);

            this.channel.push(p.toString() + "\n");
            //mac2portMapping.put(srcMac, notification.getIngress());
        } else if (Arrays.equals(ETH_TYPE_IPV6, etherType)) {
            // Handle IPV6 packet
            JSONObject json = new JSONObject();

            json.put("switch", Integer.parseInt(switch_s));
            json.put("inport", Integer.parseInt(inport));
            json.put("raw", raw);

            List<String> p = new ArrayList<String>();
            p.add("\"packet\"");
            p.add(json.toString());
            // LOG.debug("" + p);
            this.channel.push(p.toString() + "\n");
            //mac2portMapping.put(srcMac, notification.getIngress());
        } else if (Arrays.equals(ETH_TYPE_ARP, etherType)) {
            // Handle ARP packet
            // LOG.debug("ARP packet arrived");
            JSONObject json = new JSONObject();

            json.put("switch", Integer.parseInt(switch_s));
            json.put("inport", Integer.parseInt(inport));
            json.put("raw", raw);

            List<String> p = new ArrayList<String>();
            p.add("\"packet\"");
            p.add(json.toString());

            this.channel.push(p.toString() + "\n");
            mac2portMapping.put(srcMac, notification.getIngress());

        } else if (Arrays.equals(ETH_TYPE_LLDP, etherType)) {
            //Handle lldp packet
            //LOG.debug("LLDP packet arrived");

            JSONObject json = new JSONObject();

            json.put("switch", Integer.parseInt(switch_s));
            json.put("inport", Integer.parseInt(inport));
            json.put("raw", raw);

            List<String> p = new ArrayList<String>();
            p.add("\"packet\"");
            p.add(json.toString());
            this.channel.push(p.toString() + "\n");

            mac2portMapping.put(srcMac, notification.getIngress());
        } else {
            LOG.debug("Unknown packet arrived.\nThis shouldn't be happening");
        }
    } else {
        throw new IllegalArgumentException("String " + path + " does not contain -");
    }
}

From source file:org.opensolaris.opengrok.web.JSONSearchServlet.java

@SuppressWarnings({ "unchecked", "deprecation" })
@Override/*from w  ww .  j a va2s.c  o m*/
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    JSONObject result = new JSONObject();
    SearchEngine engine = new SearchEngine();

    boolean valid = false;

    String freetext = req.getParameter(PARAM_FREETEXT);
    String def = req.getParameter(PARAM_DEF);
    String symbol = req.getParameter(PARAM_SYMBOL);
    String path = req.getParameter(PARAM_PATH);
    String hist = req.getParameter(PARAM_HIST);

    if (freetext != null) {
        freetext = URLDecoder.decode(freetext);
        engine.setFreetext(freetext);
        valid = true;
        result.put(PARAM_FREETEXT, freetext);
    }

    if (def != null) {
        def = URLDecoder.decode(def);
        engine.setDefinition(def);
        valid = true;
        result.put(PARAM_DEF, def);
    }

    if (symbol != null) {
        symbol = URLDecoder.decode(symbol);
        engine.setSymbol(symbol);
        valid = true;
        result.put(PARAM_SYMBOL, symbol);
    }

    if (path != null) {
        path = URLDecoder.decode(path);
        engine.setFile(path);
        valid = true;
        result.put(PARAM_PATH, path);
    }

    if (hist != null) {
        hist = URLDecoder.decode(hist);
        engine.setHistory(hist);
        valid = true;
        result.put(PARAM_HIST, hist);
    }

    if (valid) {
        long start = System.currentTimeMillis();

        int numResults = engine.search();
        int maxResults = MAX_RESULTS;
        String maxResultsParam = req.getParameter(PARAM_MAXRESULTS);
        if (maxResultsParam != null) {
            try {
                maxResults = Integer.parseInt(maxResultsParam);
                result.put(PARAM_MAXRESULTS, maxResults);
            } catch (NumberFormatException ex) {
            }
        }
        List<Hit> results = new ArrayList<>(maxResults);
        engine.results(0, numResults > maxResults ? maxResults : numResults, results);
        JSONArray resultsArray = new JSONArray();
        for (Hit hit : results) {
            JSONObject hitJson = new JSONObject();
            hitJson.put(ATTRIBUTE_DIRECTORY, JSONObject.escape(hit.getDirectory()));
            hitJson.put(ATTRIBUTE_FILENAME, JSONObject.escape(hit.getFilename()));
            hitJson.put(ATTRIBUTE_LINENO, hit.getLineno());
            hitJson.put(ATTRIBUTE_LINE, conv.encode(hit.getLine()));
            hitJson.put(ATTRIBUTE_PATH, hit.getPath());
            resultsArray.add(hitJson);
        }

        long duration = System.currentTimeMillis() - start;

        result.put(ATTRIBUTE_DURATION, duration);
        result.put(ATTRIBUTE_RESULT_COUNT, results.size());

        result.put(ATTRIBUTE_RESULTS, resultsArray);
    }
    resp.getWriter().write(result.toString());
}

From source file:org.openstack.storlet.common.StorletObjectOutputStream.java

@SuppressWarnings("unchecked")
public void setMetadata(Map<String, String> md) throws StorletException {
    JSONObject jobj = new JSONObject();
    Iterator<Map.Entry<String, String>> it = md.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next();
        jobj.put((String) pairs.getKey(), (String) pairs.getValue());
        it.remove();//from  w w  w . j a va  2s  . c  o  m
    }
    try {
        MetadataStream_.write(jobj.toString().getBytes());
    } catch (IOException e) {
        throw new StorletException("Failed to set metadata " + e.toString());
    } finally {
        closeMD();
    }
}

From source file:org.planetcrypto.bitcoin.PlanetCryptoBitcoinMinerAPICommands.java

@SuppressWarnings("unchecked")
public String parseArgs(String _ip, String _port, String command, Boolean json_response) {
    JSONObject json = new JSONObject();
    String ip = new String();
    String port = new String();
    if (command.length() > 0 && command.trim().length() > 0) {
        String cmd = command.trim();
        int len = cmd.length();
        String param_sep = "|";
        if (cmd.toLowerCase().contains(param_sep)) {
            //System.out.println("Specific command detected, parting string for parameters");
            String _cmd = cmd.substring(0, cmd.indexOf("|"));
            String _parameters = cmd.substring(cmd.indexOf("|") + 1, len);
            json.put("parameter", _parameters);
            json.put("command", _cmd);

        } else {/* w  w w  . ja v  a 2s.c  om*/
            //System.out.println("Setting command to: " + cmd);
            json.put("command", cmd);
        }
    }
    if (_ip.length() > 1 && _ip.trim().length() > 0) {
        //System.out.println("Setting IP to: " + ip.trim());
        ip = _ip.trim();
    }
    if (_port.length() > 2 && _port.trim().length() > 0) {
        //System.out.println("Setting port to: " + ip.trim());
        port = _port.trim();
    }
    try {
        if (json_response) {
            //System.out.println("Sending: " + json.toString());
            String result = API(json.toString(), ip, port);
            return result;
        } else {
            String result = API(command, ip, port);
            return result;
        }
    } catch (Exception ex) {
        Logger.getLogger(PlanetCryptoBitcoin.class.getName()).log(Level.SEVERE, null, ex);
        return "fail";
    }
}