Search in sources :

Example 26 with ParseException

use of org.json.simple.parser.ParseException in project atlasdb by palantir.

the class NameMetadataDescription method parseFromJson.

public byte[] parseFromJson(String json, boolean allowPrefix) {
    try {
        JSONObject obj = (JSONObject) new JSONParser().parse(json);
        int numDefinedFields = countNumDefinedFields(obj);
        byte[][] bytes = new byte[numDefinedFields][];
        Preconditions.checkArgument(numDefinedFields > 0, "JSON object needs a field named: %s.  Passed json was: %s", rowParts.get(0).getComponentName(), json);
        Preconditions.checkArgument(allowPrefix || numDefinedFields == rowParts.size(), "JSON object has %s defined fields, but the number of row components is %s.  Passed json was: %s", numDefinedFields, rowParts.size(), json);
        for (int i = 0; i < numDefinedFields; ++i) {
            NameComponentDescription desc = rowParts.get(i);
            String str = String.valueOf(obj.get(desc.getComponentName()));
            bytes[i] = desc.getType().convertFromString(str);
            if (desc.isReverseOrder()) {
                EncodingUtils.flipAllBitsInPlace(bytes[i]);
            }
        }
        return com.google.common.primitives.Bytes.concat(bytes);
    } catch (ParseException e) {
        throw Throwables.throwUncheckedException(e);
    }
}
Also used : JSONObject(org.json.simple.JSONObject) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Example 27 with ParseException

use of org.json.simple.parser.ParseException in project spatial-portal by AtlasOfLivingAustralia.

the class LayerLegendGeneralComposer method setupForClassificationLayers.

