Example usage for com.google.gson JsonElement getAsLong

List of usage examples for com.google.gson JsonElement getAsLong

Introduction

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

Prototype

public long getAsLong() 

Source Link

Document

convenience method to get this element as a primitive long value.

Usage

From source file:de.azapps.mirakel.model.task.TaskDeserializer.java

License:Open Source License

@Override
public Task deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
        throws JsonParseException {
    final JsonObject el = json.getAsJsonObject();
    Optional<ListMirakel> taskList = absent();
    final JsonElement id = el.get("id");
    if (id == null) {
        throw new JsonParseException("Json malformed");
    }//from   w w w .  j  a v a  2s. c o  m
    final Task task = Task.get(id.getAsLong()).or(new Task());
    // Name
    final Set<Entry<String, JsonElement>> entries = el.entrySet();
    for (final Entry<String, JsonElement> entry : entries) {
        final String key = entry.getKey();
        final JsonElement val = entry.getValue();
        if ((key == null) || "id".equalsIgnoreCase(key)) {
            continue;
        }
        switch (key.toLowerCase()) {
        case "name":
            task.setName(val.getAsString());
            break;
        case "content":
            String content = val.getAsString();
            if (content == null) {
                content = "";
            }
            task.setContent(content);
            break;
        case "priority":
            task.setPriority((int) val.getAsFloat());
            break;
        case "progress":
            task.setProgress((int) val.getAsDouble());
            break;
        case "list_id":
            taskList = ListMirakel.get(val.getAsInt());
            if (!taskList.isPresent()) {
                taskList = fromNullable(SpecialList.firstSpecialSafe().getDefaultList());
            }
            break;
        case "created_at":
            try {
                task.setCreatedAt(DateTimeHelper.parseDateTime(val.getAsString().replace(":", "")));
            } catch (final ParseException e) {
                Log.wtf(TAG, "invalid dateformat: ", e);
            }
            break;
        case "updated_at":
            try {
                task.setUpdatedAt(DateTimeHelper.parseDateTime(val.getAsString().replace(":", "")));
            } catch (final ParseException e) {
                Log.wtf(TAG, "invalid dateformat: ", e);
            }
            break;
        case "done":
            task.setDone(val.getAsBoolean());
            break;
        case "due":
            try {
                task.setDue(of(DateTimeHelper.createLocalCalendar(val.getAsLong())));
            } catch (final NumberFormatException ignored) {
                task.setDue(Optional.<Calendar>absent());
            }
            break;
        case "reminder":
            try {
                task.setReminder(of(DateTimeHelper.createLocalCalendar(val.getAsLong())));
            } catch (final NumberFormatException ignored) {
                task.setReminder(Optional.<Calendar>absent());
            }
            break;
        case "tags":
            handleTags(task, val);
            break;
        case "sync_state":
            task.setSyncState(DefinitionsHelper.SYNC_STATE.valueOf((short) val.getAsFloat()));
            break;
        case "show_recurring":
            task.setIsRecurringShown(val.getAsBoolean());
            break;
        default:
            handleAdditionalEntries(task, key, val);
            break;
        }
    }
    if (!taskList.isPresent()) {
        taskList = of(ListMirakel.safeFirst());
    }
    task.setList(taskList.get(), true);
    return task;
}

From source file:de.symeda.sormas.app.rest.RetroProvider.java

License:Open Source License

