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

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

Introduction

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

Prototype

public JsonReader(Reader in) 

Source Link

Document

Creates a new instance that reads a JSON-encoded stream from in .

Usage

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

License:Open Source License

public long checkin(String baseAddress, String token, long poid, String comment, long deserializerOid,
        boolean merge, Flow flow, long fileSize, String filename, InputStream inputStream)
        throws ServerException, UserException {
    String address = baseAddress + "/upload";
    HttpPost httppost = new HttpPost(address);
    try {//from  ww w .  j  av  a 2 s .  c  o m
        Long topicId = getServiceInterface().initiateCheckin(poid, deserializerOid);
        // TODO find some GzipInputStream variant that _compresses_ instead of _decompresses_ using deflate for now
        InputStreamBody data = new InputStreamBody(new DeflaterInputStream(inputStream), filename);

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

        multipartEntityBuilder.addPart("topicId", new StringBody("" + topicId, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("token", new StringBody(token, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("deserializerOid",
                new StringBody("" + deserializerOid, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("merge", new StringBody("" + merge, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("poid", new StringBody("" + poid, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("comment", new StringBody("" + comment, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("sync",
                new StringBody("" + (flow == Flow.SYNC), ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("compression", new StringBody("deflate", ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("data", data);

        httppost.setEntity(multipartEntityBuilder.build());

        HttpResponse httpResponse = closeableHttpClient.execute(httppost);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            JsonParser jsonParser = new JsonParser();
            InputStreamReader in = new InputStreamReader(httpResponse.getEntity().getContent());
            try {
                JsonElement result = jsonParser.parse(new JsonReader(in));
                if (result instanceof JsonObject) {
                    JsonObject jsonObject = (JsonObject) result;
                    if (jsonObject.has("exception")) {
                        JsonObject exceptionJson = jsonObject.get("exception").getAsJsonObject();
                        String exceptionType = exceptionJson.get("__type").getAsString();
                        String message = exceptionJson.has("message")
                                ? exceptionJson.get("message").getAsString()
                                : "unknown";
                        if (exceptionType.equals(UserException.class.getSimpleName())) {
                            throw new UserException(message);
                        } else if (exceptionType.equals(ServerException.class.getSimpleName())) {
                            throw new ServerException(message);
                        }
                    } else {
                        if (jsonObject.has("topicId")) {
                            return jsonObject.get("topicId").getAsLong();
                        } else {
                            throw new ServerException("No topicId found in response: " + jsonObject.toString());
                        }
                    }
                }
            } finally {
                in.close();
            }
        }
    } catch (ClientProtocolException e) {
        throw new ServerException(e);
    } catch (IOException e) {
        throw new ServerException(e);
    } catch (PublicInterfaceNotFoundException e) {
        throw new ServerException(e);
    } finally {
        httppost.releaseConnection();
    }
    return -1;
}

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 . ja v  a  2 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  w  w  w  .j  av 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.client.notifications.WebSocketImpl.java

License:Open Source License

@OnWebSocketMessage
public void onMessage(String msg) {
    try {/*from w w w  .  j  a  v a2 s .  com*/
        System.out.println(msg);
        JsonReader jsonReader = new JsonReader(new StringReader(msg));
        JsonParser parser = new JsonParser();
        JsonElement parse = parser.parse(jsonReader);
        if (parse instanceof JsonObject) {
            JsonObject object = (JsonObject) parse;
            if (object.has("welcome")) {
                String token = socketNotificationsClient.getBimServerClient().getToken();
                session.getRemote().sendString("{\"token\":\"" + token + "\"}");
            } else if (object.has("endpointid")) {
                socketNotificationsClient.setEndpointId(object.get("endpointid").getAsLong());
                countDownLatch.countDown();
            } else {
                try {
                    socketNotificationsClient.handleIncoming(object.get("request").getAsJsonObject());
                } catch (UserException e) {
                    LOGGER.error("", e);
                } catch (ConvertException e) {
                    LOGGER.error("", e);
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("", e);
    }
}

From source file:org.bimserver.collada.OpenGLTransmissionFormatSerializer.java

License:Open Source License

private JsonElement readFileAsJSON(File expectedOutputFile) {
    String result;/*  ww w .ja  v a2  s.  com*/
    try {
        result = FileUtils.readFileToString(expectedOutputFile);
    } catch (IOException e) {
        // Something bad happened, but send something readable to the next step anyway.
        result = "{}";
        e.printStackTrace();
    }
    // Parse the existing file.
    JsonParser parser = new JsonParser();
    JsonReader reader = new JsonReader(new StringReader(result));
    reader.setLenient(true);
    JsonElement root = parser.parse(reader);
    // Send root back.
    return root;
}

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

License:Open Source License

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

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

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

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

License:Open Source License

@SuppressWarnings("rawtypes")
public IfcModelInterface read(InputStream in, IfcModelInterface model, boolean checkWaitingList)
        throws DeserializeException {
    if (model.getPackageMetaData().getSchemaDefinition() == null) {
        throw new DeserializeException("No SchemaDefinition available");
    }//from w  w  w . j av  a2 s  .co 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;
}

From source file:org.bimserver.servlets.JsonApiServlet.java

License:Open Source License

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getHeader("Origin") != null
            && (getBimServer().getServerInfo().getServerState() != ServerState.MIGRATION_REQUIRED
                    && !getBimServer().getServerSettingsCache().isHostAllowed(request.getHeader("Origin")))) {
        response.setStatus(403);/*from   w w  w  .  j a v a 2 s  .  co  m*/
        return;
    }
    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setCharacterEncoding("UTF-8");
    try {
        ServletInputStream inputStream = request.getInputStream();
        byte[] bytes = IOUtils.toByteArray(inputStream); // Not streaming here, because we want to be able to show the request-data when it's not valid
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Incoming JSON " + new String(bytes, Charsets.UTF_8));
        }
        JsonReader jsonReader = new JsonReader(
                new InputStreamReader(new ByteArrayInputStream(bytes), Charsets.UTF_8));
        JsonParser parser = new JsonParser();
        JsonElement parse = parser.parse(jsonReader);
        if (parse instanceof JsonObject) {
            JsonObject jsonRequest = (JsonObject) parse;
            response.setHeader("Content-Type", "application/json");
            getBimServer().getJsonHandler().execute(jsonRequest, request, response.getWriter());
        } else {
            LOGGER.error("Invalid JSON request: " + new String(bytes, Charsets.UTF_8));
            response.setStatus(500);
        }
    } catch (IOException e) {
        LOGGER.error("", e);
        response.setStatus(500);
    }
}

From source file:org.blockartistry.mod.DynSurround.util.JsonUtils.java

License:MIT License

public static <T> T load(final Reader stream, final Class<T> clazz) {

    T result = null;/*from   w ww .  java  2s . c  o m*/
    try (final JsonReader reader = new JsonReader(stream)) {
        result = new Gson().fromJson(reader, clazz);
    } catch (final Throwable t) {
        ModLog.error("Unable to process Json from stream", t);
        ;
    }
    return result;
}

From source file:org.blockartistry.mod.ThermalRecycling.support.ItemDefinitions.java

License:MIT License

public static ItemDefinitions load(final String modId) {
    final String fileName = modId.replaceAll("[^a-zA-Z0-9.-]", "_");
    InputStream stream = null;//from  www.jav a 2  s  .c o m
    InputStreamReader reader = null;
    JsonReader reader2 = null;
    try {
        stream = ItemDefinitions.class.getResourceAsStream("/assets/recycling/data/" + fileName + ".json");
        if (stream != null) {
            reader = new InputStreamReader(stream);
            reader2 = new JsonReader(reader);
            return (ItemDefinitions) new Gson().fromJson(reader, ItemDefinitions.class);
        }
    } finally {
        try {
            if (reader2 != null)
                reader2.close();
            if (reader != null)
                reader.close();
            if (stream != null)
                stream.close();
        } catch (final Exception e) {
            ;
        }
    }
    return new ItemDefinitions();
}