Example usage for org.json JSONTokener JSONTokener

List of usage examples for org.json JSONTokener JSONTokener

Introduction

In this page you can find the example usage for org.json JSONTokener JSONTokener.

Prototype

public JSONTokener(String s) 

Source Link

Document

Construct a JSONTokener from a string.

Usage

From source file:org.wso2.iot.agent.proxy.APIController.java

private boolean isJSONObject(String data) {
    Object json;//from  w  ww  .  j ava  2s  .  c o m
    try {
        json = new JSONTokener(data).nextValue();
        return (json instanceof JSONObject);
    } catch (JSONException e) {
        Log.e(TAG, "Failed to parse response JSON", e);
        return false;
    }
}

From source file:org.araqne.docxcod.test.DocxTest.java

@Test
public void totalTest() throws IOException, JSONException {
    File targetDir = new File(".test/_totalTest");
    File saveFile = new File(".test/totalTest-save.docx");
    saveFile.delete();//  w  ww.  j ava 2s .c  om
    targetDir.mkdirs();
    // tearDownHelper.add(targetDir);

    OOXMLPackage docx = new OOXMLPackage();
    docx.load(getClass().getResourceAsStream("/totalTest.docx"), targetDir);
    docx.setOutputStream(new FileOutputStream(saveFile));

    InputStreamReader inputReader = new InputStreamReader(getClass().getResourceAsStream("/totalTest.in"),
            Charset.forName("utf-8"));
    JSONTokener tokener = new JSONTokener(inputReader);
    Map<String, Object> rootMap = JsonHelper.parse((JSONObject) tokener.nextValue());

    docx.apply(new MergeFieldParser(), rootMap);
    docx.apply(new DirectivePlacerProcessor(), rootMap);
    docx.apply(new ChartDirectiveParser(), rootMap);
    docx.apply(new MagicNodeUnwrapper("word/document.xml"), rootMap);
    docx.apply(new FreeMarkerRunner("word/document.xml"), rootMap);

    docx.setDebug(true);
    docx.close();
    // tearDownHelper.add(saveFile);
}

From source file:org.araqne.docxcod.test.DocxTest.java

@Test
public void arbitraryTableTest() throws IOException, JSONException {
    File targetDir = new File(".test/_abtrTableTest");
    File saveFile = new File(".test/abtrTableTest-save.docx");
    saveFile.delete();//from w w  w.  j  a  va2s .  c  o  m
    targetDir.mkdirs();
    // tearDownHelper.add(targetDir);

    OOXMLPackage docx = new OOXMLPackage();
    docx.load(getClass().getResourceAsStream("/abtrTableTest.docx"), targetDir);
    docx.setOutputStream(new FileOutputStream(saveFile));

    InputStreamReader inputReader = new InputStreamReader(getClass().getResourceAsStream("/abtrTableTest.in"),
            Charset.forName("utf-8"));
    JSONTokener tokener = new JSONTokener(inputReader);
    Map<String, Object> rootMap = JsonHelper.parse((JSONObject) tokener.nextValue());

    List<OOXMLProcessor> processors = new ArrayList<OOXMLProcessor>();
    docx.apply(new MergeFieldParser(), rootMap);
    docx.apply(new DirectivePlacerProcessor(), rootMap);
    docx.apply(new AbtrTableDirectiveParser(), rootMap);
    docx.apply(new ChartDirectiveParser(), rootMap);
    docx.apply(new MagicNodeUnwrapper("word/document.xml"), rootMap);
    docx.apply(new FreeMarkerRunner("word/document.xml"), rootMap);

    docx.close();
    // tearDownHelper.add(saveFile);
}

From source file:org.araqne.docxcod.test.DocxTest.java

@Test
public void chartTest() throws IOException, JSONException {
    File targetDir = new File(".test/_chartTest");
    File saveFile = new File(".test/chartTest-save.docx");
    targetDir.mkdirs();//from  w ww  .j a  v a2  s .  co  m
    saveFile.delete();
    // tearDownHelper.add(targetDir);

    OOXMLPackage docx = new OOXMLPackage();
    docx.load(getClass().getResourceAsStream("/chartTest.docx"), targetDir);
    docx.setOutputStream(new FileOutputStream(saveFile));

    InputStreamReader inputReader = new InputStreamReader(getClass().getResourceAsStream("/nestedListTest.in"));
    JSONTokener tokener = new JSONTokener(inputReader);
    Map<String, Object> rootMap = JsonHelper.parse((JSONObject) tokener.nextValue());

    List<OOXMLProcessor> processors = new ArrayList<OOXMLProcessor>();
    processors.add(new MergeFieldParser());
    processors.add(new DirectivePlacerProcessor());
    processors.add(new ChartDirectiveParser());
    //      processors.add(new ImgDirectiveParser());
    processors.add(new MagicNodeUnwrapper("word/document.xml"));
    processors.add(new FreeMarkerRunner("word/document.xml"));

    docx.apply(processors, rootMap);

    docx.setDebug(true);
    docx.close();
}