private RetroProvider(Context context)
        throws ServerConnectionException, ServerCommunicationException, ApiVersionException {

    lastConnectionId = this.hashCode();

    this.context = context;

    RuntimeTypeAdapterFactory<ClassificationCriteriaDto> classificationCriteriaFactory = RuntimeTypeAdapterFactory
            .of(ClassificationCriteriaDto.class, "type")
            .registerSubtype(ClassificationAllOfCriteriaDto.class, "ClassificationAllOfCriteriaDto")
            .registerSubtype(ClassificationCaseCriteriaDto.class, "ClassificationCaseCriteriaDto")
            .registerSubtype(ClassificationNoneOfCriteriaDto.class, "ClassificationNoneOfCriteriaDto")
            .registerSubtype(ClassificationPersonAgeBetweenYearsCriteriaDto.class,
                    "ClassificationPersonAgeBetweenYearsCriteriaDto")
            .registerSubtype(ClassificationPathogenTestPositiveResultCriteriaDto.class,
                    "ClassificationPathogenTestPositiveResultCriteriaDto")
            .registerSubtype(ClassificationXOfCriteriaDto.class, "ClassificationXOfCriteriaDto")
            .registerSubtype(ClassificationEpiDataCriteriaDto.class, "ClassificationEpiDataCriteriaDto")
            .registerSubtype(ClassificationNotInStartDateRangeCriteriaDto.class,
                    "ClassificationNotInStartDateRangeCriteriaDto")
            .registerSubtype(ClassificationSymptomsCriteriaDto.class, "ClassificationSymptomsCriteriaDto")
            .registerSubtype(ClassificationPathogenTestCriteriaDto.class,
                    "ClassificationPathogenTestCriteriaDto")
            .registerSubtype(ClassificationXOfCriteriaDto.ClassificationXOfSubCriteriaDto.class,
                    "ClassificationXOfSubCriteriaDto")
            .registerSubtype(ClassificationXOfCriteriaDto.ClassificationOneOfCompactCriteriaDto.class,
                    "ClassificationOneOfCompactCriteriaDto")
            .registerSubtype(ClassificationAllOfCriteriaDto.ClassificationAllOfCompactCriteriaDto.class,
                    "ClassificationAllOfCompactCriteriaDto");

    Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            if (json.isJsonNull()) {
                return null;
            }/*from   www.  ja  va  2s .  c  o  m*/
            long milliseconds = json.getAsLong();
            return new Date(milliseconds);
        }
    }).registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
        @Override
        public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
            if (src == null) {
                return JsonNull.INSTANCE;
            }
            return new JsonPrimitive(src.getTime());
        }
    }).registerTypeAdapterFactory(classificationCriteriaFactory).create();

    // Basic auth as explained in https://futurestud.io/tutorials/android-basic-authentication-with-retrofit

    String authToken = Credentials.basic(ConfigProvider.getUsername(), ConfigProvider.getPassword());
    AuthenticationInterceptor interceptor = new AuthenticationInterceptor(authToken);

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.connectTimeout(20, TimeUnit.SECONDS);
    httpClient.readTimeout(60, TimeUnit.SECONDS); // for infrastructure data
    httpClient.writeTimeout(30, TimeUnit.SECONDS);

    // adds "Accept-Encoding: gzip" by default
    httpClient.addInterceptor(interceptor);

    // header for logging purposes
    httpClient.addInterceptor(chain -> {

        Request original = chain.request();
        Request.Builder builder = original.newBuilder();

        User user = ConfigProvider.getUser();
        if (user != null) {
            builder.header("User", DataHelper.getShortUuid(user.getUuid()));
            builder.header("Connection", String.valueOf(lastConnectionId)); // not sure if this is a good solution
        }

        builder.method(original.method(), original.body());
        return chain.proceed(builder.build());
    });

    retrofit = new Retrofit.Builder().baseUrl(ConfigProvider.getServerRestUrl())
            .addConverterFactory(GsonConverterFactory.create(gson)).client(httpClient.build()).build();

    checkCompatibility();

    updateLocale();
}

From source file:ee.ria.xroad.asyncdb.messagequeue.JsonUtils.java

License:Open Source License

static Date getDatePropertyValue(JsonObject jsonObject, String memberName) {
    JsonElement jsonElement = jsonObject.get(memberName);

    if (jsonElement == null) {
        return null;
    }/*  w  w  w  .ja v  a2  s .  c  o  m*/

    return new Date(jsonElement.getAsLong());
}

From source file:guru.qas.martini.report.column.ExecutionTimeColumn.java

License:Apache License

protected Long getTimestamp(JsonObject o, String key) {
    JsonElement element = o.get(key);
    return null == element ? null : element.getAsLong();
}

From source file:io.hypertrack.sendeta.util.DateDeserializer.java

License:Open Source License

@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    try {/*  ww w.j a v a 2 s .  c  o  m*/
        return json == null ? null : new Date(json.getAsLong());

    } catch (NumberFormatException e) {
        e.printStackTrace();

        return deserialize12HourDateFormatString(json.getAsString());
    }
}

From source file:io.robusta.rra.representation.implementation.GsonRepresentation.java

License:Apache License

/**
 * convert a jsonElement into Object//ww w .ja  va 2s. com
 * 
 * @param type
 * @param element
 * @return
 * @throws RepresentationException
 */
protected <T> T get(Class<T> type, JsonElement element) throws RepresentationException {

    if (type == Long.class) {
        return (T) (Long) element.getAsLong();
    } else if (type == Integer.class) {
        return (T) (Integer) element.getAsInt();
    } else if (type == Short.class) {
        return (T) (Short) element.getAsShort();
    } else if (type == Byte.class) {
        return (T) (Byte) element.getAsByte();
    } else if (type == BigInteger.class) {
        return (T) (BigInteger) element.getAsBigInteger();
    } else if (type == Double.class) {
        return (T) (Double) element.getAsDouble();
    } else if (type == Float.class) {
        return (T) (Float) element.getAsFloat();
    } else if (type == BigDecimal.class) {
        return (T) (BigDecimal) element.getAsBigDecimal();
    } else if (type == Boolean.class) {
        return (T) (Boolean) element.getAsBoolean();
    } else if (type == String.class) {
        return (T) element.getAsString();
    } else {
        return (T) gson.fromJson(element, type);
    }
}

