Example usage for org.json.simple.parser JSONParser parse

List of usage examples for org.json.simple.parser JSONParser parse

Introduction

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

Prototype

public void parse(Reader in, ContentHandler contentHandler) throws IOException, ParseException 

Source Link

Usage

From source file:TestBufferStreamGenomicsDBImporter.java

/**
 * Sample driver code for testing Java VariantContext write API for GenomicsDB
 * The code shows two ways of using the API
 *   (a) Iterator<VariantContext>// w ww.j  av a  2s.  co  m
 *   (b) Directly adding VariantContext objects
 * If "-iterators" is passed as the second argument, method (a) is used.
 */
public static void main(final String[] args) throws IOException, GenomicsDBException, ParseException {
    if (args.length < 2) {
        System.err.println("For loading: [-iterators] <loader.json> "
                + "<stream_name_to_file.json> [bufferCapacity rank lbRowIdx ubRowIdx useMultiChromosomeIterator]");
        System.exit(-1);
    }
    int argsLoaderFileIdx = 0;
    if (args[0].equals("-iterators"))
        argsLoaderFileIdx = 1;
    //Buffer capacity
    long bufferCapacity = (args.length >= argsLoaderFileIdx + 3) ? Integer.parseInt(args[argsLoaderFileIdx + 2])
            : 1024;
    //Specify rank (or partition idx) of this process
    int rank = (args.length >= argsLoaderFileIdx + 4) ? Integer.parseInt(args[argsLoaderFileIdx + 3]) : 0;
    //Specify smallest row idx from which to start loading.
    // This is useful for incremental loading into existing array
    long lbRowIdx = (args.length >= argsLoaderFileIdx + 5) ? Long.parseLong(args[argsLoaderFileIdx + 4]) : 0;
    //Specify largest row idx up to which loading should be performed - for completeness
    long ubRowIdx = (args.length >= argsLoaderFileIdx + 6) ? Long.parseLong(args[argsLoaderFileIdx + 5])
            : Long.MAX_VALUE - 1;
    //Boolean to use MultipleChromosomeIterator
    boolean useMultiChromosomeIterator = (args.length >= argsLoaderFileIdx + 7)
            ? Boolean.parseBoolean(args[argsLoaderFileIdx + 6])
            : false;
    //<loader.json> first arg
    String loaderJSONFile = args[argsLoaderFileIdx];
    GenomicsDBImporter loader = new GenomicsDBImporter(loaderJSONFile, rank, lbRowIdx, ubRowIdx);
    //<stream_name_to_file.json> - useful for the driver only
    //JSON file that contains "stream_name": "vcf_file_path" entries
    FileReader mappingReader = new FileReader(args[argsLoaderFileIdx + 1]);
    JSONParser parser = new JSONParser();
    LinkedHashMap streamNameToFileName = (LinkedHashMap) parser.parse(mappingReader, new LinkedHashFactory());
    ArrayList<VCFFileStreamInfo> streamInfoVec = new ArrayList<VCFFileStreamInfo>();
    long rowIdx = 0;
    for (Object currObj : streamNameToFileName.entrySet()) {
        Map.Entry<String, String> entry = (Map.Entry<String, String>) currObj;
        VCFFileStreamInfo currInfo = new VCFFileStreamInfo(entry.getValue(), loaderJSONFile, rank,
                useMultiChromosomeIterator);

        /** The following 2 lines are not mandatory - use initializeSampleInfoMapFromHeader()
         * iff you know for sure that sample names in the VCF header are globally unique
         * across all streams/files. If not, you have 2 options:
         *   (a) specify your own mapping from sample index in the header to SampleInfo object
         *       (unique_name, rowIdx) OR
         *   (b) specify the mapping in the callset_mapping_file (JSON) and pass null to
         *       addSortedVariantContextIterator()
         */
        LinkedHashMap<Integer, GenomicsDBImporter.SampleInfo> sampleIndexToInfo = new LinkedHashMap<Integer, GenomicsDBImporter.SampleInfo>();
        rowIdx = GenomicsDBImporter.initializeSampleInfoMapFromHeader(sampleIndexToInfo, currInfo.mVCFHeader,
                rowIdx);
        int streamIdx = -1;
        if (args[0].equals("-iterators"))
            streamIdx = loader.addSortedVariantContextIterator(entry.getKey(), currInfo.mVCFHeader,
                    currInfo.mIterator, bufferCapacity, VariantContextWriterBuilder.OutputType.BCF_STREAM,
                    sampleIndexToInfo); //pass sorted VC iterators
        else
            //use buffers - VCs will be provided by caller
            streamIdx = loader.addBufferStream(entry.getKey(), currInfo.mVCFHeader, bufferCapacity,
                    VariantContextWriterBuilder.OutputType.BCF_STREAM, sampleIndexToInfo);
        currInfo.mStreamIdx = streamIdx;
        streamInfoVec.add(currInfo);
    }
    if (args[0].equals("-iterators")) {
        //Much simpler interface if using Iterator<VariantContext>
        loader.importBatch();
        assert loader.isDone();
    } else {
        //Must be called after all iterators/streams added - no more iterators/streams
        // can be added once this function is called
        loader.setupGenomicsDBImporter();
        //Counts and tracks buffer streams for which new data must be supplied
        //Initialized to all the buffer streams
        int numExhaustedBufferStreams = streamInfoVec.size();
        int[] exhaustedBufferStreamIdxs = new int[numExhaustedBufferStreams];
        for (int i = 0; i < numExhaustedBufferStreams; ++i)
            exhaustedBufferStreamIdxs[i] = i;
        while (!loader.isDone()) {
            //Add data for streams that were exhausted in the previous round
            for (int i = 0; i < numExhaustedBufferStreams; ++i) {
                VCFFileStreamInfo currInfo = streamInfoVec.get(exhaustedBufferStreamIdxs[i]);
                boolean added = true;
                while (added && (currInfo.mIterator.hasNext() || currInfo.mNextVC != null)) {
                    if (currInfo.mNextVC != null)
                        added = loader.add(currInfo.mNextVC, currInfo.mStreamIdx);
                    if (added)
                        if (currInfo.mIterator.hasNext())
                            currInfo.mNextVC = currInfo.mIterator.next();
                        else
                            currInfo.mNextVC = null;
                }
            }
            loader.importBatch();
            numExhaustedBufferStreams = (int) loader.getNumExhaustedBufferStreams();
            for (int i = 0; i < numExhaustedBufferStreams; ++i)
                exhaustedBufferStreamIdxs[i] = loader.getExhaustedBufferStreamIndex(i);
        }
    }
}

