All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.weaverplatform.protocol.WriteOperationParser Maven / Gradle / Ivy

package com.weaverplatform.protocol;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.weaverplatform.protocol.model.*;

import java.io.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.weaverplatform.protocol.model.WriteOperation.WriteOperationAction.*;

/**
 * @author Mohamad Alamili
 */
public class WriteOperationParser {

  protected static final Gson gson;

  static {
    WriteOperationDeserializer deserializer = new WriteOperationDeserializer();

    deserializer.registerAction(CREATE_NODE,                CreateNodeOperation.class);
    deserializer.registerAction(CREATE_ATTRIBUTE,           CreateAttributeOperation.class);
    deserializer.registerAction(CHANGE_ATTRIBUTE_KEY,       ChangeAttributeKeyOperation.class);
    deserializer.registerAction(CREATE_RELATION,            CreateRelationOperation.class);
    deserializer.registerAction(CHANGE_RELATION_KEY,        ChangeRelationKeyOperation.class);
    deserializer.registerAction(REMOVE_NODE,                RemoveNodeOperation.class);
    deserializer.registerAction(REMOVE_NODE_UNRECOVERABLE,  RemoveNodeUnrecoverableOperation.class);
    deserializer.registerAction(REMOVE_ATTRIBUTE,           RemoveAttributeOperation.class);
    deserializer.registerAction(REMOVE_RELATION,            RemoveRelationOperation.class);
    deserializer.registerAction(ADD_TO_SET,                 AddToSetOperation.class);
    deserializer.registerAction(REMOVE_FROM_SET,            RemoveFromSetOperation.class);
    deserializer.registerAction(TRUNCATE_GRAPH,             TruncateGraphOperation.class);
    deserializer.registerAction(CHANGE_NODE_ID,             ChangeNodeIdOperation.class);

    gson = new GsonBuilder()
      .registerTypeAdapter(WriteOperation.class, deserializer)
      .registerTypeAdapter(AttributeValue.class, new AttributeValue.AttributeValueDeserializer())
      .create();
  }

  protected Reader sourceReader;

  protected JsonReader jsonReader = null;

  protected boolean includePayload = false;

  protected String defaultCreator = null;


  public WriteOperationParser(Reader reader) {
    this.sourceReader = reader;
  }

  public WriteOperationParser(InputStream stream) throws UnsupportedEncodingException {
    this.sourceReader = new InputStreamReader(stream, "UTF-8");
  }

  public void includePayload(boolean value) {
    includePayload = value;
  }

  public void setDefaultCreator(String defaultCreator) {
    this.defaultCreator = defaultCreator;
  }

  public static List parse(String writeOperationsJson) throws IOException {
    StringReader reader = new StringReader(writeOperationsJson);
    WriteOperationParser parser = new WriteOperationParser(reader);
    return parser.parseNext(-1);
  }

  /**
   * @param chunkSize number of WriteOperations to return; if -1 all will be returned
   * @return the list is empty if the stream is dried up
   * @throws IOException when the json reader can not iterate through the array
   */
  public List parseNext(int chunkSize) throws IOException {
    if(jsonReader == null) {
      jsonReader = new JsonReader(sourceReader);
      jsonReader.beginArray();
    }

    List list = new ArrayList<>();
    while(jsonReader.hasNext() && (chunkSize == -1 || list.size() < chunkSize)) {
      WriteOperation operation;
      if(includePayload) {
        JsonObject source = JsonParser.parseReader(jsonReader).getAsJsonObject();
        operation = gson.fromJson(source, new TypeToken() {}.getType());
        operation.setPayload(source.toString());
      } else {
        operation = gson.fromJson(jsonReader, new TypeToken() {}.getType());
      }
      if(defaultCreator != null) {
        operation.setUser(defaultCreator);
      }
      list.add(operation);
    }
    return list;
  }

  static class WriteOperationDeserializer implements JsonDeserializer {
    Map> actionRegistry = new HashMap<>();

    void registerAction(WriteOperation.WriteOperationAction action, Class javaType) {
      actionRegistry.put(action.getValue(), javaType);
    }

    @Override
    public WriteOperation deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
      JsonObject jsonObject = json.getAsJsonObject();
      String action = jsonObject.get("action").getAsString();

      if(!actionRegistry.containsKey(action)) {
        throw new WeaverError(WeaverError.WRITE_OPERATION_NOT_EXISTS, "This action was not found: " + action);
      }

      Class operationType = actionRegistry.get(action);

      return context.deserialize(jsonObject, operationType);
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy