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:me.neatmonster.spacertk.actions.ServerActions.java

/**
 * Restarts the server if it's emtpy//  w  w  w  .ja v a2  s  . c  om
 * @param save If the server should be saved before restarting
 * @return If successful
 */
@Action(aliases = { "restartIfEmpty", "restartServerIfEmpty" })
public boolean restartIfEmpty(final Boolean save) {
    final JSONArray players = (JSONArray) JSONValue.parse(Utilities.sendMethod("getPlayers", "[]"));
    if (players == null || players.size() == 0)
        RemoteToolkit.restart(save);
    return true;
}

From source file:com.happyblueduck.lembas.datastore.LembasEntity.java

private void readObject(java.io.ObjectInputStream in)
        throws IOException, ClassNotFoundException, UtilSerializeException {

    InputStreamReader isr = new InputStreamReader(in, "UTF8");
    JSONObject object = (JSONObject) JSONValue.parse(isr);
    LembasEntity shallow = (LembasEntity) LembasUtil.deserialize(object);
    this.copy(shallow);
    this.objectKey = shallow.objectKey;
    //logger.info("< deserializing "+this.getClassName() +":" + object.toJSONString());
}

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

/**
 * Get workspaces./* w ww  .j  a v a  2s .com*/
 * 
 * @return list of {@link Workspace}
 */
public List<Workspace> getWorkspaces() {
    Client client = prepareClient();
    WebResource webResource = client.resource(WORKSPACES);

    String response = webResource.get(String.class);
    JSONArray data = (JSONArray) JSONValue.parse(response);

    List<Workspace> workspaces = new ArrayList<Workspace>();
    if (data != null) {
        for (Object obj : data) {
            JSONObject entryObject = (JSONObject) obj;
            workspaces.add(new Workspace(entryObject.toJSONString()));
        }
    }
    return workspaces;
}

From source file:com.codelanx.playtime.update.UpdateHandler.java

/**
 * Gets the {@link JSONObject} from the CurseAPI of the newest project version.
 * /*from ww w  . ja va 2s.c o  m*/
 * @since 1.4.5
 * @version 1.4.5
 */
private void getJSON() {
    InputStream stream = null;
    InputStreamReader isr = null;
    BufferedReader reader = null;
    String json = null;
    try {
        URL call = new URL(this.VERSION_URL);
        stream = call.openStream();
        isr = new InputStreamReader(stream);
        reader = new BufferedReader(isr);
        json = reader.readLine();
    } catch (MalformedURLException ex) {
        plugin.getLogger().log(Level.SEVERE, "Error checking for an update", this.debug >= 3 ? ex : "");
        this.result = Result.ERROR_BADID;
        this.latest = null;
    } catch (IOException ex) {
        plugin.getLogger().log(Level.SEVERE, "Error checking for an update", this.debug >= 3 ? ex : "");
    } finally {
        try {
            if (stream != null) {
                stream.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (reader != null) {
                reader.close();
            }
        } catch (IOException ex) {
            this.plugin.getLogger().log(Level.SEVERE, "Error closing updater streams!",
                    this.debug >= 3 ? ex : "");
        }
    }
    if (json != null) {
        JSONArray arr = (JSONArray) JSONValue.parse(json);
        this.latest = (JSONObject) arr.get(arr.size() - 1);
    } else {
        this.latest = null;
    }
}

From source file:mml.handler.get.MMLGetMMLHandler.java

/**
 * Debug: Check that the corcode stil ranges do not go beyond text end
 * @param stil the stil markup as text// www.  j  av a 2  s . c om
 * @param text the text it refers to
 * @return true if it was OK, else false
 */
boolean verifyCorCode(String stil, String text) {
    JSONObject jObj = (JSONObject) JSONValue.parse(stil);
    JSONArray ranges = (JSONArray) jObj.get(JSONKeys.RANGES);
    int offset = 0;
    for (int i = 0; i < ranges.size(); i++) {
        JSONObject range = (JSONObject) ranges.get(i);
        offset += ((Number) range.get("reloff")).intValue();
        int len = ((Number) range.get("len")).intValue();
        if (offset + len > text.length())
            return false;
    }
    return true;
}

From source file:com.alvexcore.repo.masterdata.getConstraintWork.java

protected List<Map<String, String>> getRestJsonMasterData(NodeRef source) throws Exception {
    NodeService nodeService = serviceRegistry.getNodeService();
    String urlStr = (String) nodeService.getProperty(source, AlvexContentModel.PROP_MASTER_DATA_REST_URL);
    String rootPath = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_JSON_ROOT_QUERY);
    String labelField = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_JSON_LABEL_FIELD);
    String valueField = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_JSON_VALUE_FIELD);
    String caching = (String) nodeService.getProperty(source,
            AlvexContentModel.PROP_MASTER_DATA_REST_CACHE_MODE);

    URL url = new URL(urlStr);
    URLConnection conn = url.openConnection();
    InputStream inputStream = conn.getInputStream();
    String str = IOUtils.toString(inputStream);

    Object jsonObj = JSONValue.parse(str);

    List<Map<String, String>> res = new ArrayList<Map<String, String>>();
    if (jsonObj.getClass().equals(JSONArray.class)) {
        JSONArray arr = (JSONArray) jsonObj;
        for (int k = 0; k < arr.size(); k++) {
            JSONObject item = (JSONObject) arr.get(k);
            String value = item.get(valueField).toString();
            String label = item.get(labelField).toString();
            HashMap<String, String> resItem = new HashMap<String, String>();
            resItem.put("ref", "");
            resItem.put("value", value);
            resItem.put("label", label);
            res.add(resItem);//  w ww  . j  a v  a2  s. c o  m
        }
    }

    return res;
}

