List of usage examples for com.google.gson.stream JsonReader nextName
public String nextName() throws IOException
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();//w ww .j a va2 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;//from ww w . j a v a2 s . c o 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 {/* www.ja va 2s. 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//from w w w .j a va2s . c om 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 www. j a v a 2s. 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// www.j a v a2 s. 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 ww . java2 s. c o m*/ InputStream downloadData = bimServerClient.getDownloadData(download, getIfcSerializerOid()); boolean log = false; // TODO Make this streaming again, make sure the EmfSerializer getInputStream method is working properly if (log) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (downloadData instanceof SerializerInputstream) { SerializerInputstream serializerInputStream = (SerializerInputstream) downloadData; serializerInputStream.getEmfSerializer().writeToOutputStream(baos); } else { IOUtils.copy((InputStream) downloadData, baos); } FileOutputStream fos = new FileOutputStream(new File(download + ".json")); IOUtils.write(baos.toByteArray(), fos); fos.close(); downloadData = new ByteArrayInputStream(baos.toByteArray()); } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (downloadData instanceof SerializerInputstream) { SerializerInputstream serializerInputStream = (SerializerInputstream) downloadData; serializerInputStream.getEmfSerializer().writeToOutputStream(baos); } else { IOUtils.copy((InputStream) downloadData, baos); } downloadData = new ByteArrayInputStream(baos.toByteArray()); } JsonReader jsonReader = new JsonReader(new InputStreamReader(downloadData, Charsets.UTF_8)); try { jsonReader.beginObject(); if (jsonReader.nextName().equals("objects")) { jsonReader.beginArray(); while (jsonReader.hasNext()) { jsonReader.beginObject(); if (jsonReader.nextName().equals("__oid")) { long oid = jsonReader.nextLong(); if (jsonReader.nextName().equals("__type")) { String type = jsonReader.nextString(); EClass eClass = (EClass) Ifc2x3tc1Package.eINSTANCE.getEClassifier(type); if (eClass == null) { throw new BimServerClientException("No class found with name " + type); } if (jsonReader.nextName().equals("__state")) { String state = jsonReader.nextString(); IdEObject object = null; if (containsNoFetch(oid)) { object = getNoFetch(oid); } else { object = (IdEObject) Ifc2x3tc1Factory.eINSTANCE.create(eClass); ((IdEObjectImpl) object).eSetStore(eStore); ((IdEObjectImpl) object).setOid(oid); add(oid, object); } if (state.equals("NOT_LOADED")) { ((IdEObjectImpl) object).setLoadingState(State.TO_BE_LOADED); } else { while (jsonReader.hasNext()) { String featureName = jsonReader.nextName(); boolean embedded = false; if (featureName.startsWith("__ref")) { featureName = featureName.substring(5); } else if (featureName.startsWith("__emb")) { embedded = true; featureName = featureName.substring(5); } EStructuralFeature eStructuralFeature = eClass .getEStructuralFeature(featureName); if (eStructuralFeature == null) { throw new BimServerClientException("Unknown field (" + featureName + ") on class " + eClass.getName()); } if (eStructuralFeature.isMany()) { jsonReader.beginArray(); if (eStructuralFeature instanceof EAttribute) { List list = (List) object.eGet(eStructuralFeature); List<String> stringList = null; if (eStructuralFeature.getEType() == EcorePackage.eINSTANCE .getEDoubleObject() || eStructuralFeature .getEType() == EcorePackage.eINSTANCE .getEDouble()) { EStructuralFeature asStringFeature = eClass .getEStructuralFeature( eStructuralFeature.getName() + "AsString"); stringList = (List<String>) object.eGet(asStringFeature); } while (jsonReader.hasNext()) { Object e = readPrimitive(jsonReader, eStructuralFeature); list.add(e); if (eStructuralFeature.getEType() == EcorePackage.eINSTANCE .getEDouble()) { double val = (Double) e; stringList.add("" + val); // TODO this is losing precision, maybe also send the string value? } } } else if (eStructuralFeature instanceof EReference) { int index = 0; while (jsonReader.hasNext()) { if (embedded) { List list = (List) object.eGet(eStructuralFeature); jsonReader.beginObject(); String n = jsonReader.nextName(); if (n.equals("__type")) { String t = jsonReader.nextString(); IdEObject wrappedObject = (IdEObject) Ifc2x3tc1Factory.eINSTANCE .create((EClass) Ifc2x3tc1Package.eINSTANCE .getEClassifier(t)); if (jsonReader.nextName().equals("value")) { EStructuralFeature wv = wrappedObject.eClass() .getEStructuralFeature("wrappedValue"); wrappedObject.eSet(wv, readPrimitive(jsonReader, wv)); list.add(wrappedObject); } else { // error } } else if (n.equals("oid")) { // Sometimes embedded is true, bot also referenced are included, those are always embdedded in an object long refOid = jsonReader.nextLong(); if (containsNoFetch(refOid)) { IdEObject refObj = getNoFetch(refOid); AbstractEList l = (AbstractEList) object .eGet(eStructuralFeature); while (l.size() <= index) { l.addUnique(refObj.eClass().getEPackage() .getEFactoryInstance() .create(refObj.eClass())); } l.setUnique(index, refObj); } else { waitingList.add(refOid, new ListWaitingObject( object, eStructuralFeature, index)); } } jsonReader.endObject(); } else { long refOid = jsonReader.nextLong(); if (containsNoFetch(refOid)) { IdEObject refObj = getNoFetch(refOid); AbstractEList l = (AbstractEList) object .eGet(eStructuralFeature); while (l.size() <= index) { l.addUnique(refObj.eClass().getEPackage() .getEFactoryInstance() .create(refObj.eClass())); } l.setUnique(index, refObj); } else { waitingList.add(refOid, new ListWaitingObject( object, eStructuralFeature, index)); } index++; } } } jsonReader.endArray(); } else { if (eStructuralFeature instanceof EAttribute) { Object x = readPrimitive(jsonReader, eStructuralFeature); if (eStructuralFeature.getEType() == EcorePackage.eINSTANCE .getEDouble()) { EStructuralFeature asStringFeature = object.eClass() .getEStructuralFeature( eStructuralFeature.getName() + "AsString"); object.eSet(asStringFeature, "" + x); // TODO this is losing precision, maybe also send the string value? } object.eSet(eStructuralFeature, x); } else if (eStructuralFeature instanceof EReference) { if (embedded) { jsonReader.beginObject(); if (jsonReader.nextName().equals("__type")) { String t = jsonReader.nextString(); IdEObject wrappedObject = (IdEObject) Ifc2x3tc1Factory.eINSTANCE .create((EClass) Ifc2x3tc1Package.eINSTANCE .getEClassifier(t)); if (jsonReader.nextName().equals("value")) { EStructuralFeature wv = wrappedObject.eClass() .getEStructuralFeature("wrappedValue"); wrappedObject.eSet(wv, readPrimitive(jsonReader, wv)); object.eSet(eStructuralFeature, wrappedObject); } else { // error } } jsonReader.endObject(); } else { long refOid = jsonReader.nextLong(); if (containsNoFetch(refOid)) { IdEObject refObj = getNoFetch(refOid); object.eSet(eStructuralFeature, refObj); } else { waitingList.add(refOid, new SingleWaitingObject(object, eStructuralFeature)); } } } } } } if (waitingList.containsKey(oid)) { try { waitingList.updateNode(oid, eClass, object); } catch (DeserializeException e) { LOGGER.error("", e); } } } } } jsonReader.endObject(); } jsonReader.endArray(); } jsonReader.endObject(); } catch (IfcModelInterfaceException e1) { LOGGER.error("", e1); } finally { jsonReader.close(); } } catch (IOException e) { LOGGER.error("", e); } catch (SerializerException e) { LOGGER.error("", e); } finally { waitingList.dumpIfNotEmpty(); bimServerClient.getServiceInterface().cleanupLongAction(download); } }
From source file:org.bimserver.client.ClientIfcModel.java
License:Open Source License
@SuppressWarnings({ "unused", "resource" }) public void getGeometry(IfcProduct ifcProduct) { try {/*from www . ja v a 2s .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 ww. j a v a2s .com public IfcModelInterface read(InputStream in, String filename, long fileSize) throws DeserializeException { IfcModelInterface model = new IfcModel(); WaitingList<Long> waitingList = new WaitingList<Long>(); JsonReader jsonReader = new JsonReader(new InputStreamReader(in)); try { jsonReader.beginObject(); if (jsonReader.nextName().equals("objects")) { jsonReader.beginArray(); while (jsonReader.hasNext()) { jsonReader.beginObject(); if (jsonReader.nextName().equals("__oid")) { long oid = jsonReader.nextLong(); if (jsonReader.nextName().equals("__type")) { String type = jsonReader.nextString(); EClass eClass = (EClass) Ifc2x3tc1Package.eINSTANCE.getEClassifier(type); if (eClass == null) { throw new DeserializeException("No class found with name " + type); } IdEObject object = (IdEObject) Ifc2x3tc1Factory.eINSTANCE.create(eClass); // ((IdEObjectImpl) object).setDelegate(new // ClientDelegate(this, object, null)); ((IdEObjectImpl) object).setOid(oid); model.add(object.getOid(), object); while (jsonReader.hasNext()) { String featureName = jsonReader.nextName(); boolean embedded = false; if (featureName.startsWith("__ref")) { featureName = featureName.substring(5); } else if (featureName.startsWith("__emb")) { embedded = true; featureName = featureName.substring(5); } EStructuralFeature eStructuralFeature = eClass.getEStructuralFeature(featureName); if (eStructuralFeature == null) { throw new DeserializeException( "Unknown field (" + featureName + ") on class " + eClass.getName()); } if (eStructuralFeature.isMany()) { jsonReader.beginArray(); if (eStructuralFeature instanceof EAttribute) { List list = (List) object.eGet(eStructuralFeature); List<String> stringList = null; if (eStructuralFeature.getEType() == EcorePackage.eINSTANCE .getEDoubleObject() || eStructuralFeature.getEType() == EcorePackage.eINSTANCE .getEDouble()) { EStructuralFeature asStringFeature = eClass.getEStructuralFeature( eStructuralFeature.getName() + "AsString"); stringList = (List<String>) object.eGet(asStringFeature); } while (jsonReader.hasNext()) { Object e = readPrimitive(jsonReader, eStructuralFeature); list.add(e); if (eStructuralFeature.getEType() == EcorePackage.eINSTANCE .getEDouble()) { double val = (Double) e; stringList.add("" + val); // TODO // this // is // losing // precision, // maybe // also // send // the // string // value? } } } else if (eStructuralFeature instanceof EReference) { int index = 0; while (jsonReader.hasNext()) { if (embedded) { List list = (List) object.eGet(eStructuralFeature); jsonReader.beginObject(); if (jsonReader.nextName().equals("__type")) { String t = jsonReader.nextString(); IdEObject wrappedObject = (IdEObject) Ifc2x3tc1Factory.eINSTANCE .create((EClass) Ifc2x3tc1Package.eINSTANCE .getEClassifier(t)); if (jsonReader.nextName().equals("value")) { EStructuralFeature wv = wrappedObject.eClass() .getEStructuralFeature("wrappedValue"); wrappedObject.eSet(wv, readPrimitive(jsonReader, wv)); list.add(wrappedObject); } else { // error } } jsonReader.endObject(); } else { long refOid = jsonReader.nextLong(); waitingList.add(refOid, new ListWaitingObject(object, eStructuralFeature, index)); index++; } } } jsonReader.endArray(); } else { if (eStructuralFeature instanceof EAttribute) { Object x = readPrimitive(jsonReader, eStructuralFeature); if (eStructuralFeature.getEType() == EcorePackage.eINSTANCE.getEDouble()) { EStructuralFeature asStringFeature = object.eClass() .getEStructuralFeature( eStructuralFeature.getName() + "AsString"); object.eSet(asStringFeature, "" + x); // TODO // this // is // losing // precision, // maybe // also // send // the // string // value? } object.eSet(eStructuralFeature, x); } else if (eStructuralFeature instanceof EReference) { if (eStructuralFeature.getName().equals("GlobalId")) { IfcGloballyUniqueId globallyUniqueId = Ifc2x3tc1Factory.eINSTANCE .createIfcGloballyUniqueId(); globallyUniqueId.setWrappedValue(jsonReader.nextString()); object.eSet(eStructuralFeature, globallyUniqueId); } else if (embedded) { jsonReader.beginObject(); if (jsonReader.nextName().equals("__type")) { String t = jsonReader.nextString(); IdEObject wrappedObject = (IdEObject) Ifc2x3tc1Factory.eINSTANCE .create((EClass) Ifc2x3tc1Package.eINSTANCE .getEClassifier(t)); if (jsonReader.nextName().equals("value")) { EStructuralFeature wv = wrappedObject.eClass() .getEStructuralFeature("wrappedValue"); wrappedObject.eSet(wv, readPrimitive(jsonReader, wv)); object.eSet(eStructuralFeature, wrappedObject); } else { // error } } jsonReader.endObject(); } else { waitingList.add(jsonReader.nextLong(), new SingleWaitingObject(object, eStructuralFeature)); } } } } if (waitingList.containsKey(oid)) { waitingList.updateNode(oid, eClass, object); } } } jsonReader.endObject(); } jsonReader.endArray(); } jsonReader.endObject(); } catch (IOException e1) { e1.printStackTrace(); } catch (IfcModelInterfaceException e1) { e1.printStackTrace(); } finally { try { jsonReader.close(); } catch (IOException e) { e.printStackTrace(); } } return model; }
From source file:org.bimserver.emf.SharedJsonDeserializer.java
License:Open Source License
@SuppressWarnings("rawtypes") public IfcModelInterface read(InputStream in, IfcModelInterface model, boolean checkWaitingList) throws DeserializeException { if (model.getPackageMetaData().getSchemaDefinition() == null) { throw new DeserializeException("No SchemaDefinition available"); }/* w w w. ja va2s . c o m*/ WaitingList<Long> waitingList = new WaitingList<Long>(); final boolean log = false; if (log) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { IOUtils.copy(in, baos); File file = new File("debug.json"); System.out.println(file.getAbsolutePath()); FileUtils.writeByteArrayToFile(file, baos.toByteArray()); } catch (IOException e) { e.printStackTrace(); } in = new ByteArrayInputStream(baos.toByteArray()); } JsonReader jsonReader = new JsonReader(new InputStreamReader(in, Charsets.UTF_8)); int nrObjects = 0; try { JsonToken peek = jsonReader.peek(); if (peek != null && peek == JsonToken.BEGIN_OBJECT) { jsonReader.beginObject(); peek = jsonReader.peek(); while (peek == JsonToken.NAME) { String nextName = jsonReader.nextName(); if (nextName.equals("objects")) { jsonReader.beginArray(); while (jsonReader.hasNext()) { nrObjects++; processObject(model, waitingList, jsonReader, null); } jsonReader.endArray(); } else if (nextName.equals("header")) { IfcHeader ifcHeader = (IfcHeader) processObject(model, waitingList, jsonReader, StorePackage.eINSTANCE.getIfcHeader()); model.getModelMetaData().setIfcHeader(ifcHeader); } peek = jsonReader.peek(); } jsonReader.endObject(); } } catch (IOException e) { LOGGER.error("", e); } catch (IfcModelInterfaceException e) { LOGGER.error("", e); } finally { LOGGER.info("# Objects: " + nrObjects); try { jsonReader.close(); } catch (IOException e) { LOGGER.error("", e); } } boolean checkUnique = false; if (checkUnique) { for (IdEObject idEObject : model.getValues()) { for (EStructuralFeature eStructuralFeature : idEObject.eClass().getEAllStructuralFeatures()) { Object value = idEObject.eGet(eStructuralFeature); if (eStructuralFeature instanceof EReference) { if (eStructuralFeature.isMany()) { List list = (List) value; if (eStructuralFeature.isUnique()) { Set<Object> t = new HashSet<>(); for (Object v : list) { if (t.contains(v)) { // LOGGER.error("NOT UNIQUE " + idEObject.eClass().getName() + "." + eStructuralFeature.getName()); } t.add(v); } } } } } } } if (checkWaitingList && waitingList.size() > 0) { try { waitingList.dumpIfNotEmpty(); } catch (BimServerClientException e) { e.printStackTrace(); } throw new DeserializeException("Waitinglist should be empty (" + waitingList.size() + ")"); } return model; }