Search in sources :

Example 21 with JsonToken

use of com.google.gson.stream.JsonToken in project airavata by apache.

the class JsonWorkflowParser method readWorkflowInputs.

private void readWorkflowInputs(JsonReader jsonReader) throws ParserException, IOException {
    JsonToken peek = jsonReader.peek();
    InputNode inputNode;
    NodeModel nodeModel;
    ComponentStatus status;
    String name;
    if (peek == JsonToken.NULL) {
        throw new ParserException("Error! workflow inputs can't be null");
    } else if (peek == JsonToken.BEGIN_ARRAY) {
        jsonReader.beginArray();
        while (jsonReader.hasNext()) {
            jsonReader.beginObject();
            nodeModel = new NodeModel();
            status = new ComponentStatus();
            status.setState(ComponentState.CREATED);
            status.setReason("Created");
            nodeModel.setStatus(status);
            inputNode = new InputNodeImpl(nodeModel);
            while (jsonReader.hasNext()) {
                name = jsonReader.nextName();
                if (name.equals(NAME)) {
                    nodeModel.setName(jsonReader.nextString());
                } else if (name.equals(ID)) {
                    nodeModel.setNodeId(jsonReader.nextString());
                } else if (name.equals(DATATYPE)) {
                    inputNode.setDataType(DataType.valueOf(jsonReader.nextString()));
                } else if (name.equals(DESCRIPTION)) {
                    nodeModel.setDescription(jsonReader.nextString());
                } else if (name.equals(POSITION)) {
                    readPosition(jsonReader);
                } else if (name.equals(NODE_ID)) {
                    jsonReader.skipValue();
                // nodeModel.setNodeId(jsonReader.nextString());
                } else if (name.equals(DEFAULT_VALUE)) {
                    inputNode.setValue(jsonReader.nextString());
                } else {
                    jsonReader.skipValue();
                }
            }
            jsonReader.endObject();
            inputs.add(inputNode);
        }
        jsonReader.endArray();
    } else {
        throw new ParserException("Error! Unsupported value for Workflow Inputs, exptected " + getTokenString(JsonToken.BEGIN_OBJECT) + " but found" + getTokenString(peek));
    }
}
Also used : InputNode(org.apache.airavata.workflow.core.dag.nodes.InputNode) NodeModel(org.apache.airavata.model.NodeModel) InputNodeImpl(org.apache.airavata.workflow.core.dag.nodes.InputNodeImpl) ComponentStatus(org.apache.airavata.model.ComponentStatus) JsonToken(com.google.gson.stream.JsonToken)

Example 22 with JsonToken

use of com.google.gson.stream.JsonToken in project gerrit by GerritCodeReview.

the class RestApiServlet method parseRequest.

private Object parseRequest(HttpServletRequest req, Type type) throws IOException, BadRequestException, SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException, MethodNotAllowedException {
    // 400). Consume the request body for all but raw input request types here.
    if (isType(JSON_TYPE, req.getContentType())) {
        try (BufferedReader br = req.getReader();
            JsonReader json = new JsonReader(br)) {
            try {
                json.setLenient(true);
                JsonToken first;
                try {
                    first = json.peek();
                } catch (EOFException e) {
                    throw new BadRequestException("Expected JSON object", e);
                }
                if (first == JsonToken.STRING) {
                    return parseString(json.nextString(), type);
                }
                return OutputFormat.JSON.newGson().fromJson(json, type);
            } finally {
                try {
                    // Reader.close won't consume the rest of the input. Explicitly consume the request
                    // body.
                    br.skip(Long.MAX_VALUE);
                } catch (Exception e) {
                // ignore, e.g. trying to consume the rest of the input may fail if the request was
                // cancelled
                }
            }
        }
    }
    String method = req.getMethod();
    if (("PUT".equals(method) || "POST".equals(method)) && acceptsRawInput(type)) {
        return parseRawInput(req, type);
    }
    if (isDelete(req) && hasNoBody(req)) {
        return null;
    }
    if (hasNoBody(req)) {
        return createInstance(type);
    }
    if (isType(PLAIN_TEXT, req.getContentType())) {
        try (BufferedReader br = req.getReader()) {
            char[] tmp = new char[256];
            StringBuilder sb = new StringBuilder();
            int n;
            while (0 < (n = br.read(tmp))) {
                sb.append(tmp, 0, n);
            }
            return parseString(sb.toString(), type);
        }
    }
    if (isPost(req) && isType(FORM_TYPE, req.getContentType())) {
        return OutputFormat.JSON.newGson().fromJson(ParameterParser.formToJson(req), type);
    }
    throw new BadRequestException("Expected Content-Type: " + JSON_TYPE);
}
Also used : BufferedReader(java.io.BufferedReader) EOFException(java.io.EOFException) JsonReader(com.google.gson.stream.JsonReader) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) JsonToken(com.google.gson.stream.JsonToken) IdString(com.google.gerrit.extensions.restapi.IdString) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) InvalidDeadlineException(com.google.gerrit.server.InvalidDeadlineException) InvocationTargetException(java.lang.reflect.InvocationTargetException) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) PreconditionFailedException(com.google.gerrit.extensions.restapi.PreconditionFailedException) IOException(java.io.IOException) MalformedJsonException(com.google.gson.stream.MalformedJsonException) RequestCancelledException(com.google.gerrit.server.cancellation.RequestCancelledException) ServletException(javax.servlet.ServletException) AuthException(com.google.gerrit.extensions.restapi.AuthException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) EOFException(java.io.EOFException) JsonParseException(com.google.gson.JsonParseException) NotImplementedException(com.google.gerrit.extensions.restapi.NotImplementedException) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) QuotaException(com.google.gerrit.server.quota.QuotaException)

