Example usage for com.google.gson.stream JsonReader close

List of usage examples for com.google.gson.stream JsonReader close

Introduction

In this page you can find the example usage for com.google.gson.stream JsonReader close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this JSON reader and the underlying java.io.Reader .

Usage

From source file:json_export_import.GSON_Observer.java

public void read() {
    try {/*from  w w  w . j a  v a2s  . c om*/
        JsonReader reader = new JsonReader(new FileReader("/home/rgreim/Output.json"));
        reader.beginArray();
        while (reader.hasNext()) {
            String sequence = reader.nextString();
            System.out.println("Sequenz: " + sequence);
        }
        reader.endArray();
        reader.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(GSON_Observer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GSON_Observer.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:me.dags.creativeblock.util.JsonUtil.java

License:Open Source License

public static <T> T deserialize(JsonReader reader, Class<T> type) throws IOException {
    T t = GSON.fromJson(reader, type);//from   w ww  .j a va  2  s .c  o m
    reader.close();
    return t;
}

From source file:nectec.thai.widget.address.repository.JsonParser.java

License:Apache License

public static <T> List<T> parse(Context context, String jsonFileName, Class<T> tClass) {
    List<T> allProvince = new ArrayList<>();
    Gson gson = new Gson();
    try {/*from   w  w w .j  a v a2s. c  o  m*/
        InputStream inputStream = context.getAssets().open(jsonFileName);
        JsonReader reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
        reader.beginArray();
        while (reader.hasNext()) {
            T message = gson.fromJson(reader, tClass);
            allProvince.add(message);
        }
        reader.endArray();
        reader.close();
    } catch (IOException e) {
        if (BuildConfig.DEBUG)
            Log.e(TAG, "parse() error.", e);
    }
    return allProvince;
}

From source file:net.visualillusionsent.newu.StationTracker.java

License:Open Source License

private void loadStations() {
    try {/*from  w w  w  .  j  a va  2s .  c  o m*/
        File stationsJSON = new File(NewU.cfgDir, "stations.json");
        if (!stationsJSON.exists()) {
            stationsJSON.createNewFile();
            return;
        }

        JsonReader reader = new JsonReader(new FileReader(stationsJSON));
        reader.beginObject(); // Begin main object
        while (reader.hasNext()) {
            String name = reader.nextName();
            if (name.equals("Station")) {
                NewUStation temp = null;
                reader.beginObject(); // Begin Station
                String foundName = null;
                while (reader.hasNext()) {
                    name = reader.nextName();
                    if (name.equals("Name")) {
                        foundName = reader.nextString();
                        continue;
                    } else if (name.equals("Location")) {
                        reader.beginObject(); // Begin Location
                        temp = new NewUStation(foundName, reader); // Pass reader into NewUStation object for parsing
                        reader.endObject(); // End Location
                    } else if (name.equals("Discoverers")) {
                        reader.beginArray(); // Begin Discoverers
                        while (reader.hasNext()) {
                            if (temp != null) {
                                temp.addDiscoverer(reader.nextString());
                            }
                        }
                        reader.endArray(); // End Discoverers
                    } else {
                        reader.skipValue(); // UNKNOWN THING
                    }
                }
                if (temp != null) {
                    stations.put(temp.getName(), temp);
                }
                reader.endObject(); //End Station
            }
        }

        reader.endObject(); // End main object
        reader.close();
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Failed to load stations...");
    }
}

From source file:org.apache.nifi.toolkit.zkmigrator.ZooKeeperMigrator.java

License:Apache License

void writeZooKeeper(InputStream zkData, AuthMode authMode, byte[] authData, boolean ignoreSource,
        boolean useExistingACL) throws IOException, ExecutionException, InterruptedException {
    // ensure that the chroot path exists
    ZooKeeper zooKeeperRoot = getZooKeeper(Joiner.on(',').join(zooKeeperEndpointConfig.getServers()), authMode,
            authData);//w w  w . j a  v a2s.c om
    ensureNodeExists(zooKeeperRoot, zooKeeperEndpointConfig.getPath(), CreateMode.PERSISTENT);
    closeZooKeeper(zooKeeperRoot);

    ZooKeeper zooKeeper = getZooKeeper(zooKeeperEndpointConfig.getConnectString(), authMode, authData);
    JsonReader jsonReader = new JsonReader(new BufferedReader(new InputStreamReader(zkData)));
    Gson gson = new GsonBuilder().create();

    jsonReader.beginArray();

    // determine source ZooKeeperEndpointConfig for this data
    final ZooKeeperEndpointConfig sourceZooKeeperEndpointConfig = gson.fromJson(jsonReader,
            ZooKeeperEndpointConfig.class);
    LOGGER.info("Source data was obtained from ZooKeeper: {}", sourceZooKeeperEndpointConfig);
    Preconditions.checkArgument(
            !Strings.isNullOrEmpty(sourceZooKeeperEndpointConfig.getConnectString())
                    && !Strings.isNullOrEmpty(sourceZooKeeperEndpointConfig.getPath())
                    && sourceZooKeeperEndpointConfig.getServers() != null
                    && sourceZooKeeperEndpointConfig.getServers().size() > 0,
            "Source ZooKeeper %s from %s is invalid", sourceZooKeeperEndpointConfig, zkData);
    Preconditions.checkArgument(
            Collections
                    .disjoint(zooKeeperEndpointConfig.getServers(), sourceZooKeeperEndpointConfig.getServers())
                    || !zooKeeperEndpointConfig.getPath().equals(sourceZooKeeperEndpointConfig.getPath())
                    || ignoreSource,
            "Source ZooKeeper config %s for the data provided can not contain the same server and path as the configured destination ZooKeeper config %s",
            sourceZooKeeperEndpointConfig, zooKeeperEndpointConfig);

    // stream through each node read from the json input
    final Stream<DataStatAclNode> stream = StreamSupport
            .stream(new Spliterators.AbstractSpliterator<DataStatAclNode>(0, 0) {
                @Override
                public boolean tryAdvance(Consumer<? super DataStatAclNode> action) {
                    try {
                        // stream each DataStatAclNode from configured json file
                        synchronized (jsonReader) {
                            if (jsonReader.hasNext()) {
                                action.accept(gson.fromJson(jsonReader, DataStatAclNode.class));
                                return true;
                            } else {
                                return false;
                            }
                        }
                    } catch (IOException e) {
                        throw new RuntimeException("unable to read nodes from json", e);
                    }
                }
            }, false);

    final List<CompletableFuture<Stat>> writeFutures = stream.parallel().map(node -> {
        /*
         * create stage to determine the acls that should be applied to the node.
         * this stage will be used to initialize the chain
         */
        final CompletableFuture<List<ACL>> determineACLStage = CompletableFuture
                .supplyAsync(() -> determineACLs(node, authMode, useExistingACL));
        /*
         * create stage to apply acls to nodes and transform node to DataStatAclNode object
         */
        final Function<List<ACL>, CompletableFuture<DataStatAclNode>> transformNodeStage = acls -> CompletableFuture
                .supplyAsync(() -> transformNode(node, acls));
        /*
         * create stage to ensure that nodes exist for the entire path of the zookeeper node, must be invoked after the transformNode stage to
         * ensure that the node will exist after path migration
         */
        final Function<DataStatAclNode, CompletionStage<String>> ensureNodeExistsStage = dataStatAclNode -> CompletableFuture
                .supplyAsync(() -> ensureNodeExists(zooKeeper, dataStatAclNode.getPath(),
                        dataStatAclNode.getEphemeralOwner() == 0 ? CreateMode.PERSISTENT
                                : CreateMode.EPHEMERAL));
        /*
         * create stage that waits for both the transformNode and ensureNodeExists stages complete, and also provides that the given transformed node is
         * available to the next stage
         */
        final BiFunction<String, DataStatAclNode, DataStatAclNode> combineEnsureNodeAndTransferNodeStage = (u,
                dataStatAclNode) -> dataStatAclNode;
        /*
         * create stage to transmit the node to the destination zookeeper endpoint, must be invoked after the node has been transformed and its path
         * has been created (or already exists) in the destination zookeeper
         */
        final Function<DataStatAclNode, CompletionStage<Stat>> transmitNodeStage = dataStatNode -> CompletableFuture
                .supplyAsync(() -> transmitNode(zooKeeper, dataStatNode));
        /*
         * submit the stages chained together in the proper order to perform the processing on the given node
         */
        final CompletableFuture<DataStatAclNode> dataStatAclNodeCompletableFuture = determineACLStage
                .thenCompose(transformNodeStage);
        return dataStatAclNodeCompletableFuture.thenCompose(ensureNodeExistsStage)
                .thenCombine(dataStatAclNodeCompletableFuture, combineEnsureNodeAndTransferNodeStage)
                .thenCompose(transmitNodeStage);
    }).collect(Collectors.toList());

    CompletableFuture<Void> allWritesFuture = CompletableFuture
            .allOf(writeFutures.toArray(new CompletableFuture[writeFutures.size()]));
    final CompletableFuture<List<Stat>> finishedWrites = allWritesFuture
            .thenApply(v -> writeFutures.stream().map(CompletableFuture::join).collect(Collectors.toList()));
    final List<Stat> writesDone = finishedWrites.get();
    if (LOGGER.isInfoEnabled()) {
        final int writeCount = writesDone.size();
        LOGGER.info("{} {} transferred to {}", writeCount, writeCount == 1 ? "node" : "nodes",
                zooKeeperEndpointConfig);
    }
    jsonReader.close();
    closeZooKeeper(zooKeeper);
}

From source file:org.apache.olingo.odata2.core.ep.consumer.JsonEntityConsumer.java

License:Apache License

public ODataDeltaFeed readDeltaFeed(final EdmEntitySet entitySet, final InputStream content,
        final EntityProviderReadProperties readProperties) throws EntityProviderException {

    JsonReader reader = null;
    EntityProviderException cachedException = null;

    try {//  w  ww. j a va2 s .  c  o m
        EntityInfoAggregator eia = EntityInfoAggregator.create(entitySet);
        reader = createJsonReader(content);

        JsonFeedConsumer jfc = new JsonFeedConsumer(reader, eia, readProperties);
        ODataDeltaFeed result = jfc.readFeedStandalone();

        return result;
    } catch (UnsupportedEncodingException e) {
        cachedException = new EntityProviderException(
                EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e);
        throw cachedException;
    } finally {// NOPMD (suppress DoNotThrowExceptionInFinally)
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                if (cachedException != null) {
                    throw cachedException;
                } else {
                    throw new EntityProviderException(
                            EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()),
                            e);
                }
            }
        }
    }
}