private void setupForClassificationLayers() {
    if (mapLayer.isPolygonLayer())
        return;
    String activeLayerName = StringConstants.NONE;
    JSONObject field = null;
    JSONObject layer = null;
    if (mapLayer != null && mapLayer.getUri() != null) {
        if (mapLayer.getBaseUri() != null) {
            activeLayerName = mapLayer.getBaseUri().replaceAll("^.*&style=", "").replaceAll("&.*", "").replaceAll("_style", "");
        } else {
            activeLayerName = mapLayer.getUri().replaceAll("^.*&style=", "").replaceAll("&.*", "").replaceAll("_style", "");
        }
        field = CommonData.getLayer(activeLayerName);
        if (field == null)
            return;
        layer = (JSONObject) field.get("layer");
    }
    LOGGER.debug("ACTIVE LAYER: " + activeLayerName);
    if (mapLayer != null && mapLayer.getSubType() == LayerUtilitiesImpl.ALOC) {
        divClassificationPicker.setVisible(true);
        // reset content
        Integer groupCount = mapLayer.getClassificationGroupCount();
        if (groupCount == null) {
            mapLayer.setClassificationGroupCount(getClassificationGroupCount(mapLayer.getName().replace("aloc_", "")));
            groupCount = 0;
        }
        for (int i = cbClassificationGroup.getItemCount() - 1; i >= 0; i--) {
            cbClassificationGroup.removeItemAt(i);
        }
        Comboitem ci = new Comboitem(StringConstants.NONE);
        ci.setParent(cbClassificationGroup);
        for (int i = 1; i <= groupCount; i++) {
            new Comboitem("Group " + i).setParent(cbClassificationGroup);
        }
        // is there a current selection?
        Integer groupSelection = mapLayer.getClassificationSelection();
        if (groupSelection == null) {
            groupSelection = 0;
            mapLayer.setClassificationSelection(groupSelection);
        }
        cbClassificationGroup.setSelectedIndex(groupSelection);
        getFellow("btnCreateArea").setVisible(false);
        cbClassificationGroup.setVisible(true);
        lbClassificationGroup.setVisible(false);
        hboxClassificationGroup.setVisible(false);
    } else if (layer != null && layer.containsKey("type") && layer.get("type").toString().equalsIgnoreCase("contextual")) {
        divClassificationPicker.setVisible(true);
        if (mapLayer.getClassificationGroupCount() == null || mapLayer.getClassificationGroupCount() == 0) {
            // build
            String fieldId = field.get(StringConstants.ID).toString();
            JSONParser jp = new JSONParser();
            JSONObject objJson = null;
            try {
                objJson = (JSONObject) jp.parse(Util.readUrl(CommonData.getLayersServer() + "/field/" + fieldId));
            } catch (ParseException e) {
                LOGGER.error("failed to parse for: " + fieldId);
            }
            JSONArray objects = (JSONArray) objJson.get("objects");
            // sort
            List<JSONObject> list = objects.subList(0, objects.size());
            Collections.sort(list, new Comparator<JSONObject>() {

                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    String s1 = (o1 == null || !o1.containsKey("name")) ? "" : o1.get("name").toString();
                    String s2 = (o2 == null || !o2.containsKey("name")) ? "" : o2.get("name").toString();
                    return s1.compareTo(s2);
                }
            });
            JSONArray obj = new JSONArray();
            obj.addAll(list);
            mapLayer.setClassificationGroupCount(obj.size());
            mapLayer.setClassificationObjects(obj);
        }
        // reset content
        Integer groupCount = mapLayer.getClassificationGroupCount();
        JSONArray groupObjects = mapLayer.getClassificationObjects();
        lbClassificationGroup.setItemRenderer(new ListitemRenderer<JSONObject>() {

            @Override
            public void render(Listitem item, JSONObject data, int index) throws Exception {
                Checkbox cb = new Checkbox();
                final int idx = index;
                cb.addEventListener("onCheck", new EventListener<Event>() {

                    @Override
                    public void onEvent(Event event) throws Exception {
                        if (mapLayer != null) {
                            lbClassificationGroup.setMultiple(true);
                            String v = ((Listcell) event.getTarget().getParent().getParent().getChildren().get(1)).getLabel();
                            if (((CheckEvent) event).isChecked()) {
                                selectedList.add(v);
                            } else {
                                selectedList.remove(v);
                            }
                            lblSelectedCount.setValue(selectedList.size() + " checked");
                            getFellow("clearSelection").setVisible(selectedList.size() > 0);
                            getFellow("createInGroup").setVisible(selectedList.size() > 0);
                            if (getFellowIfAny("createOutGroup") != null)
                                getFellow("createOutGroup").setVisible(selectedList.size() > 0);
                            highlightSelect(idx);
                        }
                    }
                });
                determineCheckboxState(cb, data.get("name").toString());
                Listcell lc;
                lc = new Listcell();
                cb.setParent(lc);
                lc.setParent(item);
                lc = new Listcell(data.get("name").toString());
                lc.setParent(item);
                lc = new Listcell();
                Image img = new Image();
                img.setTooltip("Create as an area layer");
                img.setClass("icon-plus-sign");
                img.setParent(lc);
                lc.setParent(item);
                final JSONObject j = data;
                img.addEventListener("onClick", new EventListener<Event>() {

                    @Override
                    public void onEvent(Event event) throws Exception {
                        createAreaEcho(j.get("pid").toString());
                    }
                });
                lc = new Listcell();
                img = new Image();
                img.setTooltip("Zoom to area");
                img.setClass("icon-zoom-in");
                img.setParent(lc);
                lc.setParent(item);
                img.addEventListener("onClick", new EventListener<Event>() {

                    @Override
                    public void onEvent(Event event) throws Exception {
                        List<Double> b = Util.getBoundingBox(j.get("bbox").toString());
                        BoundingBox bbox = new BoundingBox();
                        bbox.setMinLongitude(b.get(0).floatValue());
                        bbox.setMinLatitude(b.get(1).floatValue());
                        bbox.setMaxLongitude(b.get(2).floatValue());
                        bbox.setMaxLatitude(b.get(3).floatValue());
                        getMapComposer().getOpenLayersJavascript().execute(getMapComposer().getOpenLayersJavascript().zoomToBoundingBox(bbox, false));
                    }
                });
            }
        });
        lbClassificationGroup.addEventListener("onSelect", new EventListener<Event>() {

            @Override
            public void onEvent(Event event) throws Exception {
                if (mapLayer != null) {
                    highlightSelect(lbClassificationGroup.getSelectedIndex());
                }
            }
        });
        List<JSONObject> model = new ArrayList<JSONObject>();
        for (int i = 0; i < groupCount; i++) {
            model.add((JSONObject) groupObjects.get(i));
        }
        lbClassificationGroup.setModel(new SimpleListModel(model));
        // is there a current selection?
        Integer groupSelection = mapLayer.getClassificationSelection();
        if (groupSelection == null) {
            groupSelection = 0;
            mapLayer.setClassificationSelection(groupSelection);
        }
        getFellow("btnCreateArea").setVisible(true);
        getFellow("btnCreateArea").setVisible(false);
        cbClassificationGroup.setVisible(false);
        lbClassificationGroup.setVisible(true);
        hboxClassificationGroup.setVisible(true);
    } else {
        getFellow("btnCreateArea").setVisible(false);
        divClassificationPicker.setVisible(false);
    }
}
Also used : JSONArray(org.json.simple.JSONArray) Image(org.zkoss.zul.Image) ParseException(org.json.simple.parser.ParseException) JSONObject(org.json.simple.JSONObject) Checkbox(org.zkoss.zul.Checkbox) BoundingBox(au.org.emii.portal.value.BoundingBox) CheckEvent(org.zkoss.zk.ui.event.CheckEvent) Event(org.zkoss.zk.ui.event.Event) JSONParser(org.json.simple.parser.JSONParser) List(java.util.List) ParseException(org.json.simple.parser.ParseException) EventListener(org.zkoss.zk.ui.event.EventListener)

