Example usage for com.google.gson InstanceCreator InstanceCreator

List of usage examples for com.google.gson InstanceCreator InstanceCreator

Introduction

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

Prototype

InstanceCreator

Source Link

Usage

From source file:ch.vorburger.worlds.persistence.gson.GraphAdapterBuilder.java

License:Apache License

public GraphAdapterBuilder addType(Type type) {
    final ObjectConstructor<?> objectConstructor = constructorConstructor.get(TypeToken.get(type));
    InstanceCreator<Object> instanceCreator = new InstanceCreator<Object>() {
        public Object createInstance(Type type) {
            return objectConstructor.construct();
        }// w ww.  ja  v  a2  s .  c o m
    };
    return addType(type, instanceCreator);
}

From source file:com.google.gwtjsonrpc.server.JsonServlet.java

License:Apache License

/** Create a default GsonBuilder with some extra types defined. */
public static GsonBuilder defaultGsonBuilder() {
    final GsonBuilder gb = new GsonBuilder();
    gb.registerTypeAdapter(java.util.Set.class, new InstanceCreator<java.util.Set<Object>>() {
        public Set<Object> createInstance(final Type arg0) {
            return new HashSet<Object>();
        }//from w  w w  . ja  va 2 s . c o m
    });
    gb.registerTypeAdapter(java.util.Map.class, new MapDeserializer());
    gb.registerTypeAdapter(java.sql.Date.class, new SqlDateDeserializer());
    gb.registerTypeAdapter(java.sql.Timestamp.class, new SqlTimestampDeserializer());
    return gb;
}

From source file:com.guusto.GraphAdapterBuilder.java

License:Apache License

public GraphAdapterBuilder addType(final Type type) {
    final ObjectConstructor<?> objectConstructor = constructorConstructor.get(TypeToken.get(type));
    final InstanceCreator<Object> instanceCreator = new InstanceCreator<Object>() {
        @Override//from  w w  w. j  a  v a 2 s. c  om
        public Object createInstance(final Type type) {
            return objectConstructor.construct();
        }
    };
    return addType(type, instanceCreator);
}

From source file:com.ibm.streamsx.rest.Element.java

License:Open Source License

/**
 * Refresh this element./*from  w w  w . j  a  v  a  2s  . c o m*/
 * 
 * Attributes of this object are updated from current state
 * though the Streams REST API.
 * 
 * @throws IOException Error communicating with Streams.
 */
public void refresh() throws IOException {
    String response = connection().getResponseString(self);

    if (refreshJson == null) {
        refreshJson = refreshBuilder.registerTypeAdapter(getClass(), new InstanceCreator<Object>() {
            @Override
            public Object createInstance(Type arg0) {
                return Element.this;
            }
        }).create();
    }

    Object me = refreshJson.fromJson(response, getClass());

    assert me == this;
}

From source file:com.thirstygoat.kiqo.persistence.GraphAdapterBuilder.java

License:Apache License

public GraphAdapterBuilder addType(Type type) {
    final ObjectConstructor<?> objectConstructor = constructorConstructor.get(TypeToken.get(type));
    final InstanceCreator<Object> instanceCreator = new InstanceCreator<Object>() {
        @Override/*from  w  ww  .j  av  a  2s. c o  m*/
        public Object createInstance(Type type) {
            return objectConstructor.construct();
        }
    };
    return addType(type, instanceCreator);
}

From source file:gem.talk_to_outside_world.validation.JsonLogger.java

License:Open Source License

public static AbstractConwayState readStateFromFile(File file) {
    String json = readJsonFromFile(file);
    if (USE_ILKKA_FORMAT) {
        Gson gson = new Gson();
        SimpleValidationCell[] cells = gson.fromJson(json, SimpleValidationCell[].class);
        return new SimpleValidationBoardState(cells).toConwayState();
    } else {//from   w ww  .  j a  va2 s.  c  o  m
        InstanceCreator<AbstractConwayCell> cellCreator = new InstanceCreator<AbstractConwayCell>() {
            @Override
            public AbstractConwayCell createInstance(Type arg0) {
                return new ConwayCell(CellState.DEAD, false);
            }
        };
        InstanceCreator<INeighborGraph> neighborGraphCreator = new InstanceCreator<INeighborGraph>() {
            @Override
            public INeighborGraph createInstance(Type arg0) {
                return new SymmetricalInfluenceGraph();
            }
        };
        Gson gson = new GsonBuilder().registerTypeAdapter(AbstractConwayCell.class, cellCreator)
                .registerTypeAdapter(INeighborGraph.class, neighborGraphCreator).create();
        ConwayState state = gson.fromJson(json, ConwayState.class);
        return state;
    }
}

From source file:io.datakernel.datagraph.server.DatagraphSerialization.java

License:Apache License

/**
 * Constructs a new datagraph serialization object, initializes Gson object with used classes.
 *///from  w  w  w. ja v  a2 s  . c  o m
