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

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

Introduction

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

Prototype

public void beginObject() throws IOException 

Source Link

Document

Consumes the next token from the JSON stream and asserts that it is the beginning of a new object.

Usage

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

License:Apache License

private void parseMessage(final JsonReader reader, final ODataErrorContext errorContext)
        throws IOException, EntityProviderException {

    reader.beginObject();
    boolean valueFound = false;
    boolean langFound = false;
    String currentName;//from  ww w.jav  a 2 s  .co m

    while (reader.hasNext()) {
        currentName = reader.nextName();
        if (FormatJson.LANG.equals(currentName)) {
            langFound = true;
            String langValue = getValue(reader);
            if (langValue != null) {
                errorContext.setLocale(getLocale(langValue));
            }
        } else if (FormatJson.VALUE.equals(currentName)) {
            valueFound = true;
            errorContext.setMessage(getValue(reader));
        } else {
            throw new EntityProviderException(EntityProviderException.INVALID_STATE
                    .addContent("Invalid name '" + currentName + "' found."));
        }
    }

    if (!langFound) {
        throw new EntityProviderException(
                EntityProviderException.MISSING_PROPERTY.addContent("Mandatory 'lang' property not found.'"));
    }
    if (!valueFound) {
        throw new EntityProviderException(
                EntityProviderException.MISSING_PROPERTY.addContent("Mandatory 'value' property not found.'"));
    }
    reader.endObject();
}

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

License:Apache License

public Map<String, Object> readPropertyStandalone(final JsonReader reader, final EdmProperty property,
        final EntityProviderReadProperties readProperties) throws EntityProviderException {
    try {//from   w  w w  .j a  v a2s .  c om
        EntityPropertyInfo entityPropertyInfo = EntityInfoAggregator.create(property);
        Map<String, Object> typeMappings = readProperties == null ? null : readProperties.getTypeMappings();
        Map<String, Object> result = new HashMap<String, Object>();

        reader.beginObject();
        String nextName = reader.nextName();
        if (FormatJson.D.equals(nextName)) {
            reader.beginObject();
            nextName = reader.nextName();
            handleName(reader, typeMappings, entityPropertyInfo, readProperties, result, nextName);
            reader.endObject();
        } else {
            handleName(reader, typeMappings, entityPropertyInfo, readProperties, result, nextName);
        }
        reader.endObject();

        if (reader.peek() != JsonToken.END_DOCUMENT) {
            throw new EntityProviderException(
                    EntityProviderException.END_DOCUMENT_EXPECTED.addContent(reader.peek().toString()));
        }

        return result;
    } catch (final IOException e) {
        throw new EntityProviderException(
                EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e);
    } catch (final IllegalStateException e) {
        throw new EntityProviderException(
                EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e);
    }
}

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

License:Apache License

