Search in sources :

Example 1 with OJSONWriter

use of com.orientechnologies.orient.core.serialization.serializer.OJSONWriter in project orientdb by orientechnologies.

the class OHttpMultipartFileToDiskContentParser method parse.

@Override
public InputStream parse(final OHttpRequest iRequest, final Map<String, String> headers, final OHttpMultipartContentInputStream in, ODatabaseDocument database) throws IOException {
    final StringWriter buffer = new StringWriter();
    final OJSONWriter json = new OJSONWriter(buffer);
    json.beginObject();
    String fileName = headers.get(OHttpUtils.MULTIPART_CONTENT_FILENAME);
    int fileSize = 0;
    if (fileName.charAt(0) == '"')
        fileName = fileName.substring(1);
    if (fileName.charAt(fileName.length() - 1) == '"')
        fileName = fileName.substring(0, fileName.length() - 1);
    fileName = path + fileName;
    if (!overwrite)
        // CHANGE THE FILE NAME TO AVOID OVERWRITING
        if (new File(fileName).exists()) {
            final String fileExt = fileName.substring(fileName.lastIndexOf("."));
            final String fileNoExt = fileName.substring(0, fileName.lastIndexOf("."));
            for (int i = 1; ; ++i) {
                if (!new File(fileNoExt + "_" + i + fileExt).exists()) {
                    fileName = fileNoExt + "_" + i + fileExt;
                    break;
                }
            }
        }
    // WRITE THE FILE
    final OutputStream out = new BufferedOutputStream(new FileOutputStream(fileName.toString()));
    try {
        int b;
        while ((b = in.read()) > -1) {
            out.write(b);
            fileSize++;
        }
    } finally {
        out.flush();
        out.close();
    }
    // FORMAT THE RETURNING DOCUMENT
    json.writeAttribute(1, true, "name", fileName);
    json.writeAttribute(1, true, "type", headers.get(OHttpUtils.MULTIPART_CONTENT_TYPE));
    json.writeAttribute(1, true, "size", fileSize);
    json.endObject();
    return new ByteArrayInputStream(buffer.toString().getBytes());
}
Also used : OJSONWriter(com.orientechnologies.orient.core.serialization.serializer.OJSONWriter)

Example 2 with OJSONWriter

use of com.orientechnologies.orient.core.serialization.serializer.OJSONWriter in project orientdb by orientechnologies.

the class OHttpResponse method writeRecordsOnStream.

private void writeRecordsOnStream(String iFetchPlan, String iFormat, Map<String, Object> iAdditionalProperties, Iterator<Object> it, Writer buffer) throws IOException {
    final OJSONWriter json = new OJSONWriter(buffer, iFormat);
    json.beginObject();
    final String format = iFetchPlan != null ? iFormat + ",fetchPlan:" + iFetchPlan : iFormat;
    // WRITE RECORDS
    json.beginCollection(-1, true, "result");
    formatMultiValue(it, buffer, format);
    json.endCollection(-1, true);
    if (iAdditionalProperties != null) {
        for (Map.Entry<String, Object> entry : iAdditionalProperties.entrySet()) {
            final Object v = entry.getValue();
            if (OMultiValue.isMultiValue(v)) {
                json.beginCollection(-1, true, entry.getKey());
                formatMultiValue(OMultiValue.getMultiValueIterator(v), buffer, format);
                json.endCollection(-1, true);
            } else
                json.writeAttribute(entry.getKey(), v);
            if (Thread.currentThread().isInterrupted())
                break;
        }
    }
    json.endObject();
}
Also used : OJSONWriter(com.orientechnologies.orient.core.serialization.serializer.OJSONWriter)

Example 3 with OJSONWriter

use of com.orientechnologies.orient.core.serialization.serializer.OJSONWriter in project orientdb by orientechnologies.

the class OServerCommandGetClass method execute.

@Override
public boolean execute(final OHttpRequest iRequest, OHttpResponse iResponse) throws Exception {
    String[] urlParts = checkSyntax(iRequest.url, 3, "Syntax error: class/<database>/<class-name>");
    iRequest.data.commandInfo = "Returns the information of a class in the schema";
    iRequest.data.commandDetail = urlParts[2];
    ODatabaseDocument db = null;
    try {
        db = getProfiledDatabaseInstance(iRequest);
        if (db.getMetadata().getSchema().existsClass(urlParts[2])) {
            final OClass cls = db.getMetadata().getSchema().getClass(urlParts[2]);
            final StringWriter buffer = new StringWriter();
            final OJSONWriter json = new OJSONWriter(buffer, OHttpResponse.JSON_FORMAT);
            OServerCommandGetDatabase.exportClass(db, json, cls);
            iResponse.send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_JSON, buffer.toString(), null);
        } else
            iResponse.send(OHttpUtils.STATUS_NOTFOUND_CODE, null, null, null, null);
    } finally {
        if (db != null)
            db.close();
    }
    return false;
}
Also used : StringWriter(java.io.StringWriter) OJSONWriter(com.orientechnologies.orient.core.serialization.serializer.OJSONWriter) ODatabaseDocument(com.orientechnologies.orient.core.db.document.ODatabaseDocument) OClass(com.orientechnologies.orient.core.metadata.schema.OClass)