From source file:com.hunchee.haystack.server.JSONHelper.java

public static Map<String, Object> parseJson(String jsonText) throws ParseException {
    Map<String, Object> json = null;
    org.json.simple.parser.JSONParser parser = new org.json.simple.parser.JSONParser();
    ContainerFactory containerFactory = new ContainerFactory() {
        public List creatArrayContainer() {
            return new LinkedList();
        }/* w  w w  .j  av  a 2  s .co m*/

        public Map createObjectContainer() {
            return new LinkedHashMap();
        }
    };
    json = (Map<String, Object>) parser.parse(jsonText, containerFactory);
    Iterator iter = json.entrySet().iterator();
    LOG.info("==iterate result==");
    while (iter.hasNext()) {
        Map.Entry entry = (Map.Entry) iter.next();
        LOG.info(entry.getKey() + "=>" + entry.getValue());
    }
    LOG.info("==toJSONString()==");
    LOG.info(org.json.simple.JSONValue.toJSONString(json));
    return json;
}

From source file:com.textquo.dreamcode.server.JSONHelper.java

public static Map<String, Object> parseJson(String jsonText) {
    Map<String, Object> json = null;
    try {//  w  w w. j av a  2 s .c  om
        org.json.simple.parser.JSONParser parser = new org.json.simple.parser.JSONParser();
        ContainerFactory containerFactory = new ContainerFactory() {
            public List creatArrayContainer() {
                return new LinkedList();
            }

            public Map createObjectContainer() {
                return new LinkedHashMap();
            }
        };
        json = (Map<String, Object>) parser.parse(jsonText, containerFactory);
        Iterator iter = json.entrySet().iterator();
        LOG.info("==iterate result==");
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            LOG.info(entry.getKey() + "=>" + entry.getValue());
        }
        LOG.info("==toJSONString()==");
        LOG.info(org.json.simple.JSONValue.toJSONString(json));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return json;
}