@SuppressWarnings("unchecked")
private Object readComplexProperty(final JsonReader reader, final EntityComplexPropertyInfo complexPropertyInfo,
        final Object typeMapping, final EntityProviderReadProperties readProperties)
        throws EdmException, EntityProviderException, IOException {
    if (reader.peek().equals(JsonToken.NULL)) {
        reader.nextNull();/*from ww  w  . j a v a2  s .c  om*/
        if ((readProperties == null || readProperties.isValidatingFacets())
                && complexPropertyInfo.isMandatory()) {
            throw new EntityProviderException(
                    EntityProviderException.INVALID_PROPERTY_VALUE.addContent(complexPropertyInfo.getName()));
        }
        return null;
    }

    reader.beginObject();
    Map<String, Object> data = new HashMap<String, Object>();

    Map<String, Object> mapping;
    if (typeMapping != null) {
        if (typeMapping instanceof Map) {
            mapping = (Map<String, Object>) typeMapping;
        } else {
            throw new EntityProviderException(
                    EntityProviderException.INVALID_MAPPING.addContent(complexPropertyInfo.getName()));
        }
    } else {
        mapping = new HashMap<String, Object>();
    }

    while (reader.hasNext()) {
        String childName = reader.nextName();
        if (FormatJson.METADATA.equals(childName)) {
            reader.beginObject();
            childName = reader.nextName();
            if (!FormatJson.TYPE.equals(childName)) {
                throw new EntityProviderException(EntityProviderException.MISSING_ATTRIBUTE
                        .addContent(FormatJson.TYPE).addContent(FormatJson.METADATA));
            }
            String actualTypeName = reader.nextString();
            String expectedTypeName = complexPropertyInfo.getType().getNamespace() + Edm.DELIMITER
                    + complexPropertyInfo.getType().getName();
            if (!expectedTypeName.equals(actualTypeName)) {
                throw new EntityProviderException(EntityProviderException.INVALID_ENTITYTYPE
                        .addContent(expectedTypeName).addContent(actualTypeName));
            }
            reader.endObject();
        } else {
            EntityPropertyInfo childPropertyInfo = complexPropertyInfo.getPropertyInfo(childName);
            if (childPropertyInfo == null) {
                throw new EntityProviderException(
                        EntityProviderException.INVALID_PROPERTY.addContent(childName));
            }
            Object childData = readPropertyValue(reader, childPropertyInfo, mapping.get(childName),
                    readProperties);
            if (data.containsKey(childName)) {
                throw new EntityProviderException(
                        EntityProviderException.DOUBLE_PROPERTY.addContent(childName));
            }
            data.put(childName, childData);
        }
    }
    reader.endObject();
    return data;
}

From source file:org.apache.olingo.odata2.core.ep.util.JsonUtils.java

License:Apache License

