Search in sources :

Example 61 with GsonBuilder

use of com.google.gson.GsonBuilder in project DVECTN by tanaponudom.

the class NetworkConnectionManager method callServer_dd_p1.

// ///////////////////////////////////////////////////////////////////////////////////////////////
public void callServer_dd_p1(final OnNetworkCallback_DD_P1 listener, int member_id, int ex11, int ex12, int ex13, int ex14, int ex15) {
    Gson gson = new GsonBuilder().setLenient().create();
    final Retrofit retrofit = new Retrofit.Builder().baseUrl(Fragment_login.BASE_URL).addConverterFactory(GsonConverterFactory.create(gson)).build();
    APISERVER callapi = retrofit.create(APISERVER.class);
    Call call = callapi.getDataDDP1(member_id, ex11, ex12, ex13, ex14, ex15);
    call.enqueue(new Callback<POJO_DD_P1>() {

        @Override
        public void onResponse(Call<POJO_DD_P1> call, Response<POJO_DD_P1> response) {
            try {
                POJO_DD_P1 affective1 = (POJO_DD_P1) response.body();
                if (response.code() != 200) {
                    // Log.e("Network connected","Response code = "+response.code());
                    ResponseBody responseBody = response.errorBody();
                    if (responseBody != null) {
                        listener.onBodyError(responseBody);
                    } else if (responseBody == null) {
                        listener.onBodyErrorIsNull();
                    }
                // Toast.makeText(, ""+loginRes.getAccesstoken(), Toast.LENGTH_SHORT).show();
                // Log.e("Network connected","Response code = "+loginRes.getAccesstoken());
                } else {
                    listener.onResponse(affective1);
                }
            } catch (Exception e) {
            // Log.e("Network connect error",e.getMessage());
            }
        }

        @Override
        public void onFailure(Call<POJO_DD_P1> call, Throwable t) {
            Log.e("NT", t.getMessage());
            try {
                listener.onFailure(t);
            } catch (Exception e) {
                listener.onFailure(t);
            // Log.e("Network connectLogin",t.getMessage());
            }
        }
    });
}
Also used : Call(retrofit2.Call) GsonBuilder(com.google.gson.GsonBuilder) Gson(com.google.gson.Gson) POJO_DD_P1(com.example.user.dvectn.POJO.POJO_DD_P1) ResponseBody(okhttp3.ResponseBody) Retrofit(retrofit2.Retrofit)

Example 62 with GsonBuilder

use of com.google.gson.GsonBuilder in project nifi by apache.

the class ZooKeeperMigrator method writeZooKeeper.