From source file:org.exoplatform.social.client.core.util.SocialJSONDecodingSupport.java

/**
 * Parse JSON text into java Map object from the input source.
 *  // w  ww. j  av  a 2s  .  c o  m
 * @param jsonContent Json content which you need to create the Model
 * @throws ParseException Throw this exception if any
 */
public static Map parser(String jsonContent) throws ParseException {
    JSONParser parser = new JSONParser();
    ContainerFactory containerFactory = new ContainerFactory() {
        public List creatArrayContainer() {
            return new LinkedList();
        }

        public Map createObjectContainer() {
            return new LinkedHashMap();
        }
    };
    return (Map) parser.parse(jsonContent, containerFactory);
}

From source file:com.turt2live.xmail.api.Attachments.java

/**
 * Attempts to get an attachment from a JSON string. This will throw an IllegalArgumentException if
 * the json string is null or invalid./*  www.  j  a va 2s  .c o  m*/
 *
 * @param json the JSON string
 *
 * @return the attachment, or an UnknownAttachment if no match
 */
@SuppressWarnings("unchecked")
public static Attachment getAttachment(String json) {
    if (json == null) {
        throw new IllegalArgumentException();
    }
    JSONParser parser = new JSONParser();
    ContainerFactory containerFactory = new ContainerFactory() {
        @Override
        public List<Object> creatArrayContainer() {
            return new LinkedList<Object>();
        }

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

    };

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

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

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

        map = (Map<String, Object>) json1;
    } catch (ParseException e) {
        e.printStackTrace();
        return null;
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        return null;
    }
    XMail plugin = XMail.getInstance();
    Attachment a = plugin.getMailServer().attemptAttachmentDecode(map);
    if (a != null) {
        return a;
    }
    a = plugin.getAttachmentHandlerRegistry().getAttachmentFromHandler(json);
    return a == null ? new UnknownAttachment(json) : a;
}

From source file:org.exoplatform.social.client.core.util.SocialJSONDecodingSupport.java

/**
 * Parse JSON text into java Model object from the input source.
 * and then it's base on the class type.
 * //  w  w w.j a va  2  s.  com
 * @param <T> Generic type must extend from Model.
 * @param clazz Class type.
 * @param jsonContent Json content which you need to create the Model
 * @throws ParseException Throw this exception if any
 * 
 */
public static <T extends Model> T parser(final Class<T> clazz, String jsonContent) throws ParseException {
    JSONParser parser = new JSONParser();
    ContainerFactory containerFactory = new ContainerFactory() {
        public List<T> creatArrayContainer() {
            return new LinkedList<T>();
        }

        public T createObjectContainer() {
            try {
                return clazz.newInstance();
            } catch (InstantiationException e) {
                return null;
            } catch (IllegalAccessException e) {
                return null;
            }
        }
    };
    return (T) parser.parse(jsonContent, containerFactory);
}

From source file:com.turt2live.xmail.mail.attachment.MailMessageAttachment.java

