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

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

Introduction

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

Prototype

public String nextString() throws IOException 

Source Link

Document

Returns the com.google.gson.stream.JsonToken#STRING string value of the next token, consuming it.

Usage

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  www . j a  v a2s . 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.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 ava  2  s. co 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//from   w ww  .  j a v a2s .  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/* w w  w .j av  a  2  s.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//  w ww .ja v  a 2 s  . c  o  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  ava  2s  .  com*/
        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

private Object readPrimitive(JsonReader jsonReader, EStructuralFeature eStructuralFeature) throws IOException {
    EClassifier eClassifier = eStructuralFeature.getEType();
    if (eClassifier == EcorePackage.eINSTANCE.getEString()) {
        return jsonReader.nextString();
    } else if (eClassifier == EcorePackage.eINSTANCE.getEDouble()
            || eClassifier == EcorePackage.eINSTANCE.getEDoubleObject()) {
        return jsonReader.nextDouble();
    } else if (eClassifier == EcorePackage.eINSTANCE.getEFloat()
            || eClassifier == EcorePackage.eINSTANCE.getEFloatObject()) {
        return (float) jsonReader.nextDouble();
    } else if (eClassifier == EcorePackage.eINSTANCE.getEBoolean()
            || eClassifier == EcorePackage.eINSTANCE.getEBooleanObject()) {
        return jsonReader.nextBoolean();
    } else if (eClassifier == EcorePackage.eINSTANCE.getEInt()
            || eClassifier == EcorePackage.eINSTANCE.getEIntegerObject()) {
        return jsonReader.nextInt();
    } else if (eClassifier == EcorePackage.eINSTANCE.getEEnum()) {
        // TODO DOES THIS EVER HAPPEN??
        if (jsonReader.peek() == JsonToken.BOOLEAN) {
            EEnum eEnum = (EEnum) eStructuralFeature.getEType();
            return eEnum.getEEnumLiteral(("" + jsonReader.nextBoolean()).toUpperCase()).getInstance();
        } else {//from   w w  w. ja va2  s.  com
            EEnum eEnum = (EEnum) eStructuralFeature.getEType();
            return eEnum.getEEnumLiteral(jsonReader.nextString()).getInstance();
        }
    } else if (eClassifier instanceof EClass) {
        throw new RuntimeException();
    } else if (eClassifier == EcorePackage.eINSTANCE.getEByteArray()) {
        return Base64.decodeBase64(jsonReader.nextString().getBytes(Charsets.UTF_8));
    } else if (eClassifier instanceof EEnum) {
        if (jsonReader.peek() == JsonToken.BOOLEAN) {
            EEnum eEnum = (EEnum) eStructuralFeature.getEType();
            return eEnum.getEEnumLiteral(("" + jsonReader.nextBoolean()).toUpperCase()).getInstance();
        } else {
            EEnum eEnum = (EEnum) eStructuralFeature.getEType();
            return eEnum.getEEnumLiteral(jsonReader.nextString()).getInstance();
        }
    } else {
        throw new RuntimeException("Unimplemented type " + eStructuralFeature.getEType().getName());
    }
}

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

License:Open Source License

@SuppressWarnings({ "unused", "resource" })
public void getGeometry(IfcProduct ifcProduct) {
    try {//from  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);
    }
}

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

License:Open Source License

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override//w w  w  .  java 2 s.  c o m
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.deserializers.JsonDeserializer.java

License:Open Source License

private Object readPrimitive(JsonReader jsonReader, EStructuralFeature eStructuralFeature) throws IOException {
    EClassifier eClassifier = eStructuralFeature.getEType();
    if (eClassifier == EcorePackage.eINSTANCE.getEString()) {
        return jsonReader.nextString();
    } else if (eClassifier == EcorePackage.eINSTANCE.getEDouble()) {
        return jsonReader.nextDouble();
    } else if (eClassifier == EcorePackage.eINSTANCE.getEBoolean()) {
        return jsonReader.nextBoolean();
    } else if (eClassifier == EcorePackage.eINSTANCE.getEInt()) {
        return jsonReader.nextInt();
    } else if (eClassifier == EcorePackage.eINSTANCE.getEEnum()) {
        EEnum eEnum = (EEnum) eStructuralFeature.getEType();
        return eEnum.getEEnumLiteral(jsonReader.nextString()).getInstance();
    } else if (eClassifier instanceof EClass) {
        if (eStructuralFeature.getEType().getName().equals("IfcGloballyUniqueId")) {
            IfcGloballyUniqueId ifcGloballyUniqueId = Ifc2x3tc1Factory.eINSTANCE.createIfcGloballyUniqueId();
            ifcGloballyUniqueId.setWrappedValue(jsonReader.nextString());
            return ifcGloballyUniqueId;
        } else {//from  w  w  w .  j ava 2  s .com
            throw new RuntimeException();
        }
    } else if (eClassifier instanceof EEnum) {
        EEnum eEnum = (EEnum) eStructuralFeature.getEType();
        return eEnum.getEEnumLiteral(jsonReader.nextString()).getInstance();
    } else {
        throw new RuntimeException("Unimplemented type " + eStructuralFeature.getEType().getName());
    }
}