From source file:org.araqne.docxcod.test.DocxTest.java

@Test
public void mainTest() throws IOException, JSONException {
    File targetDir = new File(".test/mainTest");
    File saveFile = new File(".test/mainTest-save.docx");
    saveFile.delete();//w w w.j a  v a2  s.  c om
    targetDir.mkdirs();

    OOXMLPackage docx = new OOXMLPackage();
    docx.load(getClass().getResourceAsStream("/nestedList2.docx"), targetDir);
    docx.setOutputStream(new FileOutputStream(saveFile));
    docx.setDebug(true);

    InputStreamReader inputReader = new InputStreamReader(getClass().getResourceAsStream("/nestedListTest.in"));
    JSONTokener tokener = new JSONTokener(inputReader);
    Map<String, Object> rootMap = JsonHelper.parse((JSONObject) tokener.nextValue());

    List<OOXMLProcessor> processors = new ArrayList<OOXMLProcessor>();
    processors.add(new MergeFieldParser());
    processors.add(new DirectivePlacerProcessor());
    processors.add(new MagicNodeUnwrapper("word/document.xml"));
    processors.add(new FreeMarkerRunner("word/document.xml"));

    docx.apply(processors, rootMap);

    docx.setDebug(true);
    docx.close();
}

From source file:my.home.lehome.receiver.LocalMessageReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(LOCAL_MSG_RECEIVER_ACTION)) {
        if (PrefUtil.getbooleanValue(context, MainActivityPresenter.APP_EXIT_KEY, false)) {
            Log.d(TAG, "app set exit. ignore network state change.");
            return;
        }//from   ww  w . j a  v a2s.c  o  m
        String lm = intent.getStringExtra(LOCAL_MSG_REP_KEY);
        Log.d(TAG, "receive local msg: " + lm);
        if (lm != null) {
            JSONTokener jsonParser = new JSONTokener(lm);
            String type = "";
            String msg = "";
            String err_msg = "";
            int seq = -1;
            try {
                JSONObject cmdObject = (JSONObject) jsonParser.nextValue();
                type = cmdObject.getString("type");
                msg = cmdObject.getString("msg");
                seq = cmdObject.getInt("seq");
                if (MessageHelper.enqueueMsgSeq(context, seq))
                    return;
            } catch (JSONException e) {
                e.printStackTrace();
                err_msg = context.getString(R.string.msg_push_msg_format_error);
            } catch (Exception e) {
                e.printStackTrace();
                err_msg = context.getString(R.string.msg_push_msg_format_error);
            }

            if (!TextUtils.isEmpty(err_msg)) {
                MessageHelper.sendToast(err_msg);
                return;
            }

            if (type.equals("req_loc") || type.equals("req_geo")) {
                LocationHelper.enqueueLocationRequest(context, seq, type, msg);
                return;
            } else if (Arrays.asList(MessageHelper.NORMAIL_FILTER_TAG_LIST).contains(type)) {
                MessageHelper.inNormalState = true;
            } else if (type.equals("toast")) {
                MessageHelper.sendToast(msg);
                return;
            } else {
                MessageHelper.inNormalState = false;
            }
            MessageHelper.sendServerMsgToList(seq, type, msg, context);
        }
    }
}

From source file:info.axbase.app.VersionInfo.java

public static VersionInfo parse(String text) throws JSONException {
    JSONTokener jsonParser = new JSONTokener(text);
    JSONObject msg = (JSONObject) jsonParser.nextValue();
    if (msg == null) {
        return null;
    }//from ww w . ja va  2s .  com
    if (msg.optInt("error") == 0) {
        JSONObject data = msg.optJSONObject("data");
        if (data == null) {
            return null;
        }

        VersionInfo versionInfo = new VersionInfo();
        versionInfo.fileName = data.optString("fileName");
        versionInfo.whatsNew = data.optString("whatsNew");
        versionInfo.fileTime = data.optLong("fileTime");
        versionInfo.fileSize = data.optLong("fileSize");
        versionInfo.appProject = data.optString("appProject");
        versionInfo.digest = data.optString("digest");
        versionInfo.version = data.optString("version");
        return versionInfo;
    } else {
        Log.e("ParseError", msg.optString("msg"));
        return null;
    }
}

From source file:org.springsource.ide.eclipse.commons.ui.tips.TipProvider.java

public void refresh() {
    error = null;/*from www .j  a  v a 2 s .  co m*/
    InputStreamReader tipReader = new InputStreamReader(TipProvider.class.getClassLoader()
            .getResourceAsStream("org/springsource/ide/eclipse/commons/ui/tips/spring_tool_tips.json"));
    JSONTokener tokener = new JSONTokener(tipReader);
    List<TipInfo> tipList = Collections.emptyList();
    try {
        JSONArray json = new JSONArray(tokener);
        int length = json.length();
        tipList = new ArrayList<TipInfo>(length);
        for (int i = 0; i < length; i++) {
            JSONObject object = (JSONObject) json.get(i);
            if (object.has("required")) {
                String requiredPlugin = object.getString("required");
                if (Platform.getBundle(requiredPlugin) == null) {
                    continue;
                }
            }
            tipList.add(new TipInfo(object.getString("infoText"), object.getString("linkText"),
                    object.has("keyBindingId") ? object.getString("keyBindingId") : null));
        }
    } catch (JSONException e) {
        CorePlugin.log("Error parsing tips of the day file", e);
        error = e;
    }

    if (tipList.size() == 0) {
        tips = new TipInfo[] { new TipInfo("There's a lot going on with Spring",
                "Read the latest <a href\"http://spring.io/blog\">Spring news</a>.") };
    } else {
        tips = tipList.toArray(new TipInfo[tipList.size()]);
    }

    pointer = RAND.nextInt(tips.length);
}

From source file:my.home.lehome.receiver.RemoteMessageReceiver.java

public void onMessage(Context context, String message) {
    if (PrefUtil.getbooleanValue(context, MainActivityPresenter.APP_EXIT_KEY, false)) {
        Log.d(TAG, "app set exit. ignore network state change.");
        return;//from   www .j  a  va  2  s .  c  o m
    }

    JSONTokener jsonParser = new JSONTokener(message);
    String type = "";
    String msg = "";
    String err_msg = "";
    int seq = -1;
    try {
        JSONObject cmdObject = (JSONObject) jsonParser.nextValue();
        type = cmdObject.getString("type");
        msg = cmdObject.getString("msg");
        seq = cmdObject.getInt("seq");
        if (MessageHelper.enqueueMsgSeq(context, seq))
            return;
    } catch (JSONException e) {
        e.printStackTrace();
        err_msg = context.getString(R.string.msg_push_msg_format_error);
    } catch (Exception e) {
        e.printStackTrace();
        err_msg = context.getString(R.string.msg_push_msg_format_error);
    }

    if (!TextUtils.isEmpty(err_msg)) {
        MessageHelper.sendToast(err_msg);
        return;
    }

    if (type.equals("req_loc") || type.equals("req_geo")) {
        LocationHelper.enqueueLocationRequest(context, seq, type, msg);
        return;
    } else if (Arrays.asList(MessageHelper.NORMAIL_FILTER_TAG_LIST).contains(type)) {
        MessageHelper.inNormalState = true;
    } else if (type.equals("toast")) {
        MessageHelper.sendToast(msg);
        return;
    } else {
        MessageHelper.inNormalState = false;
    }
    MessageHelper.sendServerMsgToList(seq, type, msg, context);
}

From source file:org.zaizi.alfresco.redlink.service.search.solr.SensefySolrQueryHTTPClient.java