@SuppressWarnings("unchecked")
public static MailMessageAttachment deserializeFromJson(String content) {
    JSONParser parser = new JSONParser();
    ContainerFactory containerFactory = new ContainerFactory() {
        @Override/* w  w  w.j  a  va2s  .  com*/
        public List<Object> creatArrayContainer() {
            return new LinkedList<Object>();
        }

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

    };

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

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

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

        map = (Map<String, Object>) json;
    } catch (ParseException e) {
        e.printStackTrace();
        return null;
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        return null;
    }
    Mail mail = Mail.fromJSON(map);
    MessageAttachmentType type = MessageAttachmentType.OTHER;
    if (mail != null) {
        Object obj = map.get("message_type");
        if (obj instanceof String) {
            String typestr = (String) obj;
            type = MessageAttachmentType.fromString(typestr);
        }
    }
    return new MailMessageAttachment(mail, type);
}

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

/**
 * Turn the json input string into a HashMap
 * @param input/*from  w  w w .j av a 2s  .c  om*/
 * @return
 */
public static HashMap jsonDecode(String input) {

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

    HashMap result = new HashMap();

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

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

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

    return result;
}

From source file:com.turt2live.xmail.mail.attachment.ItemAttachment.java

@SuppressWarnings("unchecked")
public static ItemAttachment deserializeFromJson(String content) {
    JSONParser parser = new JSONParser();
    ContainerFactory containerFactory = new ContainerFactory() {
        @Override/*from w  w  w.  j  a va  2  s  .  c om*/
        public List<Object> creatArrayContainer() {
            return new LinkedList<Object>();
        }

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

    };

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

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

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

        keys = (Map<String, Object>) json;
    } catch (ParseException e) {
        e.printStackTrace();
        return new ItemAttachment(new ItemStack(Material.GRASS, 1));
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        return new ItemAttachment(new ItemStack(Material.GRASS, 1));
    }

    // Repair Gson thinking int == double
    if (keys.get("amount") != null) {
        Double d = (Double) keys.get("amount");
        Integer i = d.intValue();
        keys.put("amount", i);
    }

    ItemStack item = null;
    try {
        item = ItemStack.deserialize(keys);
    } catch (Exception e) {
        return null;
    }

    // Handle item meta
    if (keys.containsKey("meta")) {
        Map<String, Object> itemmeta = (Map<String, Object>) keys.get("meta");
        // Convert doubles -> ints
        itemmeta = recursiveDoubleToInteger(itemmeta);

        // Deserilize everything
        itemmeta = recursiveDeserialization(itemmeta);

        // Create the Item Meta
        ItemMeta meta = (ItemMeta) ConfigurationSerialization.deserializeObject(itemmeta,
                ConfigurationSerialization.getClassByAlias("ItemMeta"));

        // Colorize everything
        if (meta.hasDisplayName()) {
            meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', meta.getDisplayName()));
        }
        if (meta.hasLore()) {
            List<String> lore = meta.getLore();
            for (int i = 0; i < lore.size(); i++) {
                String line = lore.get(i);
                line = ChatColor.translateAlternateColorCodes('?', line);
                line = ChatColor.translateAlternateColorCodes('&', line);
                lore.set(i, line);
            }
            meta.setLore(lore);
        }
        if (meta instanceof BookMeta) {
            BookMeta book = (BookMeta) meta;
            if (book.hasAuthor()) {
                book.setAuthor(ChatColor.translateAlternateColorCodes('&', book.getAuthor()));
            }
            if (book.hasTitle()) {
                book.setTitle(ChatColor.translateAlternateColorCodes('&', book.getTitle()));
            }
            if (book.hasPages()) {
                List<String> pages = new ArrayList<String>();
                pages.addAll(book.getPages());
                for (int i = 0; i < pages.size(); i++) {
                    String line = pages.get(i);
                    line = ChatColor.translateAlternateColorCodes('&', line);
                    pages.set(i, line);
                }
                book.setPages(pages);
            }
        }

        // Assign the item meta
        item.setItemMeta(meta);
    }
    return new ItemAttachment(item);
}