From source file:org.apache.zeppelin.interpreter.InterpreterSetting.java

License:Apache License

public static InterpreterSetting fromJson(String json) {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    StringReader stringReader = new StringReader(json);
    JsonReader jsonReader = new JsonReader(stringReader);
    InterpreterSetting intpSetting = new InterpreterSetting();
    try {/*from  ww  w .  j a  va2s .  c om*/
        jsonReader.beginObject();
        while (jsonReader.hasNext()) {
            String tag = jsonReader.nextName();
            if (tag.equals("id")) {
                String id = jsonReader.nextString();
                intpSetting.setId(id);
            } else if (tag.equals("name")) {
                String name = jsonReader.nextString();
                intpSetting.setName(name);
            } else if (tag.equals("group")) {
                String group = jsonReader.nextString();
                intpSetting.setGroup(group);
            } else if (tag.equals("dependencies")) {
                String strDep = jsonReader.nextString();
                List<Dependency> dependencies = gson.fromJson(strDep, new TypeToken<List<Dependency>>() {
                }.getType());
                intpSetting.setDependencies(dependencies);
            } else if (tag.equals("properties")) {
                String strProp = jsonReader.nextString();
                Map<String, InterpreterProperty> properties = gson.fromJson(strProp,
                        new TypeToken<Map<String, InterpreterProperty>>() {
                        }.getType());
                intpSetting.setProperties(properties);
            } else if (tag.equals("interpreterOption")) {
                String strOption = jsonReader.nextString();
                InterpreterOption intpOption = gson.fromJson(strOption, new TypeToken<InterpreterOption>() {
                }.getType());
                intpSetting.setOption(intpOption);
            } else if (tag.equals("interpreterGroup")) {
                String strIntpInfos = jsonReader.nextString();
                List<InterpreterInfo> intpInfos = gson.fromJson(strIntpInfos,
                        new TypeToken<List<InterpreterInfo>>() {
                        }.getType());
                intpSetting.setInterpreterInfos(intpInfos);
            } else {
                LOGGER.error("Error data type!");
            }
        }
        jsonReader.endObject();
        jsonReader.close();
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }

    return intpSetting;
}