From source file:io.soliton.protobuf.json.JsonRpcClientHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpResponse response)
        throws Exception {
    if (!(response instanceof HttpContent)) {
        clientLogger.logServerError(null, null, new Exception("Returned response has no content"));
        logger.severe("Returned response has no content");
        return;/*from  w ww.  j ava 2 s  .c  o m*/
    }

    HttpContent content = (HttpContent) response;

    if (!response.headers().get(HttpHeaders.Names.CONTENT_TYPE).equals(JsonRpcProtocol.CONTENT_TYPE)) {
        logger.warning("Incorrect Content-Type: " + response.headers().get(HttpHeaders.Names.CONTENT_TYPE));
    }

    JsonElement root;
    try {
        ByteBufInputStream stream = new ByteBufInputStream(content.content());
        JsonReader reader = new JsonReader(new InputStreamReader(stream, Charsets.UTF_8));
        root = new JsonParser().parse(reader);
    } catch (JsonSyntaxException jsonException) {
        clientLogger.logServerError(null, null, jsonException);
        logger.warning("JSON response cannot be decoded");
        return;
    }
    if (!root.isJsonObject()) {
        logger.warning("JSON response is not a JSON object: " + root.toString());
        return;
    }

    JsonRpcResponse jsonRpcResponse = JsonRpcResponse.fromJson(root.getAsJsonObject());

    JsonElement requestId = jsonRpcResponse.id();
    if (requestId == null || !requestId.isJsonPrimitive()) {
        clientLogger.logServerError(null, null,
                new Exception("Received response identifier is not JSON primitive"));
        logger.warning("Received response identifier is not JSON primitive: " + requestId.toString());
        return;
    }

    JsonResponseFuture<? extends Message> future = inFlightRequests.remove(requestId.getAsLong());
    if (future == null) {
        clientLogger.logServerError(null, null, new Exception("Response received for unknown identifier"));
        logger.severe("Response received for unknown identifier: " + requestId.getAsLong());
        return;
    }

    clientLogger.logSuccess(future.method());
    future.setResponse(jsonRpcResponse);
}

From source file:net.doubledoordev.backend.util.TypeHellhole.java

License:Open Source License

public static void set(Field field, Object object, JsonElement value) throws Exception {
    if (field.getType() == byte.class)
        field.setByte(object, value.getAsByte());
    else if (field.getType() == short.class)
        field.setShort(object, value.getAsShort());
    else if (field.getType() == int.class)
        field.setInt(object, value.getAsInt());
    else if (field.getType() == long.class)
        field.setLong(object, value.getAsLong());
    else if (field.getType() == float.class)
        field.setFloat(object, value.getAsFloat());
    else if (field.getType() == double.class)
        field.setDouble(object, value.getAsDouble());
    else if (field.getType() == boolean.class)
        field.setBoolean(object, value.getAsBoolean());
    else if (field.getType() == char.class)
        field.setChar(object, value.getAsCharacter());
    //// w  w  w.  j  av  a2 s.c o  m
    else if (field.getType() == Byte.class)
        field.set(object, value.getAsByte());
    else if (field.getType() == Short.class)
        field.set(object, value.getAsShort());
    else if (field.getType() == Integer.class)
        field.set(object, value.getAsInt());
    else if (field.getType() == Long.class)
        field.set(object, value.getAsLong());
    else if (field.getType() == Float.class)
        field.set(object, value.getAsFloat());
    else if (field.getType() == Double.class)
        field.set(object, value.getAsDouble());
    else if (field.getType() == Boolean.class)
        field.set(object, value.getAsBoolean());
    else if (field.getType() == Character.class)
        field.set(object, value.getAsCharacter());
    //
    else if (field.getType() == String.class)
        field.set(object, value.getAsString());
    else {
        String m = String.format("Unknown type! Field type: %s Json value: %s Data class: %s", field.getType(),
                value.toString(), object.getClass().getSimpleName());
        Main.LOGGER.error(m);
        throw new Exception(m);
    }
}

From source file:net.swisstech.bitly.gson.converter.DateTimeTypeConverter.java

License:Apache License

@Override
public DateTime deserialize(JsonElement json, Type type, JsonDeserializationContext context) {
    try {/*from www  .  ja v  a2 s. c om*/
        return new DateTime(json.getAsLong());
    } catch (IllegalArgumentException e) {
        // May be it can be formatted as a java.util.Date, so try that
        Date date = context.deserialize(json, Date.class);
        return new DateTime(date);
    }
}

From source file:net.swisstech.bitly.gson.converter.InstantTypeConverter.java

License:Apache License

@Override
public Instant deserialize(JsonElement json, Type type, JsonDeserializationContext context) {
    return new Instant(json.getAsLong());
}