public DatagraphSerialization(List<NodeSubclass> nodeSubclasses) {
    Class<?> naturalOrderingClass;
    Class<?> identityFunctionClass;
    try {
        naturalOrderingClass = Class.forName("com.google.common.collect.NaturalOrdering");
        identityFunctionClass = Class.forName("com.google.common.base.Functions$IdentityFunction");
    } catch (ClassNotFoundException e) {
        throw Throwables.propagate(e);
    }

    GsonSubclassesAdapter.Builder<Object> gsonSubclassesAdapterBuilder = GsonSubclassesAdapter.builder()
            .subclassField("nodeType").subclass("Download", NodeDownload.class)
            .subclass("Upload", NodeUpload.class).subclass("Map", NodeMap.class)
            .subclass("Filter", NodeFilter.class).subclass("Sort", NodeSort.class)
            .subclass("Shard", NodeShard.class).subclass("Merge", NodeMerge.class)
            .subclass("Reduce", NodeReduce.class).subclass("ReduceSimple", NodeReduceSimple.class)
            .subclass("Join", NodeJoin.class).subclass("ProducerOfIterable", NodeProducerOfIterable.class)
            .subclass("ConsumerToList", NodeConsumerToList.class);

    for (NodeSubclass nodeSubclass : nodeSubclasses) {
        gsonSubclassesAdapterBuilder.subclass(nodeSubclass.getSubclassName(), nodeSubclass.getSubclass());
    }

    this.gson = new GsonBuilder().registerTypeAdapter(Class.class, new GsonClassTypeAdapter())
            .registerTypeAdapter(StreamId.class, new GsonStreamIdAdapter())
            .registerTypeAdapter(InetSocketAddress.class, new GsonInetSocketAddressAdapter())
            .registerTypeAdapter(DatagraphCommand.class,
                    GsonSubclassesAdapter.builder().subclassField("commandType")
                            .subclass("Download", DatagraphCommandDownload.class)
                            .subclass("Execute", DatagraphCommandExecute.class).build())
            .registerTypeAdapter(Node.class, gsonSubclassesAdapterBuilder.build())
            .registerTypeAdapter(Predicate.class,
                    GsonSubclassesAdapter.builder().subclassField("predicateType").build())
            .registerTypeAdapter(Function.class,
                    GsonSubclassesAdapter.builder().subclassField("functionType")
                            .classTag(identityFunctionClass.getName(), identityFunctionClass,
                                    new InstanceCreator<Object>() {
                                        @Override
                                        public Object createInstance(Type type) {
                                            return Functions.identity();
                                        }
                                    })
                            .build())
            .registerTypeAdapter(Comparator.class,
                    GsonSubclassesAdapter.builder().subclassField("comparatorType")
                            .classTag(naturalOrderingClass.getName(), naturalOrderingClass,
                                    new InstanceCreator<Object>() {
                                        @Override
                                        public Object createInstance(Type type) {
                                            return Ordering.natural();
                                        }
                                    })
                            .build())
            .registerTypeAdapter(StreamMap.Mapper.class,
                    GsonSubclassesAdapter.builder().subclassField("mapperType").build())
            .registerTypeAdapter(StreamReducers.Reducer.class, GsonSubclassesAdapter.builder()
                    .subclassField("reducerType")
                    .classTag("MergeDeduplicateReducer", StreamReducers.MergeDeduplicateReducer.class)
                    .classTag("MergeSortReducer", StreamReducers.MergeSortReducer.class)
                    .subclass("InputToAccumulator", StreamReducers.ReducerToResult.InputToAccumulator.class)
                    .subclass("InputToOutput", StreamReducers.ReducerToResult.InputToOutput.class)
                    .subclass("AccumulatorToAccumulator",
                            StreamReducers.ReducerToResult.AccumulatorToAccumulator.class)
                    .subclass("AccumulatorToOutput", StreamReducers.ReducerToResult.AccumulatorToOutput.class)
                    .build())
            .registerTypeAdapter(StreamReducers.ReducerToResult.class,
                    GsonSubclassesAdapter.builder().subclassField("reducerToResultType").build())
            .registerTypeAdapter(Sharder.class,
                    GsonSubclassesAdapter.builder().subclassField("sharderType")
                            .subclass("HashSharder", Sharders.HashSharder.class).build())
            .registerTypeAdapter(StreamJoin.Joiner.class,
                    GsonSubclassesAdapter.builder().subclassField("joinerType").build())
            .setPrettyPrinting().enableComplexMapKeySerialization().create();
}

From source file:io.s4.client.util.ObjectBuilder.java

License:Open Source License