Example 4 with OJSONWriter

use of com.orientechnologies.orient.core.serialization.serializer.OJSONWriter in project orientdb by orientechnologies.

the class ORecordSerializerJSON method toString.

@Override
public StringBuilder toString(final ORecord iRecord, final StringBuilder iOutput, final String iFormat, final OUserObject2RecordHandler iObjHandler, boolean iOnlyDelta, boolean autoDetectCollectionType) {
    try {
        final StringWriter buffer = new StringWriter(INITIAL_SIZE);
        final OJSONWriter json = new OJSONWriter(buffer, iFormat);
        final FormatSettings settings = new FormatSettings(iFormat);
        json.beginObject();
        OJSONFetchContext context = new OJSONFetchContext(json, settings);
        context.writeSignature(json, iRecord);
        if (iRecord instanceof ODocument) {
            final OFetchPlan fp = OFetchHelper.buildFetchPlan(settings.fetchPlan);
            OFetchHelper.fetch(iRecord, null, fp, new OJSONFetchListener(), context, iFormat);
        } else if (iRecord instanceof ORecordStringable) {
            // STRINGABLE
            final ORecordStringable record = (ORecordStringable) iRecord;
            json.writeAttribute(settings.indentLevel, true, "value", record.value());
        } else if (iRecord instanceof OBlob) {
            // BYTES
            final OBlob record = (OBlob) iRecord;
            json.writeAttribute(settings.indentLevel, true, "value", OBase64Utils.encodeBytes(record.toStream()));
        } else
            throw new OSerializationException("Error on marshalling record of type '" + iRecord.getClass() + "' to JSON. The record type cannot be exported to JSON");
        json.endObject(settings.indentLevel, true);
        iOutput.append(buffer);
        return iOutput;
    } catch (IOException e) {
        throw OException.wrapException(new OSerializationException("Error on marshalling of record to JSON"), e);
    }
}
Also used : OJSONFetchContext(com.orientechnologies.orient.core.fetch.json.OJSONFetchContext) StringWriter(java.io.StringWriter) OJSONWriter(com.orientechnologies.orient.core.serialization.serializer.OJSONWriter) OSerializationException(com.orientechnologies.orient.core.exception.OSerializationException) ORecordStringable(com.orientechnologies.orient.core.record.ORecordStringable) IOException(java.io.IOException) OFetchPlan(com.orientechnologies.orient.core.fetch.OFetchPlan) OJSONFetchListener(com.orientechnologies.orient.core.fetch.json.OJSONFetchListener)

Example 5 with OJSONWriter

use of com.orientechnologies.orient.core.serialization.serializer.OJSONWriter in project orientdb by orientechnologies.

the class OHttpGraphResponse method writeRecords.