From source file:io.tempra.AppServer.java

public static String getProperty(String string) {
    // TODO Auto-generated method stub
    try {// w ww  .j av a  2 s .c om
        // sample to handle params on a json string on a system properties
        String s = System.getenv("VERSATILE.CONFIG");
        org.json.simple.JSONObject json = (JSONObject) JSONValue.parse(s);

        return (String) json.get(string).toString();
    } catch (Exception e) {
        InputStream in = AppServer.class.getResourceAsStream("/properties.json");
        org.json.simple.JSONObject json = null;
        try {
            String s = convertStreamToString(in);
            json = (JSONObject) JSONValue.parse(s);
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        return (String) json.get(string);
    }

}

From source file:ch.sourcepond.maven.release.scm.git.GitRepository.java

@Override
public ProposedTag fromRef(final Ref gitTag) throws SCMException {
    notNull(gitTag, "gitTag");

    final RevWalk walk = new RevWalk(getGit().getRepository());
    final ObjectId tagId = gitTag.getObjectId();
    JSONObject message;//from www  . jav a2  s. c o m
    try {
        final RevTag tag = walk.parseTag(tagId);
        message = (JSONObject) JSONValue.parse(tag.getFullMessage());
    } catch (final IOException e) {
        throw new SCMException(e,
                "Error while looking up tag because RevTag could not be parsed! Object-id was %s", tagId);
    } finally {
        walk.dispose();
    }
    if (message == null) {
        message = new JSONObject();
        message.put(VERSION, "0");
        message.put(BUILD_NUMBER, "0");
    }
    return new GitProposedTag(getGit(), log, gitTag, stripRefPrefix(gitTag.getName()), message,
            config.getRemoteUrlOrNull());
}

From source file:net.emotivecloud.scheduler.drp4ost.DRP4OST.java

/**
 * Creates a VM on OpenStack with the information received from the *.ovf
 * content received attached to the POST request. Returns an OVF with the VM
 * launched//  w  w w .j  a  v  a2  s .  co  m
 *
 * @param ovfXml
 * @return String containin an OVF input with the VM instance ID
 * @throws DRPOSTException
 */
@POST
@Path("/compute")
@Consumes("application/xml")
@Produces("application/xml")
public String createCompute(String ovfXml) throws DRPOSTException {

    HashMap<String, String> hmap = new HashMap<String, String>();

    String vmName = null;
    String vmID = null;

    System.out.println("**********************************************");
    System.out.println("**********************************************");
    System.out.println("**********************************************");
    System.out.println("THE OVF: \n" + ovfXml);
    System.out.println("**********************************************");
    System.out.println("**********************************************");
    System.out.println("**********************************************");

    //(0) Parse the info from the *.ovf
    if (ovfXml == null) {
        throw new DRPOSTException("\nFailed createCompute method!!\n." + "\nThe ovf xml is" + ovfXml
                + "\n.Please enter correct xml ovf and try again.\n", StatusCodes.BAD_OVF);
    }
    OVFWrapper ovf;
    try {
        ovf = parse(ovfXml);
    } catch (DRPOSTException e) {
        // This one is expectet to be thrown, and should pass unchanged
        throw e;
    } catch (Exception e) {
        throw new DRPOSTException("\nFailed createCompute method!!\n"
                + "An error occured to parse ovfXml.\n The parse of ovfxml is " + e.getCause()
                + "\n.Please enter correct xml ovf anf try again.\n", StatusCodes.BAD_OVF);

    }
    EmotiveOVF emotiveOvf = new EmotiveOVF(ovf);
    List<SectionType> sections = OVFAux.findSections(emotiveOvf.getOVFEnvelope().getSection(),
            ProductSectionType.class);
    ProductSectionType ps = null;
    for (SectionType s : sections) {
        if (s instanceof ProductSectionType
                && ((ProductSectionType) s).getClazz().equals(OVFWrapper.class.getName())) {
            ps = (ProductSectionType) s;
            break;

        }
    }
    if (ps != null) {
        List cop = ps.getCategoryOrProperty();
        ProductSectionType.Property propertyToRemove = null;
        for (Object prop : cop) {
            if (prop instanceof ProductSectionType.Property) {
                ProductSectionType.Property p = (ProductSectionType.Property) prop;
                hmap.put(p.getKey(), p.getValueAttribute());
            }
        }
    }

    //(1) we must create an Image for the VM

    //(1.1) Merge ISO & QCOW2
    Collection<OVFDisk> tmpDisks = ovf.getDisks().values();
    OVFDisk oDisks[] = tmpDisks.toArray(new OVFDisk[tmpDisks.size()]);
    String baseImageID = emotiveOvf.getBaseImage();
    String pathLocalIso = null;
    String pathLocalBaseImage = null;
    OVFDisk baseDisk = null;
    boolean isoFound = false;
    boolean baseFound = false;

    String name = emotiveOvf.getId();

    for (OVFDisk disk : oDisks) {

        String path = disk.getHref();

        System.out.println("DRP4OST>createCompute()Disk info- disk.getId()=" + disk.getId()
                + ", disk.getHref()=" + disk.getHref());
        System.out.println("DRP4OST>createCompute()Disk info- disk.getHref()=" + disk.getHref());

        if (path.trim().endsWith(".iso")) {
            pathLocalIso = this.tmpPath + getFileNameFromPath(path);
            downloadImage(path, pathLocalIso);
            isoFound = true;
            System.out.println("DRP4OST>createCompute()Found ISO to merge isoPath=" + pathLocalIso);
        } else if (path.contains(baseImageID)) {
            pathLocalBaseImage = this.tmpPath + getFileNameFromPath(path);
            downloadImage(path, pathLocalBaseImage);
            baseDisk = disk;
            baseFound = true;
            System.out.println(
                    "DRP4OST>createCompute()Found baseImage to merge baseImagePath=" + pathLocalBaseImage);
        } else {
            // if not base, and not iso, leave the images
            System.out.println(
                    "DRP4OST>createCompute(), This disk will be ignored (suposed to use just QCOW2 and ISO)");
        }
    }

    // Verify that merge is possible
    if (isoFound && baseFound) {
        ImageMerge.merge(pathLocalIso, pathLocalBaseImage);
    } else {
        System.out.println("DRP4OST>createCompute() -> ISO or BASE missing: isoFound=" + isoFound
                + ", baseFound=" + baseFound);
    }

    //(1.2) Create the baseImage at the OpenStack repository (if iso found, it has been merged)
    if (!existsImage(getFileNameFromPath(baseDisk.getHref()))) {
        baseImageID = createImage(baseDisk, pathLocalBaseImage);
    } else {
        System.out.println("DRP4OST>CREATE IMAGE: NO (ALREADY exist), baseDisk.getId()=" + baseDisk.getId());
        //TODO: get image ID
    }

    //Remove the downloaded images, after merged and uploaded to OpenStack
    FileUtils.deleteQuietly(new File(pathLocalBaseImage));
    FileUtils.deleteQuietly(new File(pathLocalIso));

    //(2) we must create a flavor for the VM
    String flavorID = createFlavor(emotiveOvf);

    //(3) we must create VM with Flavor & Image created at sections (1)&(2)
    vmName = ovf.getId(); // + "_" + (new Random()).nextInt(99999999);

    String host = emotiveOvf.getProductProperty(EmotiveOVF.PROPERTYNAME_DESTINATION_HOST);

    if (host != null) {
        String response = oStackClient.createVM(flavorID, baseImageID, vmName, host);
        // Parsing the JSON response to get the flavor ID
        JSONObject jo = (JSONObject) JSONValue.parse(response);
        jo = (JSONObject) jo.get("server");
        vmID = jo.get("id").toString();
    } else {
        String response = oStackClient.createVM(flavorID, baseImageID, vmName);
        JSONObject jo = (JSONObject) JSONValue.parse(response);
        jo = (JSONObject) jo.get("server");
        vmID = jo.get("id").toString();
    }
    System.out.println("DRP4OST>DRP4OST.createImage(), VM created vmID=" + vmID);

    // get the network properties
    //        Collection<OVFNetwork> tmpNets = ovf.getNetworks().values();
    //        OVFNetwork nets[] = tmpNets.toArray(new OVFNetwork[tmpNets.size()]);

    //        public OVFNetwork(String connectionName, String ip, String mac, String netmask, String gateway)
    OVFNetwork nets[] = this.getNetworks(vmID);

    // Create the ovf
    String xx = OVFWrapperFactory.create(vmID, ovf.getCPUsNumber(), ovf.getMemoryMB(), oDisks, nets, hmap)
            .toCleanString();

    return xx;
}

From source file:fr.bmartel.protocol.google.oauth.device.CalendarNotifManager.java

public void requestToken(final IRequestTokenListener requestTokenListener) {

    if (oauthRegistration == null) {
        System.err.println("Error oauth registration not proceeded");
        requestTokenListener.onRequestTokenError("oauth registration must be proccessed before");
        return;/*ww  w  . jav  a  2 s.c  o  m*/
    }

    String method = "POST";
    String uri = GoogleConst.GOOGLE_TOKEN;

    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
    headers.put("Host", GoogleConst.GOOGLE_ACCOUNT_HOST);
    headers.put("Accept", "*/*");
    headers.put("Accept-Encoding", "gzip, deflate, compress");

    String body = "client_id=" + clientId + "&" + "client_secret=" + clientSecret + "&" + "code="
            + oauthRegistration.getDeviceCode() + "&" + "grant_type=http://oauth.net/grant_type/device/1.0";

    HttpFrame frame = new HttpFrame(method, new HttpVersion(1, 1), headers, uri, new ListOfBytes(body));

    ClientSocket clientSocket = new ClientSocket(GoogleConst.GOOGLE_ACCOUNT_HOST, 443);

    // set SSL encryption
    clientSocket.setSsl(true);

    clientSocket.checkCertificate(false);

    clientSocket.addClientSocketEventListener(new IHttpClientListener() {

        @Override
        public void onIncomingHttpFrame(HttpFrame frame, HttpStates httpStates, IClientSocket clientSocket) {

            if (httpStates == HttpStates.HTTP_FRAME_OK && frame.isHttpResponseFrame()) {

                Object obj = JSONValue.parse(new String(frame.getBody().getBytes()));

                try {
                    JSONObject mainObject = (JSONObject) obj;
                    if (mainObject.containsKey("error")) {
                        System.err.println("request token error. Retry later ...");
                        String description = "";
                        if (mainObject.containsKey("error_description")) {
                            description = mainObject.get("error_description").toString();
                        }
                        requestTokenListener.onRequestTokenError(description);
                    } else {
                        if (mainObject.containsKey("access_token") == true
                                && mainObject.containsKey("token_type") == true
                                && mainObject.containsKey("expires_in") == true) {

                            currentToken = new OauthToken(mainObject.get("access_token").toString(),
                                    mainObject.get("token_type").toString(),
                                    Integer.parseInt(mainObject.get("expires_in").toString()));

                            requestTokenListener.onRequestTokenReceived(currentToken);

                            return;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {

                System.err.println("Error occured while requesting token");
            }
            requestTokenListener.onRequestTokenError("");
        }
    });
    clientSocket.write(frame.toString().getBytes());
}