Example 28 with ParseException

use of org.json.simple.parser.ParseException in project chatty by chatty.

the class BTTVEmotes method parseEmotes.

/**
 * Parse emotes from the given JSON.
 *
 * @param json
 * @param channelRestriction
 * @return
 */
private static Set<Emoticon> parseEmotes(String json, String channelRestriction) {
    Set<Emoticon> emotes = new HashSet<>();
    if (json == null) {
        return emotes;
    }
    JSONParser parser = new JSONParser();
    try {
        JSONObject root = (JSONObject) parser.parse(json);
        String urlTemplate = (String) root.get("urlTemplate");
        if (urlTemplate == null || urlTemplate.isEmpty()) {
            LOGGER.warning("No URL Template");
            return emotes;
        }
        JSONArray emotesArray = (JSONArray) root.get("emotes");
        for (Object o : emotesArray) {
            if (o instanceof JSONObject) {
                Emoticon emote = parseEmote((JSONObject) o, urlTemplate, channelRestriction);
                if (emote != null) {
                    emotes.add(emote);
                }
            }
        }
    } catch (ParseException | ClassCastException ex) {
        // ClassCastException is also caught in parseEmote(), so it won't
        // quit completely when one emote is invalid.
        LOGGER.warning("BTTV: Error parsing emotes: " + ex);
    }
    return emotes;
}
Also used : Emoticon(chatty.util.api.Emoticon) JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) ParseException(org.json.simple.parser.ParseException) HashSet(java.util.HashSet)

Example 29 with ParseException

use of org.json.simple.parser.ParseException in project chatty by chatty.

the class BTTVEmotes method parseBots.

/**
 * Parse list of bots from the given JSON.
 *
 * @param json
 * @return
 */
private static Set<String> parseBots(String json) {
    Set<String> result = new HashSet<>();
    if (json == null) {
        return result;
    }
    JSONParser parser = new JSONParser();
    try {
        JSONObject root = (JSONObject) parser.parse(json);
        JSONArray botsArray = (JSONArray) root.get("bots");
        if (botsArray == null) {
            // No bots for this channel
            return result;
        }
        for (Object o : botsArray) {
            result.add((String) o);
        }
    } catch (ParseException | ClassCastException ex) {
        LOGGER.warning("BTTV: Error parsing bots: " + ex);
    }
    return result;
}
Also used : JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) ParseException(org.json.simple.parser.ParseException) HashSet(java.util.HashSet)

Example 30 with ParseException

use of org.json.simple.parser.ParseException in project teiid by teiid.

the class BinaryWSProcedureExecution method execute.