public static int startJson(final JsonReader reader) throws EntityProviderException {
    // The enclosing "d" and "results" are optional - so we cannot check for the presence
    // but we have to read over them in case they are present.
    JsonToken token;//  ww  w  . j  a v a 2s  .co  m
    try {
        token = reader.peek();
        int openJsonObjects = 0;
        if (JsonToken.BEGIN_OBJECT == token) {
            reader.beginObject();
            openJsonObjects++;
            token = reader.peek();
            if (JsonToken.NAME == token) {
                String name = reader.nextName();
                if (!("d".equals(name) ^ "results".equals(name))) {
                    // TODO I18N
                    throw new EntityProviderException(EntityProviderException.COMMON,
                            name + " not expected, only d or results");
                }
            }

            token = reader.peek();
            if (JsonToken.BEGIN_OBJECT == token) {
                reader.beginObject();
                openJsonObjects++;
            } else if (JsonToken.BEGIN_ARRAY == token) {
                // TODO I18N
                throw new EntityProviderException(EntityProviderException.COMMON, "Array not expected");
            }
        }

        return openJsonObjects;
    } catch (IOException e) {
        // TODO I18N
        throw new EntityProviderException(EntityProviderException.COMMON, 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 {//  w  w w.  java 2  s .  c  o  m
        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.arl.fjage.remote.ArrayAdapterFactory.java

License:BSD License

@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    final Class<T> rawType = (Class<T>) type.getRawType();
    if (!rawType.isArray())
        return null;
    final Class<?> compType = rawType.getComponentType();
    if (compType == null)
        return null;
    if (!compType.isPrimitive())
        return null;
    if (!compType.equals(byte.class) && !compType.equals(int.class) && !compType.equals(short.class)
            && !compType.equals(long.class) && !compType.equals(float.class) && !compType.equals(double.class))
        return null;
    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
    return new TypeAdapter<T>() {

        @Override//ww  w  .j a va2  s.  c  o m
        public void write(JsonWriter out, T value) throws IOException {
            if (value == null)
                out.nullValue();
            else {
                byte[] data;
                if (compType.equals(byte.class))
                    data = (byte[]) value;
                else {
                    ByteBuffer buf = null;
                    if (compType.equals(int.class)) {
                        buf = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE * ((int[]) value).length)
                                .order(ByteOrder.LITTLE_ENDIAN);
                        buf.asIntBuffer().put((int[]) value);
                    } else if (compType.equals(short.class)) {
                        buf = ByteBuffer.allocate(Short.SIZE / Byte.SIZE * ((short[]) value).length)
                                .order(ByteOrder.LITTLE_ENDIAN);
                        buf.asShortBuffer().put((short[]) value);
                    } else if (compType.equals(long.class)) {
                        buf = ByteBuffer.allocate(Long.SIZE / Byte.SIZE * ((long[]) value).length)
                                .order(ByteOrder.LITTLE_ENDIAN);
                        buf.asLongBuffer().put((long[]) value);
                    } else if (compType.equals(float.class)) {
                        buf = ByteBuffer.allocate(Float.SIZE / Byte.SIZE * ((float[]) value).length)
                                .order(ByteOrder.LITTLE_ENDIAN);
                        buf.asFloatBuffer().put((float[]) value);
                    } else if (compType.equals(double.class)) {
                        buf = ByteBuffer.allocate(Double.SIZE / Byte.SIZE * ((double[]) value).length)
                                .order(ByteOrder.LITTLE_ENDIAN);
                        buf.asDoubleBuffer().put((double[]) value);
                    }
                    data = buf.array();
                }
                if (bare)
                    out.value(Base64.getEncoder().encodeToString(data));
                else {
                    out.beginObject();
                    out.name("clazz").value(rawType.getName());
                    out.name("data").value(Base64.getEncoder().encodeToString(data));
                    out.endObject();
                }
            }
        }

        @Override
        public T read(JsonReader in) throws IOException {
            JsonToken tok = in.peek();
            if (tok == JsonToken.NULL) {
                in.nextNull();
                return null;
            }
            if (tok == JsonToken.STRING)
                return decodeString(in.nextString());
            if (tok == JsonToken.BEGIN_ARRAY)
                return delegate.read(in);
            if (tok != JsonToken.BEGIN_OBJECT)
                return null;
            T rv = null;
            in.beginObject();
            while (in.hasNext()) {
                String name = in.nextName();
                if (name.equals("data"))
                    rv = decodeString(in.nextString());
                else
                    in.skipValue();
            }
            in.endObject();
            return rv;
        }

        private T decodeString(String s) {
            byte[] data = Base64.getDecoder().decode(s);
            if (compType.equals(byte.class))
                return (T) data;
            ByteBuffer buf = ByteBuffer.wrap(data);
            if (compType.equals(int.class)) {
                IntBuffer buf2 = ByteBuffer.wrap(Base64.getDecoder().decode(s)).order(ByteOrder.LITTLE_ENDIAN)
                        .asIntBuffer();
                int[] array = new int[buf2.limit()];
                buf2.get(array);
                return (T) array;
            }
            if (compType.equals(short.class)) {
                ShortBuffer buf2 = ByteBuffer.wrap(Base64.getDecoder().decode(s)).order(ByteOrder.LITTLE_ENDIAN)
                        .asShortBuffer();
                short[] array = new short[buf2.limit()];
                buf2.get(array);
                return (T) array;
            }
            if (compType.equals(long.class)) {
                LongBuffer buf2 = ByteBuffer.wrap(Base64.getDecoder().decode(s)).order(ByteOrder.LITTLE_ENDIAN)
                        .asLongBuffer();
                long[] array = new long[buf2.limit()];
                buf2.get(array);
                return (T) array;
            }
            if (compType.equals(float.class)) {
                FloatBuffer buf2 = ByteBuffer.wrap(Base64.getDecoder().decode(s)).order(ByteOrder.LITTLE_ENDIAN)
                        .asFloatBuffer();
                float[] array = new float[buf2.limit()];
                buf2.get(array);
                return (T) array;
            }
            if (compType.equals(double.class)) {
                DoubleBuffer buf2 = ByteBuffer.wrap(Base64.getDecoder().decode(s))
                        .order(ByteOrder.LITTLE_ENDIAN).asDoubleBuffer();
                double[] array = new double[buf2.limit()];
                buf2.get(array);
                return (T) array;
            }
            return null;
        }

    };
}

From source file:org.arl.fjage.remote.GenericValueAdapterFactory.java

License:BSD License

public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) {
    final Class<T> rawType = (Class<T>) type.getRawType();
    if (!rawType.equals(GenericValue.class))
        return null;
    final GenericValueAdapterFactory parent = this;
    return new TypeAdapter<T>() {

        @Override/*from  ww  w.java2s  .  c o  m*/
        public void write(JsonWriter out, T value) throws IOException {
            if (value == null) {
                out.nullValue();
                return;
            }
            Class type = ((GenericValue) value).getType();
            if (type == null) {
                out.nullValue();
                return;
            }
            if (Number.class.isAssignableFrom(type))
                out.value((Number) ((GenericValue) value).getValue());
            else if (type.equals(String.class))
                out.value((String) ((GenericValue) value).getValue());
            else if (type.equals(Boolean.class))
                out.value((Boolean) ((GenericValue) value).getValue());
            else {
                out.beginObject();
                out.name("clazz").value(type.getName());
                out.name("data");
                TypeAdapter delegate = gson.getAdapter(TypeToken.get(type));
                Object v = ((GenericValue) value).getValue();
                delegate.write(out, v);
                out.endObject();
            }
        }

        @Override
        public T read(JsonReader in) throws IOException {
            JsonToken tok = in.peek();
            if (tok == JsonToken.NULL) {
                in.nextNull();
                return null;
            }
            if (tok == JsonToken.NUMBER) {
                String s = in.nextString();
                try {
                    if (s.contains("."))
                        return (T) new GenericValue(Double.parseDouble(s));
                    else
                        return (T) new GenericValue(Long.parseLong(s));
                } catch (NumberFormatException ex) {
                    return (T) new GenericValue(null);
                }
            }
            if (tok == JsonToken.STRING)
                return (T) new GenericValue(in.nextString());
            if (tok == JsonToken.BOOLEAN)
                return (T) new GenericValue(in.nextBoolean());
            if (tok != JsonToken.BEGIN_OBJECT)
                return null;
            TypeToken tt = null;
            GenericValue rv = null;
            in.beginObject();
            while (in.hasNext()) {
                String name = in.nextName();
                if (name.equals("clazz")) {
                    try {
                        Class<?> cls = Class.forName(in.nextString());
                        tt = TypeToken.get(cls);
                    } catch (Exception ex) {
                        // do nothing
                    }
                } else if (name.equals("data") && tt != null) {
                    TypeAdapter delegate = gson.getAdapter(tt);
                    rv = new GenericValue(delegate.read(in));
                } else
                    in.skipValue();
            }
            in.endObject();
            return (T) rv;
        }

    };
}

From source file:org.arl.fjage.remote.MessageAdapterFactory.java

License:BSD License

@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) {
    final Class<T> rawType = (Class<T>) type.getRawType();
    if (!Message.class.isAssignableFrom(rawType))
        return null;
    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
    final TypeAdapter<Performative> perfDelegate = gson.getAdapter(TypeToken.get(Performative.class));
    final TypeAdapter<AgentID> aidDelegate = gson.getAdapter(TypeToken.get(AgentID.class));
    final TypeAdapter<GenericValue> gvDelegate = gson.getAdapter(TypeToken.get(GenericValue.class));
    final MessageAdapterFactory parent = this;
    return new TypeAdapter<T>() {

        @Override//from   w  w  w.  j a  v a 2s. co  m
        public void write(JsonWriter out, T value) throws IOException {
            if (value == null)
                out.nullValue();
            else {
                out.beginObject();
                out.name("clazz").value(value.getClass().getName());
                out.name("data");
                if (value instanceof GenericMessage) {
                    GenericMessage msg = (GenericMessage) value;
                    out.beginObject();
                    out.name("msgID").value(msg.getMessageID());
                    out.name("inReplyTo").value(msg.getInReplyTo());
                    out.name("perf");
                    perfDelegate.write(out, msg.getPerformative());
                    out.name("recipient");
                    aidDelegate.write(out, msg.getRecipient());
                    out.name("sender");
                    aidDelegate.write(out, msg.getSender());
                    out.name("map");
                    delegate.write(out, value);
                    out.endObject();
                } else
                    delegate.write(out, value);
                out.endObject();
            }
        }

        @Override
        public T read(JsonReader in) throws IOException {
            if (in.peek() == JsonToken.NULL) {
                in.nextNull();
                return null;
            }
            T rv = null;
            Class<?> cls = null;
            in.beginObject();
            while (in.hasNext()) {
                String name = in.nextName();
                if (name.equals("clazz")) {
                    String className = in.nextString();
                    try {
                        cls = classloader != null ? Class.forName(className, true, classloader)
                                : Class.forName(className);
                    } catch (Exception ex) {
                        // do nothing
                    }
                } else if (name.equals("data")) {
                    if (cls == null)
                        rv = delegate.read(in);
                    else if (cls.equals(GenericMessage.class)) {
                        GenericMessage msg = new GenericMessage();
                        in.beginObject();
                        while (in.hasNext()) {
                            String fname = in.nextName();
                            if (fname.equals("msgID"))
                                msg.setMessageID(in.nextString());
                            else if (fname.equals("inReplyTo"))
                                msg.setInReplyTo(in.nextString());
                            else if (fname.equals("perf"))
                                msg.setPerformative(perfDelegate.read(in));
                            else if (fname.equals("recipient"))
                                msg.setRecipient(aidDelegate.read(in));
                            else if (fname.equals("sender"))
                                msg.setSender(aidDelegate.read(in));
                            else if (fname.equals("map")) {
                                in.beginObject();
                                while (in.hasNext()) {
                                    String key = in.nextName();
                                    GenericValue value = gvDelegate.read(in);
                                    msg.put(key, value);
                                }
                                in.endObject();
                            } else
                                in.skipValue();
                        }
                        in.endObject();
                        rv = (T) msg;
                    } else {
                        TypeAdapter<?> delegate1 = gson.getDelegateAdapter(parent, TypeToken.get(cls));
                        rv = (T) delegate1.read(in);
                    }
                } else
                    in.skipValue();
            }
            in.endObject();
            return rv;
        }

    };
}

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 w  w.  j a  va2  s.co  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.client.ClientIfcModel.java