public ResultSet executeQuery(SearchParameters searchParameters)// , String language)
{
    if (repositoryState.isBootstrapping()) {
        throw new AlfrescoRuntimeException(
                "SOLR queries can not be executed while the repository is bootstrapping");
    }//from   w ww . j  a v a  2s.c o  m

    try {
        if (searchParameters.getStores().size() == 0) {
            throw new AlfrescoRuntimeException("No store for query");
        }

        URLCodec encoder = new URLCodec();
        StringBuilder url = new StringBuilder();
        url.append(sensefySearchEndpoint);

        // Send the query
        url.append("?query=");
        url.append(encoder.encode(searchParameters.getQuery(), "UTF-8"));
        // url.append("?wt=").append(encoder.encode("json", "UTF-8"));
        url.append("&fields=").append(encoder.encode("DBID,score", "UTF-8"));

        // Emulate old limiting behaviour and metadata
        final LimitBy limitBy;
        int maxResults = -1;
        if (searchParameters.getMaxItems() >= 0) {
            maxResults = searchParameters.getMaxItems();
            limitBy = LimitBy.FINAL_SIZE;
        } else if (searchParameters.getLimitBy() == LimitBy.FINAL_SIZE && searchParameters.getLimit() >= 0) {
            maxResults = searchParameters.getLimit();
            limitBy = LimitBy.FINAL_SIZE;
        } else {
            maxResults = searchParameters.getMaxPermissionChecks();
            if (maxResults < 0) {
                maxResults = maximumResultsFromUnlimitedQuery;
            }
            limitBy = LimitBy.NUMBER_OF_PERMISSION_EVALUATIONS;
        }
        url.append("&rows=").append(String.valueOf(maxResults));

        // url.append("&df=").append(encoder.encode(searchParameters.getDefaultFieldName(), "UTF-8"));
        url.append("&start=").append(encoder.encode("" + searchParameters.getSkipCount(), "UTF-8"));

        // Locale locale = I18NUtil.getLocale();
        // if (searchParameters.getLocales().size() > 0)
        // {
        // locale = searchParameters.getLocales().get(0);
        // }
        // url.append("&locale=");
        // url.append(encoder.encode(locale.toString(), "UTF-8"));

        StringBuffer sortBuffer = new StringBuffer();
        for (SortDefinition sortDefinition : searchParameters.getSortDefinitions()) {
            if (sortBuffer.length() == 0) {
                sortBuffer.append("&sort=");
            } else {
                sortBuffer.append(encoder.encode(", ", "UTF-8"));
            }
            sortBuffer.append(encoder.encode(sortDefinition.getField(), "UTF-8"))
                    .append(encoder.encode(" ", "UTF-8"));
            if (sortDefinition.isAscending()) {
                sortBuffer.append(encoder.encode("asc", "UTF-8"));
            } else {
                sortBuffer.append(encoder.encode("desc", "UTF-8"));
            }

        }
        url.append(sortBuffer);

        if (searchParameters.getFieldFacets().size() > 0) {
            for (FieldFacet facet : searchParameters.getFieldFacets()) {
                url.append("&facet=").append(encoder.encode(facet.getField(), "UTF-8"));
            }
        }
        // end of field factes

        // add current username doing the request for permissions
        url.append("&userName=").append(encoder.encode(AuthenticationUtil.getRunAsUser(), "UTF-8"));

        GetMethod get = new GetMethod(url.toString());

        try {
            httpClient.executeMethod(get);

            if (get.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY
                    || get.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
                Header locationHeader = get.getResponseHeader("location");
                if (locationHeader != null) {
                    String redirectLocation = locationHeader.getValue();
                    get.setURI(new URI(redirectLocation, true));
                    httpClient.executeMethod(get);
                }
            }

            if (get.getStatusCode() != HttpServletResponse.SC_OK) {
                throw new LuceneQueryParserException(
                        "Request failed " + get.getStatusCode() + " " + url.toString());
            }

            Reader reader = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream()));
            // TODO - replace with streaming-based solution e.g. SimpleJSON ContentHandler
            JSONObject json = new JSONObject(new JSONTokener(reader));
            SensefySolrJSONResultSet results = new SensefySolrJSONResultSet(json, searchParameters, nodeService,
                    nodeDAO, limitBy, maxResults);
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Sent :" + url);
                s_logger.debug("Got: " + results.getNumberFound() + " in " + results.getQueryTime() + " ms");
            }

            return results;
        } finally {
            get.releaseConnection();
        }
    } catch (UnsupportedEncodingException e) {
        throw new LuceneQueryParserException("", e);
    } catch (HttpException e) {
        throw new LuceneQueryParserException("", e);
    } catch (IOException e) {
        throw new LuceneQueryParserException("", e);
    } catch (JSONException e) {
        throw new LuceneQueryParserException("", e);
    }
}