public void writeRecords(final Object iRecords, final String iFetchPlan, String iFormat, final String accept, final Map<String, Object> iAdditionalProperties, final String mode) throws IOException {
    if (iRecords == null) {
        send(OHttpUtils.STATUS_OK_NOCONTENT_CODE, "", OHttpUtils.CONTENT_TEXT_PLAIN, null, null);
        return;
    }
    if (!mode.equalsIgnoreCase("graph")) {
        super.writeRecords(iRecords, iFetchPlan, iFormat, accept, iAdditionalProperties, mode);
        return;
    }
    if (accept != null && accept.contains("text/csv"))
        throw new IllegalArgumentException("Graph mode cannot accept '" + accept + "'");
    final OrientGraphNoTx graph = (OrientGraphNoTx) OrientGraphFactory.getNoTxGraphImplFactory().getGraph((ODatabaseDocumentTx) ODatabaseRecordThreadLocal.INSTANCE.get());
    try {
        // DIVIDE VERTICES FROM EDGES
        final Set<OrientVertex> vertices = new HashSet<OrientVertex>();
        final Set<OrientEdge> edges = new HashSet<OrientEdge>();
        final Iterator<Object> iIterator = OMultiValue.getMultiValueIterator(iRecords);
        while (iIterator.hasNext()) {
            Object entry = iIterator.next();
            if (entry == null || !(entry instanceof OIdentifiable))
                // IGNORE IT
                continue;
            entry = ((OIdentifiable) entry).getRecord();
            if (entry == null || !(entry instanceof OIdentifiable))
                // IGNORE IT
                continue;
            if (entry instanceof ODocument) {
                OClass schemaClass = ((ODocument) entry).getSchemaClass();
                if (schemaClass != null && schemaClass.isVertexType())
                    vertices.add(graph.getVertex(entry));
                else if (schemaClass != null && schemaClass.isEdgeType()) {
                    OrientEdge edge = graph.getEdge(entry);
                    vertices.add(graph.getVertex(edge.getVertex(Direction.IN)));
                    vertices.add(graph.getVertex(edge.getVertex(Direction.OUT)));
                    edges.add(edge);
                } else
                    // IGNORE IT
                    continue;
            }
        }
        final StringWriter buffer = new StringWriter();
        final OJSONWriter json = new OJSONWriter(buffer, "");
        json.beginObject();
        json.beginObject("graph");
        // WRITE VERTICES
        json.beginCollection("vertices");
        for (OrientVertex vertex : vertices) {
            json.beginObject();
            json.writeAttribute("@rid", vertex.getIdentity());
            json.writeAttribute("@class", vertex.getRecord().getClassName());
            // ADD ALL THE VERTEX'S EDGES
            for (Edge e : vertex.getEdges(Direction.BOTH)) edges.add((OrientEdge) e);
            // ADD ALL THE PROPERTIES
            for (String field : vertex.getPropertyKeys()) {
                final Object v = vertex.getProperty(field);
                if (v != null)
                    json.writeAttribute(field, v);
            }
            json.endObject();
        }
        json.endCollection();
        // WRITE EDGES
        json.beginCollection("edges");
        for (OrientEdge edge : edges) {
            if (!vertices.contains(edge.getVertex(Direction.OUT)) || !vertices.contains(edge.getVertex(Direction.IN)))
                // ONE OF THE 2 VERTICES ARE NOT PART OF THE RESULT SET: DISCARD IT
                continue;
            json.beginObject();
            json.writeAttribute("@rid", edge.getIdentity());
            json.writeAttribute("@class", edge.getRecord().getClassName());
            json.writeAttribute("out", edge.getVertex(Direction.OUT).getId());
            json.writeAttribute("in", edge.getVertex(Direction.IN).getId());
            for (String field : edge.getPropertyKeys()) {
                final Object v = edge.getProperty(field);
                if (v != null)
                    json.writeAttribute(field, v);
            }
            json.endObject();
        }
        json.endCollection();
        if (iAdditionalProperties != null) {
            for (Map.Entry<String, Object> entry : iAdditionalProperties.entrySet()) {
                final Object v = entry.getValue();
                if (OMultiValue.isMultiValue(v)) {
                    json.beginCollection(-1, true, entry.getKey());
                    formatMultiValue(OMultiValue.getMultiValueIterator(v), buffer, null);
                    json.endCollection(-1, true);
                } else
                    json.writeAttribute(entry.getKey(), v);
                if (Thread.currentThread().isInterrupted())
                    break;
            }
        }
        json.endObject();
        json.endObject();
        send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_JSON, buffer.toString(), null);
    } finally {
        graph.shutdown();
    }
}
Also used : OJSONWriter(com.orientechnologies.orient.core.serialization.serializer.OJSONWriter) ODatabaseDocumentTx(com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx) OrientVertex(com.tinkerpop.blueprints.impls.orient.OrientVertex) OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) OrientEdge(com.tinkerpop.blueprints.impls.orient.OrientEdge) StringWriter(java.io.StringWriter) OClass(com.orientechnologies.orient.core.metadata.schema.OClass) OrientGraphNoTx(com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx) Edge(com.tinkerpop.blueprints.Edge) OrientEdge(com.tinkerpop.blueprints.impls.orient.OrientEdge) Map(java.util.Map) HashSet(java.util.HashSet) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Aggregations

OJSONWriter (com.orientechnologies.orient.core.serialization.serializer.OJSONWriter)11 StringWriter (java.io.StringWriter)9 OClass (com.orientechnologies.orient.core.metadata.schema.OClass)4 IOException (java.io.IOException)4 OStorageEntryConfiguration (com.orientechnologies.orient.core.config.OStorageEntryConfiguration)2 OSecurityAccessException (com.orientechnologies.orient.core.exception.OSecurityAccessException)2 ODocument (com.orientechnologies.orient.core.record.impl.ODocument)2 OCluster (com.orientechnologies.orient.core.storage.OCluster)2 HashSet (java.util.HashSet)2 Map (java.util.Map)2 ODatabaseDocumentInternal (com.orientechnologies.orient.core.db.ODatabaseDocumentInternal)1 ODatabaseDocument (com.orientechnologies.orient.core.db.document.ODatabaseDocument)1 ODatabaseDocumentTx (com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx)1 OIdentifiable (com.orientechnologies.orient.core.db.record.OIdentifiable)1 OCommandExecutionException (com.orientechnologies.orient.core.exception.OCommandExecutionException)1 ODatabaseException (com.orientechnologies.orient.core.exception.ODatabaseException)1 OSerializationException (com.orientechnologies.orient.core.exception.OSerializationException)1 OFetchPlan (com.orientechnologies.orient.core.fetch.OFetchPlan)1 OJSONFetchContext (com.orientechnologies.orient.core.fetch.json.OJSONFetchContext)1 OJSONFetchListener (com.orientechnologies.orient.core.fetch.json.OJSONFetchListener)1