public static void main(String[] argv) throws Exception {

    ObjectBuilder b = new ObjectBuilder();

    String s = "{a:5, b:100}";
    Object out = b.fromJson(s, TEST.class);

    System.out.println(out.toString());

    TEST t = new TEST(1, 2);

    System.out.println(b.toJson(t));

    String[] query = { "name", "count", "freq" };
    String target[] = { "ACDW", "11" };

    io.s4.message.Request.ClientRInfo rinfo = new io.s4.message.Request.ClientRInfo();
    rinfo.setRequesterUUID(UUID.randomUUID());
    Request req = new io.s4.message.SinglePERequest(Arrays.asList(target), Arrays.asList(query), rinfo);

    System.out.println(req.toString());

    InstanceCreator<io.s4.message.Request.RInfo> infoCreator = new InstanceCreator<io.s4.message.Request.RInfo>() {
        public io.s4.message.Request.RInfo createInstance(Type type) {
            return new io.s4.message.Request.ClientRInfo();
        }/*  w ww.  j  av a 2  s.c  om*/
    };

    Gson gson = (new GsonBuilder()).registerTypeAdapter(io.s4.message.Request.RInfo.class, infoCreator)
            .registerTypeAdapter(Object.class, new ObjectTypeAdapter()).create();

    System.out.println("gson: " + gson.toJson(req));
    System.out.println("gson reversed: " + gson.fromJson(gson.toJson(req), SinglePERequest.class));

    System.out.println(b.toJson(req));
    System.out.println(b.toJson(Arrays.asList(query)));

    System.out.println("----------------------------------------------");

    ArrayList<SSTest> list = new ArrayList<SSTest>();

    SSTest ss1 = new SSTest();
    ss1.str = "list-element-1";
    SSTest ss2 = new SSTest();
    ss2.str = "list-element-2";

    list.add(ss1);
    list.add(ss2);

    Map<String, Object> listmap = new HashMap<String, Object>();
    listmap.put("ll", list);

    MapTest mt = new MapTest();
    mt.map = listmap;

    Object listmapobj = listmap;

    System.out.println("list: " + gson.toJson(list));
    System.out.println("listmap: " + gson.toJson(listmap));
    System.out.println("listmapobj: " + gson.toJson(listmapobj));
    System.out.println("mapobject: " + gson.toJson(mt));
}

From source file:it.unibo.alchemist.boundary.projectview.utils.ProjectIOUtils.java

License:Open Source License

/**
 * //from   w  w  w .j  a  v  a 2s .  c  om
 * @param directory The folder directory.
 * @return Deserializing reader of Json. 
 */
public static Project loadFrom(final String directory) {
    final Gson gson = new GsonBuilder().registerTypeAdapter(Project.class, new InstanceCreator<Project>() {
        @Override
        public Project createInstance(final Type type) {
            return new Project(new File(directory));
        }
    }).setPrettyPrinting().create();
    final String actualPath = directory + PROJECT_FILE;
    if (new File(actualPath).exists() && new File(actualPath).isFile()) {
        try {
            return gson.fromJson(new FileReader(actualPath), Project.class);
            /* TODO:
             * Create a dry-run
             * R
             */
        } catch (JsonSyntaxException | JsonIOException | FileNotFoundException e) {
            throw new IllegalStateException(e);
        }
    } else {
        return null;
    }
}

From source file:org.apache.s4.client.util.ObjectBuilder.java

License:Apache License

public static void main(String[] argv) throws Exception {

    ObjectBuilder b = new ObjectBuilder();

    String s = "{a:5, b:100}";
    Object out = b.fromJson(s, TEST.class);

    System.out.println(out.toString());

    TEST t = new TEST(1, 2);

    System.out.println(b.toJson(t));

    String[] query = { "name", "count", "freq" };
    String target[] = { "ACDW", "11" };

    org.apache.s4.message.Request.ClientRInfo rinfo = new org.apache.s4.message.Request.ClientRInfo();
    rinfo.setRequesterUUID(UUID.randomUUID());
    Request req = new org.apache.s4.message.SinglePERequest(Arrays.asList(target), Arrays.asList(query), rinfo);

    System.out.println(req.toString());

    InstanceCreator<org.apache.s4.message.Request.RInfo> infoCreator = new InstanceCreator<org.apache.s4.message.Request.RInfo>() {
        public org.apache.s4.message.Request.RInfo createInstance(Type type) {
            return new org.apache.s4.message.Request.ClientRInfo();
        }//from  w w w  .java2  s.c om
    };

    Gson gson = (new GsonBuilder()).registerTypeAdapter(org.apache.s4.message.Request.RInfo.class, infoCreator)
            .registerTypeAdapter(Object.class, new ObjectTypeAdapter()).create();

    System.out.println("gson: " + gson.toJson(req));
    System.out.println("gson reversed: " + gson.fromJson(gson.toJson(req), SinglePERequest.class));

    System.out.println(b.toJson(req));
    System.out.println(b.toJson(Arrays.asList(query)));

    System.out.println("----------------------------------------------");

    ArrayList<SSTest> list = new ArrayList<SSTest>();

    SSTest ss1 = new SSTest();
    ss1.str = "list-element-1";
    SSTest ss2 = new SSTest();
    ss2.str = "list-element-2";

    list.add(ss1);
    list.add(ss2);

    Map<String, Object> listmap = new HashMap<String, Object>();
    listmap.put("ll", list);

    MapTest mt = new MapTest();
    mt.map = listmap;

    Object listmapobj = listmap;

    System.out.println("list: " + gson.toJson(list));
    System.out.println("listmap: " + gson.toJson(listmap));
    System.out.println("listmapobj: " + gson.toJson(listmapobj));
    System.out.println("mapobject: " + gson.toJson(mt));
}