From source file:org.bimserver.client.ClientIfcModel.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
private void processDownload(Long download)
        throws BimServerClientException, UserException, ServerException, PublicInterfaceNotFoundException {
    WaitingList<Long> waitingList = new WaitingList<Long>();
    try {//from   w ww.ja  va2s. c  o  m
        InputStream downloadData = bimServerClient.getDownloadData(download, getIfcSerializerOid());
        boolean log = false;
        // TODO Make this streaming again, make sure the EmfSerializer getInputStream method is working properly
        if (log) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            if (downloadData instanceof SerializerInputstream) {
                SerializerInputstream serializerInputStream = (SerializerInputstream) downloadData;
                serializerInputStream.getEmfSerializer().writeToOutputStream(baos);
            } else {
                IOUtils.copy((InputStream) downloadData, baos);
            }
            FileOutputStream fos = new FileOutputStream(new File(download + ".json"));
            IOUtils.write(baos.toByteArray(), fos);
            fos.close();
            downloadData = new ByteArrayInputStream(baos.toByteArray());
        } else {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            if (downloadData instanceof SerializerInputstream) {
                SerializerInputstream serializerInputStream = (SerializerInputstream) downloadData;
                serializerInputStream.getEmfSerializer().writeToOutputStream(baos);
            } else {
                IOUtils.copy((InputStream) downloadData, baos);
            }
            downloadData = new ByteArrayInputStream(baos.toByteArray());
        }
        JsonReader jsonReader = new JsonReader(new InputStreamReader(downloadData, Charsets.UTF_8));
        try {
            jsonReader.beginObject();
            if (jsonReader.nextName().equals("objects")) {
                jsonReader.beginArray();
                while (jsonReader.hasNext()) {
                    jsonReader.beginObject();
                    if (jsonReader.nextName().equals("__oid")) {
                        long oid = jsonReader.nextLong();
                        if (jsonReader.nextName().equals("__type")) {
                            String type = jsonReader.nextString();
                            EClass eClass = (EClass) Ifc2x3tc1Package.eINSTANCE.getEClassifier(type);
                            if (eClass == null) {
                                throw new BimServerClientException("No class found with name " + type);
                            }
                            if (jsonReader.nextName().equals("__state")) {
                                String state = jsonReader.nextString();
                                IdEObject object = null;
                                if (containsNoFetch(oid)) {
                                    object = getNoFetch(oid);
                                } else {
                                    object = (IdEObject) Ifc2x3tc1Factory.eINSTANCE.create(eClass);
                                    ((IdEObjectImpl) object).eSetStore(eStore);
                                    ((IdEObjectImpl) object).setOid(oid);
                                    add(oid, object);
                                }
                                if (state.equals("NOT_LOADED")) {
                                    ((IdEObjectImpl) object).setLoadingState(State.TO_BE_LOADED);
                                } else {
                                    while (jsonReader.hasNext()) {
                                        String featureName = jsonReader.nextName();
                                        boolean embedded = false;
                                        if (featureName.startsWith("__ref")) {
                                            featureName = featureName.substring(5);
                                        } else if (featureName.startsWith("__emb")) {
                                            embedded = true;
                                            featureName = featureName.substring(5);
                                        }
                                        EStructuralFeature eStructuralFeature = eClass
                                                .getEStructuralFeature(featureName);
                                        if (eStructuralFeature == null) {
                                            throw new BimServerClientException("Unknown field (" + featureName
                                                    + ") on class " + eClass.getName());
                                        }
                                        if (eStructuralFeature.isMany()) {
                                            jsonReader.beginArray();
                                            if (eStructuralFeature instanceof EAttribute) {
                                                List list = (List) object.eGet(eStructuralFeature);
                                                List<String> stringList = null;

                                                if (eStructuralFeature.getEType() == EcorePackage.eINSTANCE
                                                        .getEDoubleObject()
                                                        || eStructuralFeature
                                                                .getEType() == EcorePackage.eINSTANCE
                                                                        .getEDouble()) {
                                                    EStructuralFeature asStringFeature = eClass
                                                            .getEStructuralFeature(
                                                                    eStructuralFeature.getName() + "AsString");
                                                    stringList = (List<String>) object.eGet(asStringFeature);
                                                }

                                                while (jsonReader.hasNext()) {
                                                    Object e = readPrimitive(jsonReader, eStructuralFeature);
                                                    list.add(e);
                                                    if (eStructuralFeature.getEType() == EcorePackage.eINSTANCE
                                                            .getEDouble()) {
                                                        double val = (Double) e;
                                                        stringList.add("" + val); // TODO this is losing precision, maybe also send the string value?
                                                    }
                                                }
                                            } else if (eStructuralFeature instanceof EReference) {
                                                int index = 0;
                                                while (jsonReader.hasNext()) {
                                                    if (embedded) {
                                                        List list = (List) object.eGet(eStructuralFeature);
                                                        jsonReader.beginObject();
                                                        String n = jsonReader.nextName();
                                                        if (n.equals("__type")) {
                                                            String t = jsonReader.nextString();
                                                            IdEObject wrappedObject = (IdEObject) Ifc2x3tc1Factory.eINSTANCE
                                                                    .create((EClass) Ifc2x3tc1Package.eINSTANCE
                                                                            .getEClassifier(t));
                                                            if (jsonReader.nextName().equals("value")) {
                                                                EStructuralFeature wv = wrappedObject.eClass()
                                                                        .getEStructuralFeature("wrappedValue");
                                                                wrappedObject.eSet(wv,
                                                                        readPrimitive(jsonReader, wv));
                                                                list.add(wrappedObject);
                                                            } else {
                                                                // error
                                                            }
                                                        } else if (n.equals("oid")) {
                                                            // Sometimes embedded is true, bot also referenced are included, those are always embdedded in an object
                                                            long refOid = jsonReader.nextLong();
                                                            if (containsNoFetch(refOid)) {
                                                                IdEObject refObj = getNoFetch(refOid);
                                                                AbstractEList l = (AbstractEList) object
                                                                        .eGet(eStructuralFeature);
                                                                while (l.size() <= index) {
                                                                    l.addUnique(refObj.eClass().getEPackage()
                                                                            .getEFactoryInstance()
                                                                            .create(refObj.eClass()));
                                                                }
                                                                l.setUnique(index, refObj);
                                                            } else {
                                                                waitingList.add(refOid, new ListWaitingObject(
                                                                        object, eStructuralFeature, index));
                                                            }
                                                        }
                                                        jsonReader.endObject();
                                                    } else {
                                                        long refOid = jsonReader.nextLong();
                                                        if (containsNoFetch(refOid)) {
                                                            IdEObject refObj = getNoFetch(refOid);
                                                            AbstractEList l = (AbstractEList) object
                                                                    .eGet(eStructuralFeature);
                                                            while (l.size() <= index) {
                                                                l.addUnique(refObj.eClass().getEPackage()
                                                                        .getEFactoryInstance()
                                                                        .create(refObj.eClass()));
                                                            }
                                                            l.setUnique(index, refObj);
                                                        } else {
                                                            waitingList.add(refOid, new ListWaitingObject(
                                                                    object, eStructuralFeature, index));
                                                        }
                                                        index++;
                                                    }
                                                }
                                            }
                                            jsonReader.endArray();
                                        } else {
                                            if (eStructuralFeature instanceof EAttribute) {
                                                Object x = readPrimitive(jsonReader, eStructuralFeature);
                                                if (eStructuralFeature.getEType() == EcorePackage.eINSTANCE
                                                        .getEDouble()) {
                                                    EStructuralFeature asStringFeature = object.eClass()
                                                            .getEStructuralFeature(
                                                                    eStructuralFeature.getName() + "AsString");
                                                    object.eSet(asStringFeature, "" + x); // TODO this is losing precision, maybe also send the string value?
                                                }
                                                object.eSet(eStructuralFeature, x);
                                            } else if (eStructuralFeature instanceof EReference) {
                                                if (embedded) {
                                                    jsonReader.beginObject();
                                                    if (jsonReader.nextName().equals("__type")) {
                                                        String t = jsonReader.nextString();
                                                        IdEObject wrappedObject = (IdEObject) Ifc2x3tc1Factory.eINSTANCE
                                                                .create((EClass) Ifc2x3tc1Package.eINSTANCE
                                                                        .getEClassifier(t));
                                                        if (jsonReader.nextName().equals("value")) {
                                                            EStructuralFeature wv = wrappedObject.eClass()
                                                                    .getEStructuralFeature("wrappedValue");
                                                            wrappedObject.eSet(wv,
                                                                    readPrimitive(jsonReader, wv));
                                                            object.eSet(eStructuralFeature, wrappedObject);
                                                        } else {
                                                            // error
                                                        }
                                                    }
                                                    jsonReader.endObject();
                                                } else {
                                                    long refOid = jsonReader.nextLong();
                                                    if (containsNoFetch(refOid)) {
                                                        IdEObject refObj = getNoFetch(refOid);
                                                        object.eSet(eStructuralFeature, refObj);
                                                    } else {
                                                        waitingList.add(refOid, new SingleWaitingObject(object,
                                                                eStructuralFeature));
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                if (waitingList.containsKey(oid)) {
                                    try {
                                        waitingList.updateNode(oid, eClass, object);
                                    } catch (DeserializeException e) {
                                        LOGGER.error("", e);
                                    }
                                }
                            }
                        }
                    }
                    jsonReader.endObject();
                }
                jsonReader.endArray();
            }
            jsonReader.endObject();
        } catch (IfcModelInterfaceException e1) {
            LOGGER.error("", e1);
        } finally {
            jsonReader.close();
        }
    } catch (IOException e) {
        LOGGER.error("", e);
    } catch (SerializerException e) {
        LOGGER.error("", e);
    } finally {
        waitingList.dumpIfNotEmpty();
        bimServerClient.getServiceInterface().cleanupLongAction(download);
    }
}

From source file:org.bimserver.deserializers.JsonDeserializer.java

License:Open Source License

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override/*from w  w w. ja  va 2 s .c  om*/
public IfcModelInterface read(InputStream in, String filename, long fileSize) throws DeserializeException {
    IfcModelInterface model = new IfcModel();
    WaitingList<Long> waitingList = new WaitingList<Long>();
    JsonReader jsonReader = new JsonReader(new InputStreamReader(in));
    try {
        jsonReader.beginObject();
        if (jsonReader.nextName().equals("objects")) {
            jsonReader.beginArray();
            while (jsonReader.hasNext()) {
                jsonReader.beginObject();
                if (jsonReader.nextName().equals("__oid")) {
                    long oid = jsonReader.nextLong();
                    if (jsonReader.nextName().equals("__type")) {
                        String type = jsonReader.nextString();
                        EClass eClass = (EClass) Ifc2x3tc1Package.eINSTANCE.getEClassifier(type);
                        if (eClass == null) {
                            throw new DeserializeException("No class found with name " + type);
                        }
                        IdEObject object = (IdEObject) Ifc2x3tc1Factory.eINSTANCE.create(eClass);
                        // ((IdEObjectImpl) object).setDelegate(new
                        // ClientDelegate(this, object, null));
                        ((IdEObjectImpl) object).setOid(oid);
                        model.add(object.getOid(), object);
                        while (jsonReader.hasNext()) {
                            String featureName = jsonReader.nextName();
                            boolean embedded = false;
                            if (featureName.startsWith("__ref")) {
                                featureName = featureName.substring(5);
                            } else if (featureName.startsWith("__emb")) {
                                embedded = true;
                                featureName = featureName.substring(5);
                            }
                            EStructuralFeature eStructuralFeature = eClass.getEStructuralFeature(featureName);
                            if (eStructuralFeature == null) {
                                throw new DeserializeException(
                                        "Unknown field (" + featureName + ") on class " + eClass.getName());
                            }
                            if (eStructuralFeature.isMany()) {
                                jsonReader.beginArray();
                                if (eStructuralFeature instanceof EAttribute) {
                                    List list = (List) object.eGet(eStructuralFeature);
                                    List<String> stringList = null;

                                    if (eStructuralFeature.getEType() == EcorePackage.eINSTANCE
                                            .getEDoubleObject()
                                            || eStructuralFeature.getEType() == EcorePackage.eINSTANCE
                                                    .getEDouble()) {
                                        EStructuralFeature asStringFeature = eClass.getEStructuralFeature(
                                                eStructuralFeature.getName() + "AsString");
                                        stringList = (List<String>) object.eGet(asStringFeature);
                                    }

                                    while (jsonReader.hasNext()) {
                                        Object e = readPrimitive(jsonReader, eStructuralFeature);
                                        list.add(e);
                                        if (eStructuralFeature.getEType() == EcorePackage.eINSTANCE
                                                .getEDouble()) {
                                            double val = (Double) e;
                                            stringList.add("" + val); // TODO
                                            // this
                                            // is
                                            // losing
                                            // precision,
                                            // maybe
                                            // also
                                            // send
                                            // the
                                            // string
                                            // value?
                                        }
                                    }
                                } else if (eStructuralFeature instanceof EReference) {
                                    int index = 0;
                                    while (jsonReader.hasNext()) {
                                        if (embedded) {
                                            List list = (List) object.eGet(eStructuralFeature);
                                            jsonReader.beginObject();
                                            if (jsonReader.nextName().equals("__type")) {
                                                String t = jsonReader.nextString();
                                                IdEObject wrappedObject = (IdEObject) Ifc2x3tc1Factory.eINSTANCE
                                                        .create((EClass) Ifc2x3tc1Package.eINSTANCE
                                                                .getEClassifier(t));
                                                if (jsonReader.nextName().equals("value")) {
                                                    EStructuralFeature wv = wrappedObject.eClass()
                                                            .getEStructuralFeature("wrappedValue");
                                                    wrappedObject.eSet(wv, readPrimitive(jsonReader, wv));
                                                    list.add(wrappedObject);
                                                } else {
                                                    // error
                                                }
                                            }
                                            jsonReader.endObject();
                                        } else {
                                            long refOid = jsonReader.nextLong();
                                            waitingList.add(refOid,
                                                    new ListWaitingObject(object, eStructuralFeature, index));
                                            index++;
                                        }
                                    }
                                }
                                jsonReader.endArray();
                            } else {
                                if (eStructuralFeature instanceof EAttribute) {
                                    Object x = readPrimitive(jsonReader, eStructuralFeature);
                                    if (eStructuralFeature.getEType() == EcorePackage.eINSTANCE.getEDouble()) {
                                        EStructuralFeature asStringFeature = object.eClass()
                                                .getEStructuralFeature(
                                                        eStructuralFeature.getName() + "AsString");
                                        object.eSet(asStringFeature, "" + x); // TODO
                                        // this
                                        // is
                                        // losing
                                        // precision,
                                        // maybe
                                        // also
                                        // send
                                        // the
                                        // string
                                        // value?
                                    }
                                    object.eSet(eStructuralFeature, x);
                                } else if (eStructuralFeature instanceof EReference) {
                                    if (eStructuralFeature.getName().equals("GlobalId")) {
                                        IfcGloballyUniqueId globallyUniqueId = Ifc2x3tc1Factory.eINSTANCE
                                                .createIfcGloballyUniqueId();
                                        globallyUniqueId.setWrappedValue(jsonReader.nextString());
                                        object.eSet(eStructuralFeature, globallyUniqueId);
                                    } else if (embedded) {
                                        jsonReader.beginObject();
                                        if (jsonReader.nextName().equals("__type")) {
                                            String t = jsonReader.nextString();
                                            IdEObject wrappedObject = (IdEObject) Ifc2x3tc1Factory.eINSTANCE
                                                    .create((EClass) Ifc2x3tc1Package.eINSTANCE
                                                            .getEClassifier(t));
                                            if (jsonReader.nextName().equals("value")) {
                                                EStructuralFeature wv = wrappedObject.eClass()
                                                        .getEStructuralFeature("wrappedValue");
                                                wrappedObject.eSet(wv, readPrimitive(jsonReader, wv));
                                                object.eSet(eStructuralFeature, wrappedObject);
                                            } else {
                                                // error
                                            }
                                        }
                                        jsonReader.endObject();
                                    } else {
                                        waitingList.add(jsonReader.nextLong(),
                                                new SingleWaitingObject(object, eStructuralFeature));
                                    }
                                }
                            }
                        }
                        if (waitingList.containsKey(oid)) {
                            waitingList.updateNode(oid, eClass, object);
                        }
                    }
                }
                jsonReader.endObject();
            }
            jsonReader.endArray();
        }
        jsonReader.endObject();
    } catch (IOException e1) {
        e1.printStackTrace();
    } catch (IfcModelInterfaceException e1) {
        e1.printStackTrace();
    } finally {
        try {
            jsonReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return model;
}

From source file:org.bimserver.emf.SharedJsonDeserializer.java

License:Open Source License

@SuppressWarnings("rawtypes")
public IfcModelInterface read(InputStream in, IfcModelInterface model, boolean checkWaitingList)
        throws DeserializeException {
    if (model.getPackageMetaData().getSchemaDefinition() == null) {
        throw new DeserializeException("No SchemaDefinition available");
    }/* w  w w.j av a 2 s  .c o m*/
    WaitingList<Long> waitingList = new WaitingList<Long>();
    final boolean log = false;
    if (log) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            IOUtils.copy(in, baos);
            File file = new File("debug.json");
            System.out.println(file.getAbsolutePath());
            FileUtils.writeByteArrayToFile(file, baos.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        in = new ByteArrayInputStream(baos.toByteArray());
    }
    JsonReader jsonReader = new JsonReader(new InputStreamReader(in, Charsets.UTF_8));
    int nrObjects = 0;
    try {
        JsonToken peek = jsonReader.peek();
        if (peek != null && peek == JsonToken.BEGIN_OBJECT) {
            jsonReader.beginObject();
            peek = jsonReader.peek();
            while (peek == JsonToken.NAME) {
                String nextName = jsonReader.nextName();
                if (nextName.equals("objects")) {
                    jsonReader.beginArray();
                    while (jsonReader.hasNext()) {
                        nrObjects++;
                        processObject(model, waitingList, jsonReader, null);
                    }
                    jsonReader.endArray();
                } else if (nextName.equals("header")) {
                    IfcHeader ifcHeader = (IfcHeader) processObject(model, waitingList, jsonReader,
                            StorePackage.eINSTANCE.getIfcHeader());
                    model.getModelMetaData().setIfcHeader(ifcHeader);
                }
                peek = jsonReader.peek();
            }
            jsonReader.endObject();
        }
    } catch (IOException e) {
        LOGGER.error("", e);
    } catch (IfcModelInterfaceException e) {
        LOGGER.error("", e);
    } finally {
        LOGGER.info("# Objects: " + nrObjects);
        try {
            jsonReader.close();
        } catch (IOException e) {
            LOGGER.error("", e);
        }
    }
    boolean checkUnique = false;
    if (checkUnique) {
        for (IdEObject idEObject : model.getValues()) {
            for (EStructuralFeature eStructuralFeature : idEObject.eClass().getEAllStructuralFeatures()) {
                Object value = idEObject.eGet(eStructuralFeature);
                if (eStructuralFeature instanceof EReference) {
                    if (eStructuralFeature.isMany()) {
                        List list = (List) value;
                        if (eStructuralFeature.isUnique()) {
                            Set<Object> t = new HashSet<>();
                            for (Object v : list) {
                                if (t.contains(v)) {
                                    //                           LOGGER.error("NOT UNIQUE " + idEObject.eClass().getName() + "." + eStructuralFeature.getName());
                                }
                                t.add(v);
                            }
                        }
                    }
                }
            }
        }
    }
    if (checkWaitingList && waitingList.size() > 0) {
        try {
            waitingList.dumpIfNotEmpty();
        } catch (BimServerClientException e) {
            e.printStackTrace();
        }
        throw new DeserializeException("Waitinglist should be empty (" + waitingList.size() + ")");
    }
    return model;
}