public void execute() throws TranslatorException {
    List<Argument> arguments = this.procedure.getArguments();
    String method = (String) arguments.get(0).getArgumentValue().getValue();
    Object payload = arguments.get(1).getArgumentValue().getValue();
    String endpoint = (String) arguments.get(2).getArgumentValue().getValue();
    try {
        Dispatch<DataSource> dispatch = this.conn.createDispatch(HTTPBinding.HTTP_BINDING, endpoint, DataSource.class, Mode.MESSAGE);
        if (method == null) {
            // $NON-NLS-1$
            method = "POST";
        }
        dispatch.getRequestContext().put(MessageContext.HTTP_REQUEST_METHOD, method);
        if (payload != null && !"POST".equalsIgnoreCase(method) && !"PUT".equalsIgnoreCase(method) && !"PATCH".equalsIgnoreCase(method)) {
            // $NON-NLS-1$
            throw new WebServiceException(WSExecutionFactory.UTIL.getString("http_usage_error"));
        }
        Map<String, List<String>> httpHeaders = (Map<String, List<String>>) dispatch.getRequestContext().get(MessageContext.HTTP_REQUEST_HEADERS);
        if (customHeaders != null) {
            httpHeaders.putAll(customHeaders);
        }
        if (arguments.size() > 5 && // designer modeled the return value as an out, which will add an argument in the 5th position that is an out
        this.procedure.getMetadataObject() != null && (this.procedure.getMetadataObject().getParameters().get(0).getType() == Type.ReturnValue || arguments.get(5).getMetadataObject().getSourceName().equalsIgnoreCase("headers"))) {
            // $NON-NLS-1$
            Clob headers = (Clob) arguments.get(5).getArgumentValue().getValue();
            if (headers != null) {
                parseHeader(httpHeaders, headers);
            }
        }
        dispatch.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, httpHeaders);
        DataSource ds = null;
        if (payload instanceof String) {
            ds = new InputStreamFactory.ClobInputStreamFactory(new ClobImpl((String) payload));
        } else if (payload instanceof SQLXML) {
            ds = new InputStreamFactory.SQLXMLInputStreamFactory((SQLXML) payload);
        } else if (payload instanceof Clob) {
            ds = new InputStreamFactory.ClobInputStreamFactory((Clob) payload);
        } else if (payload instanceof Blob) {
            ds = new InputStreamFactory.BlobInputStreamFactory((Blob) payload);
        }
        this.returnValue = dispatch.invoke(ds);
        Map<String, Object> rc = dispatch.getResponseContext();
        this.responseCode = (Integer) rc.get(WSConnection.STATUS_CODE);
        if (this.useResponseContext) {
            // it's presumed that the caller will handle the response codes
            this.responseContext = rc;
        } else {
            // TODO: may need to add logic around some 200/300 codes - cxf should at least be logging this
            if (this.responseCode >= 400) {
                String message = conn.getStatusMessage(this.responseCode);
                throw new TranslatorException(WSExecutionFactory.Event.TEIID15005, WSExecutionFactory.UTIL.gs(WSExecutionFactory.Event.TEIID15005, this.responseCode, message));
            }
        }
    } catch (WebServiceException e) {
        throw new TranslatorException(e);
    } catch (ParseException e) {
        throw new TranslatorException(e);
    } catch (IOException e) {
        throw new TranslatorException(e);
    } catch (SQLException e) {
        throw new TranslatorException(e);
    }
}
Also used : Blob(java.sql.Blob) Argument(org.teiid.language.Argument) WebServiceException(javax.xml.ws.WebServiceException) SQLException(java.sql.SQLException) IOException(java.io.IOException) InputStreamFactory(org.teiid.core.types.InputStreamFactory) DataSource(javax.activation.DataSource) SQLXML(java.sql.SQLXML) List(java.util.List) TranslatorException(org.teiid.translator.TranslatorException) ParseException(org.json.simple.parser.ParseException) Clob(java.sql.Clob) HashMap(java.util.HashMap) Map(java.util.Map) ClobImpl(org.teiid.core.types.ClobImpl)

Aggregations

ParseException (org.json.simple.parser.ParseException)258 JSONObject (org.json.simple.JSONObject)191 JSONParser (org.json.simple.parser.JSONParser)185 JSONArray (org.json.simple.JSONArray)84 IOException (java.io.IOException)71 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)50 HashMap (java.util.HashMap)41 ArrayList (java.util.ArrayList)34 Map (java.util.Map)23 HashSet (java.util.HashSet)18 API (org.wso2.carbon.apimgt.api.model.API)18 BufferedReader (java.io.BufferedReader)13 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)13 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)13 List (java.util.List)12 File (java.io.File)11 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)11 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)11 InputStreamReader (java.io.InputStreamReader)10 URL (java.net.URL)10