License:Open Source License

@SuppressWarnings({ "unused", "resource" })
public void getGeometry(IfcProduct ifcProduct) {
    try {//  www  .  j a v a2  s .c o  m
        Long downloadByOids = bimServerClient.getBimsie1ServiceInterface().downloadByOids(
                Collections.singleton(roid), Collections.singleton(ifcProduct.getOid()),
                getJsonGeometrySerializerOid(), true, false);
        InputStream downloadData = bimServerClient.getDownloadData(downloadByOids,
                getJsonGeometrySerializerOid());
        JsonReader jsonReader = new JsonReader(new InputStreamReader(downloadData));
        jsonReader.beginObject();
        if (jsonReader.nextName().equals("geometry")) {
            jsonReader.beginArray();
            while (jsonReader.hasNext()) {
                jsonReader.beginObject();
                if (jsonReader.nextName().equals("material")) {
                    String material = jsonReader.nextString();
                    if (jsonReader.nextName().equals("type")) {
                        String type = jsonReader.nextString();
                        if (jsonReader.nextName().equals("coreId")) {
                            String coreid = jsonReader.nextString();
                            if (jsonReader.nextName().equals("primitive")) {
                                String primitive = jsonReader.nextString();
                                if (jsonReader.nextName().equals("positions")) {
                                    jsonReader.beginArray();
                                    while (jsonReader.hasNext()) {
                                        double position = jsonReader.nextDouble();
                                    }
                                    jsonReader.endArray();
                                    if (jsonReader.nextName().equals("normals")) {
                                        jsonReader.beginArray();
                                        while (jsonReader.hasNext()) {
                                            double normal = jsonReader.nextDouble();
                                        }
                                        jsonReader.endArray();
                                        if (jsonReader.nextName().equals("nrindices")) {
                                            int nrindices = jsonReader.nextInt();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                jsonReader.endObject();
            }
            jsonReader.endArray();
        }
        jsonReader.endObject();
    } catch (Exception e) {
        LOGGER.error("", e);
    }
}