Example 23 with JsonToken

use of com.google.gson.stream.JsonToken in project maple-ir by LLVM-but-worse.

the class JsonTreeReader method nextLong.

@Override
public long nextLong() throws IOException {
    JsonToken token = peek();
    if (token != JsonToken.NUMBER && token != JsonToken.STRING) {
        throw new IllegalStateException("Expected " + JsonToken.NUMBER + " but was " + token);
    }
    long result = ((JsonPrimitive) peekStack()).getAsLong();
    popStack();
    return result;
}
Also used : JsonPrimitive(com.google.gson.JsonPrimitive) JsonToken(com.google.gson.stream.JsonToken)

Example 24 with JsonToken

use of com.google.gson.stream.JsonToken in project maple-ir by LLVM-but-worse.

the class JsonTreeReader method nextDouble.

@Override
public double nextDouble() throws IOException {
    JsonToken token = peek();
    if (token != JsonToken.NUMBER && token != JsonToken.STRING) {
        throw new IllegalStateException("Expected " + JsonToken.NUMBER + " but was " + token);
    }
    double result = ((JsonPrimitive) peekStack()).getAsDouble();
    if (!isLenient() && (Double.isNaN(result) || Double.isInfinite(result))) {
        throw new NumberFormatException("JSON forbids NaN and infinities: " + result);
    }
    popStack();
    return result;
}
Also used : JsonPrimitive(com.google.gson.JsonPrimitive) JsonToken(com.google.gson.stream.JsonToken)

Example 25 with JsonToken

use of com.google.gson.stream.JsonToken in project BIMserver by opensourceBIM.

the class SharedJsonDeserializer method read.

@SuppressWarnings("rawtypes")
public IfcModelInterface read(InputStream in, IfcModelInterface model, boolean checkWaitingList) throws DeserializeException {
    if (model.getPackageMetaData().getSchemaDefinition() == null) {
        throw new DeserializeException(DeserializerErrorCode.INTERNAL_BIMSERVER_ERROR, "No SchemaDefinition available");
    }
    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 BufferedReader(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.debug("# 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(DeserializerErrorCode.NON_EXISTING_ENTITY_REFERENCED, "Waitinglist should be empty (" + waitingList.size() + ")");
    }
    return model;
}
Also used : JsonReader(com.google.gson.stream.JsonReader) JsonToken(com.google.gson.stream.JsonToken) EList(org.eclipse.emf.common.util.EList) AbstractEList(org.eclipse.emf.common.util.AbstractEList) WaitingList(org.bimserver.shared.WaitingList) List(java.util.List) EReference(org.eclipse.emf.ecore.EReference) HashSet(java.util.HashSet) InputStreamReader(java.io.InputStreamReader) EStructuralFeature(org.eclipse.emf.ecore.EStructuralFeature) DeserializeException(org.bimserver.plugins.deserializers.DeserializeException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) BimServerClientException(org.bimserver.shared.exceptions.BimServerClientException) IfcHeader(org.bimserver.models.store.IfcHeader) WaitingList(org.bimserver.shared.WaitingList) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedReader(java.io.BufferedReader) ListWaitingObject(org.bimserver.shared.ListWaitingObject) EObject(org.eclipse.emf.ecore.EObject) File(java.io.File)

Aggregations

JsonToken (com.google.gson.stream.JsonToken)26 JsonReader (com.google.gson.stream.JsonReader)9 IOException (java.io.IOException)6 List (java.util.List)4 JsonPrimitive (com.google.gson.JsonPrimitive)3 InputStreamReader (java.io.InputStreamReader)3 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3 BufferedReader (java.io.BufferedReader)2 PortModel (org.apache.airavata.model.PortModel)2 DeserializeException (org.bimserver.plugins.deserializers.DeserializeException)2 ListWaitingObject (org.bimserver.shared.ListWaitingObject)2 WaitingList (org.bimserver.shared.WaitingList)2 AbstractEList (org.eclipse.emf.common.util.AbstractEList)2 EList (org.eclipse.emf.common.util.EList)2 EObject (org.eclipse.emf.ecore.EObject)2 EReference (org.eclipse.emf.ecore.EReference)2 EStructuralFeature (org.eclipse.emf.ecore.EStructuralFeature)2 ParsingException (org.eclipse.smarthome.automation.parser.ParsingException)2 ParsingNestedException (org.eclipse.smarthome.automation.parser.ParsingNestedException)2