void writeZooKeeper(InputStream zkData, AuthMode authMode, byte[] authData, boolean ignoreSource, boolean useExistingACL) throws IOException, ExecutionException, InterruptedException {
    // ensure that the chroot path exists
    ZooKeeper zooKeeperRoot = getZooKeeper(Joiner.on(',').join(zooKeeperEndpointConfig.getServers()), authMode, authData);
    ensureNodeExists(zooKeeperRoot, zooKeeperEndpointConfig.getPath(), CreateMode.PERSISTENT);
    closeZooKeeper(zooKeeperRoot);
    ZooKeeper zooKeeper = getZooKeeper(zooKeeperEndpointConfig.getConnectString(), authMode, authData);
    JsonReader jsonReader = new JsonReader(new BufferedReader(new InputStreamReader(zkData)));
    Gson gson = new GsonBuilder().create();
    jsonReader.beginArray();
    // determine source ZooKeeperEndpointConfig for this data
    final ZooKeeperEndpointConfig sourceZooKeeperEndpointConfig = gson.fromJson(jsonReader, ZooKeeperEndpointConfig.class);
    LOGGER.info("Source data was obtained from ZooKeeper: {}", sourceZooKeeperEndpointConfig);
    Preconditions.checkArgument(!Strings.isNullOrEmpty(sourceZooKeeperEndpointConfig.getConnectString()) && !Strings.isNullOrEmpty(sourceZooKeeperEndpointConfig.getPath()) && sourceZooKeeperEndpointConfig.getServers() != null && sourceZooKeeperEndpointConfig.getServers().size() > 0, "Source ZooKeeper %s from %s is invalid", sourceZooKeeperEndpointConfig, zkData);
    Preconditions.checkArgument(Collections.disjoint(zooKeeperEndpointConfig.getServers(), sourceZooKeeperEndpointConfig.getServers()) || !zooKeeperEndpointConfig.getPath().equals(sourceZooKeeperEndpointConfig.getPath()) || ignoreSource, "Source ZooKeeper config %s for the data provided can not contain the same server and path as the configured destination ZooKeeper config %s", sourceZooKeeperEndpointConfig, zooKeeperEndpointConfig);
    // stream through each node read from the json input
    final Stream<DataStatAclNode> stream = StreamSupport.stream(new Spliterators.AbstractSpliterator<DataStatAclNode>(0, 0) {

        @Override
        public boolean tryAdvance(Consumer<? super DataStatAclNode> action) {
            try {
                // stream each DataStatAclNode from configured json file
                synchronized (jsonReader) {
                    if (jsonReader.hasNext()) {
                        action.accept(gson.fromJson(jsonReader, DataStatAclNode.class));
                        return true;
                    } else {
                        return false;
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException("unable to read nodes from json", e);
            }
        }
    }, false);
    final List<CompletableFuture<Stat>> writeFutures = stream.parallel().map(node -> {
        /*
             * create stage to determine the acls that should be applied to the node.
             * this stage will be used to initialize the chain
             */
        final CompletableFuture<List<ACL>> determineACLStage = CompletableFuture.supplyAsync(() -> determineACLs(node, authMode, useExistingACL));
        /*
             * create stage to apply acls to nodes and transform node to DataStatAclNode object
             */
        final Function<List<ACL>, CompletableFuture<DataStatAclNode>> transformNodeStage = acls -> CompletableFuture.supplyAsync(() -> transformNode(node, acls));
        /*
             * create stage to ensure that nodes exist for the entire path of the zookeeper node, must be invoked after the transformNode stage to
             * ensure that the node will exist after path migration
             */
        final Function<DataStatAclNode, CompletionStage<String>> ensureNodeExistsStage = dataStatAclNode -> CompletableFuture.supplyAsync(() -> ensureNodeExists(zooKeeper, dataStatAclNode.getPath(), dataStatAclNode.getEphemeralOwner() == 0 ? CreateMode.PERSISTENT : CreateMode.EPHEMERAL));
        /*
             * create stage that waits for both the transformNode and ensureNodeExists stages complete, and also provides that the given transformed node is
             * available to the next stage
             */
        final BiFunction<String, DataStatAclNode, DataStatAclNode> combineEnsureNodeAndTransferNodeStage = (u, dataStatAclNode) -> dataStatAclNode;
        /*
             * create stage to transmit the node to the destination zookeeper endpoint, must be invoked after the node has been transformed and its path
             * has been created (or already exists) in the destination zookeeper
             */
        final Function<DataStatAclNode, CompletionStage<Stat>> transmitNodeStage = dataStatNode -> CompletableFuture.supplyAsync(() -> transmitNode(zooKeeper, dataStatNode));
        /*
             * submit the stages chained together in the proper order to perform the processing on the given node
             */
        final CompletableFuture<DataStatAclNode> dataStatAclNodeCompletableFuture = determineACLStage.thenCompose(transformNodeStage);
        return dataStatAclNodeCompletableFuture.thenCompose(ensureNodeExistsStage).thenCombine(dataStatAclNodeCompletableFuture, combineEnsureNodeAndTransferNodeStage).thenCompose(transmitNodeStage);
    }).collect(Collectors.toList());
    CompletableFuture<Void> allWritesFuture = CompletableFuture.allOf(writeFutures.toArray(new CompletableFuture[writeFutures.size()]));
    final CompletableFuture<List<Stat>> finishedWrites = allWritesFuture.thenApply(v -> writeFutures.stream().map(CompletableFuture::join).collect(Collectors.toList()));
    final List<Stat> writesDone = finishedWrites.get();
    if (LOGGER.isInfoEnabled()) {
        final int writeCount = writesDone.size();
        LOGGER.info("{} {} transferred to {}", writeCount, writeCount == 1 ? "node" : "nodes", zooKeeperEndpointConfig);
    }
    jsonReader.close();
    closeZooKeeper(zooKeeper);
}
Also used : CreateMode(org.apache.zookeeper.CreateMode) Spliterators(java.util.Spliterators) BiFunction(java.util.function.BiFunction) LoggerFactory(org.slf4j.LoggerFactory) ACL(org.apache.zookeeper.data.ACL) CompletableFuture(java.util.concurrent.CompletableFuture) Stat(org.apache.zookeeper.data.Stat) JsonParser(com.google.gson.JsonParser) Function(java.util.function.Function) GsonBuilder(com.google.gson.GsonBuilder) JsonReader(com.google.gson.stream.JsonReader) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) Gson(com.google.gson.Gson) OutputStreamWriter(java.io.OutputStreamWriter) StreamSupport(java.util.stream.StreamSupport) Splitter(com.google.common.base.Splitter) JsonWriter(com.google.gson.stream.JsonWriter) ZooKeeper(org.apache.zookeeper.ZooKeeper) OutputStream(java.io.OutputStream) Logger(org.slf4j.Logger) KeeperException(org.apache.zookeeper.KeeperException) Watcher(org.apache.zookeeper.Watcher) BufferedWriter(java.io.BufferedWriter) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) Stream(java.util.stream.Stream) ZooDefs(org.apache.zookeeper.ZooDefs) Preconditions(com.google.common.base.Preconditions) BufferedReader(java.io.BufferedReader) Collections(java.util.Collections) Joiner(com.google.common.base.Joiner) InputStream(java.io.InputStream) Gson(com.google.gson.Gson) BiFunction(java.util.function.BiFunction) Function(java.util.function.Function) CompletableFuture(java.util.concurrent.CompletableFuture) Stat(org.apache.zookeeper.data.Stat) JsonReader(com.google.gson.stream.JsonReader) ArrayList(java.util.ArrayList) List(java.util.List) InputStreamReader(java.io.InputStreamReader) GsonBuilder(com.google.gson.GsonBuilder) ACL(org.apache.zookeeper.data.ACL) IOException(java.io.IOException) Spliterators(java.util.Spliterators) ZooKeeper(org.apache.zookeeper.ZooKeeper) BiFunction(java.util.function.BiFunction) BufferedReader(java.io.BufferedReader)

Example 63 with GsonBuilder

use of com.google.gson.GsonBuilder in project nifi by apache.

the class ZooKeeperMigrator method readZooKeeper.

void readZooKeeper(OutputStream zkData, AuthMode authMode, byte[] authData) throws IOException, KeeperException, InterruptedException, ExecutionException {
    ZooKeeper zooKeeper = getZooKeeper(zooKeeperEndpointConfig.getConnectString(), authMode, authData);
    JsonWriter jsonWriter = new JsonWriter(new BufferedWriter(new OutputStreamWriter(zkData)));
    jsonWriter.setIndent("  ");
    JsonParser jsonParser = new JsonParser();
    Gson gson = new GsonBuilder().create();
    jsonWriter.beginArray();
    // persist source ZooKeeperEndpointConfig
    gson.toJson(jsonParser.parse(gson.toJson(zooKeeperEndpointConfig)).getAsJsonObject(), jsonWriter);
    LOGGER.info("Retrieving data from source ZooKeeper: {}", zooKeeperEndpointConfig);
    final List<CompletableFuture<Void>> readFutures = streamPaths(getNode(zooKeeper, "/")).parallel().map(node -> CompletableFuture.supplyAsync(() -> {
        final DataStatAclNode dataStatAclNode = retrieveNode(zooKeeper, node);
        LOGGER.debug("retrieved node {} from {}", dataStatAclNode, zooKeeperEndpointConfig);
        return dataStatAclNode;
    }).thenAccept(dataStatAclNode -> {
        // persist each zookeeper node
        synchronized (jsonWriter) {
            gson.toJson(jsonParser.parse(gson.toJson(dataStatAclNode)).getAsJsonObject(), jsonWriter);
        }
    })).collect(Collectors.toList());
    CompletableFuture<Void> allReadsFuture = CompletableFuture.allOf(readFutures.toArray(new CompletableFuture[readFutures.size()]));
    final CompletableFuture<List<Void>> finishedReads = allReadsFuture.thenApply(v -> readFutures.stream().map(CompletableFuture::join).collect(Collectors.toList()));
    final List<Void> readsDone = finishedReads.get();
    jsonWriter.endArray();
    jsonWriter.close();
    if (LOGGER.isInfoEnabled()) {
        final int readCount = readsDone.size();
        LOGGER.info("{} {} read from {}", readCount, readCount == 1 ? "node" : "nodes", zooKeeperEndpointConfig);
    }
    closeZooKeeper(zooKeeper);
}
Also used : CreateMode(org.apache.zookeeper.CreateMode) Spliterators(java.util.Spliterators) BiFunction(java.util.function.BiFunction) LoggerFactory(org.slf4j.LoggerFactory) ACL(org.apache.zookeeper.data.ACL) CompletableFuture(java.util.concurrent.CompletableFuture) Stat(org.apache.zookeeper.data.Stat) JsonParser(com.google.gson.JsonParser) Function(java.util.function.Function) GsonBuilder(com.google.gson.GsonBuilder) JsonReader(com.google.gson.stream.JsonReader) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) Gson(com.google.gson.Gson) OutputStreamWriter(java.io.OutputStreamWriter) StreamSupport(java.util.stream.StreamSupport) Splitter(com.google.common.base.Splitter) JsonWriter(com.google.gson.stream.JsonWriter) ZooKeeper(org.apache.zookeeper.ZooKeeper) OutputStream(java.io.OutputStream) Logger(org.slf4j.Logger) KeeperException(org.apache.zookeeper.KeeperException) Watcher(org.apache.zookeeper.Watcher) BufferedWriter(java.io.BufferedWriter) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) Stream(java.util.stream.Stream) ZooDefs(org.apache.zookeeper.ZooDefs) Preconditions(com.google.common.base.Preconditions) BufferedReader(java.io.BufferedReader) Collections(java.util.Collections) Joiner(com.google.common.base.Joiner) InputStream(java.io.InputStream) GsonBuilder(com.google.gson.GsonBuilder) Gson(com.google.gson.Gson) JsonWriter(com.google.gson.stream.JsonWriter) BufferedWriter(java.io.BufferedWriter) CompletableFuture(java.util.concurrent.CompletableFuture) ZooKeeper(org.apache.zookeeper.ZooKeeper) OutputStreamWriter(java.io.OutputStreamWriter) ArrayList(java.util.ArrayList) List(java.util.List) JsonParser(com.google.gson.JsonParser)

Example 64 with GsonBuilder

use of com.google.gson.GsonBuilder in project apps-android-commons by commons-app.

the class NearbyBaseMarker method writeToParcel.

@Override
public void writeToParcel(Parcel dest, int flags) {
    Gson gson = new GsonBuilder().registerTypeAdapter(Uri.class, new UriSerializer()).create();
    dest.writeParcelable(position, flags);
    dest.writeString(snippet);
    dest.writeString(icon.getId());
    dest.writeParcelable(icon.getBitmap(), flags);
    dest.writeString(title);
    dest.writeString(gson.toJson(place));
}
Also used : GsonBuilder(com.google.gson.GsonBuilder) Gson(com.google.gson.Gson) UriSerializer(fr.free.nrw.commons.utils.UriSerializer) Uri(android.net.Uri)

Example 65 with GsonBuilder

use of com.google.gson.GsonBuilder in project streamsx.health by IBMStreams.

the class VinesMessageParser method createGson.

private static Gson createGson() {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(ITerm.class, new TermTransformer());
    builder.registerTypeAdapter(ITermValue.class, new TermValueTransformer());
    builder.registerTypeAdapter(Vines.class, new VinesTransformer());
    return builder.create();
}
Also used : TermValueTransformer(com.ibm.streamsx.health.vines.model.TermValueTransformer) GsonBuilder(com.google.gson.GsonBuilder) VinesTransformer(com.ibm.streamsx.health.vines.model.VinesTransformer) TermTransformer(com.ibm.streamsx.health.vines.model.TermTransformer)

Aggregations

GsonBuilder (com.google.gson.GsonBuilder)1067 Gson (com.google.gson.Gson)803 IOException (java.io.IOException)185 Test (org.junit.Test)141 ArrayList (java.util.ArrayList)101 JsonObject (com.google.gson.JsonObject)90 File (java.io.File)80 JsonElement (com.google.gson.JsonElement)78 HashMap (java.util.HashMap)67 List (java.util.List)62 Map (java.util.Map)59 Retrofit (retrofit2.Retrofit)56 Type (java.lang.reflect.Type)52 FileNotFoundException (java.io.FileNotFoundException)42 TypeToken (com.google.gson.reflect.TypeToken)40 ResponseBody (okhttp3.ResponseBody)39 FileOutputStream (java.io.FileOutputStream)38 Call (retrofit2.Call)38 JsonSyntaxException (com.google.gson.JsonSyntaxException)37 JsonParser (com.google.gson.JsonParser)36