Example usage for com.google.gson JsonElement toString

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

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Returns a String representation of this element.

Usage

From source file:hdm.stuttgart.esell.router.GeneralObjectDeserializer.java

License:Apache License

public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (json.isJsonNull()) {
        return null;
    } else if (json.isJsonPrimitive()) {
        JsonPrimitive primitive = json.getAsJsonPrimitive();
        if (primitive.isString()) {
            return primitive.getAsString();
        } else if (primitive.isNumber()) {
            return primitive.getAsNumber();
        } else if (primitive.isBoolean()) {
            return primitive.getAsBoolean();
        }//from w  w w  .j  a  v a2  s . co  m
    } else if (json.isJsonArray()) {
        JsonArray array = json.getAsJsonArray();
        Object[] result = new Object[array.size()];
        int i = 0;
        for (JsonElement element : array) {
            result[i] = deserialize(element, null, context);
            ++i;
        }
        return result;
    } else if (json.isJsonObject()) {
        JsonObject object = json.getAsJsonObject();
        Map<String, Object> result = new HashMap<String, Object>();
        for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
            Object value = deserialize(entry.getValue(), null, context);
            result.put(entry.getKey(), value);
        }
        return result;
    } else {
        throw new JsonParseException("Unknown JSON type for JsonElement " + json.toString());
    }
    return null;
}

From source file:ilearnrw.rest.WordDeserializer.java

License:Open Source License

public Word deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    return new Word(json.toString());
}

From source file:im.vector.adapters.VectorMessagesAdapterMediasHelper.java

License:Apache License

/**
 * Manage the image/video download./*  w ww. j a va2 s  .  c o  m*/
 *
 * @param convertView the parent view.
 * @param event       the event
 * @param message     the image / video message
 * @param position    the message position
 */
void managePendingImageVideoDownload(final View convertView, final Event event, final Message message,
        final int position) {
    int maxImageWidth = mMaxImageWidth;
    int maxImageHeight = mMaxImageHeight;
    int rotationAngle = 0;
    int orientation = ExifInterface.ORIENTATION_NORMAL;
    String thumbUrl = null;
    int thumbWidth = -1;
    int thumbHeight = -1;

    EncryptedFileInfo encryptedFileInfo = null;

    // retrieve the common items
    if (message instanceof ImageMessage) {
        ImageMessage imageMessage = (ImageMessage) message;
        imageMessage.checkMediaUrls();

        // Backwards compatibility with events from before Synapse 0.6.0
        if (imageMessage.getThumbnailUrl() != null) {
            thumbUrl = imageMessage.getThumbnailUrl();

            if (null != imageMessage.info) {
                encryptedFileInfo = imageMessage.info.thumbnail_file;
            }

        } else if (imageMessage.getUrl() != null) {
            thumbUrl = imageMessage.getUrl();
            encryptedFileInfo = imageMessage.file;
        }

        rotationAngle = imageMessage.getRotation();

        ImageInfo imageInfo = imageMessage.info;

        if (null != imageInfo) {
            if ((null != imageInfo.w) && (null != imageInfo.h)) {
                thumbWidth = imageInfo.w;
                thumbHeight = imageInfo.h;
            }

            if (null != imageInfo.orientation) {
                orientation = imageInfo.orientation;
            }
        }
    } else if (message instanceof VideoMessage) { // video
        VideoMessage videoMessage = (VideoMessage) message;
        videoMessage.checkMediaUrls();

        thumbUrl = videoMessage.getThumbnailUrl();
        if (null != videoMessage.info) {
            encryptedFileInfo = videoMessage.info.thumbnail_file;
        }

        VideoInfo videoinfo = videoMessage.info;

        if (null != videoinfo) {
            if ((null != videoMessage.info.thumbnail_info) && (null != videoMessage.info.thumbnail_info.w)
                    && (null != videoMessage.info.thumbnail_info.h)) {
                thumbWidth = videoMessage.info.thumbnail_info.w;
                thumbHeight = videoMessage.info.thumbnail_info.h;
            }
        }
    }

    ImageView imageView = convertView.findViewById(R.id.messagesAdapter_image);

    // reset the bitmap if the url is not the same than before
    if ((null == thumbUrl) || !TextUtils.equals(imageView.hashCode() + "", mUrlByBitmapIndex.get(thumbUrl))) {
        imageView.setImageBitmap(null);
        if (null != thumbUrl) {
            mUrlByBitmapIndex.put(thumbUrl, imageView.hashCode() + "");
        }
    }

    RelativeLayout informationLayout = convertView.findViewById(R.id.messagesAdapter_image_layout);
    final FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) informationLayout
            .getLayoutParams();

    // the thumbnails are always pre - rotated
    String downloadId = null;
    if (!event.getType().equals(Event.EVENT_TYPE_STICKER)) {
        downloadId = mMediasCache.loadBitmap(mSession.getHomeServerConfig(), imageView, thumbUrl, maxImageWidth,
                maxImageHeight, rotationAngle, ExifInterface.ORIENTATION_UNDEFINED, "image/jpeg",
                encryptedFileInfo);
    }

    // test if the media is downloading when the thumbnail is not downloading
    if (null == downloadId) {
        if (message instanceof VideoMessage) {
            downloadId = mMediasCache.downloadIdFromUrl(((VideoMessage) message).getUrl());
        } else if (message instanceof ImageMessage) {
            downloadId = mMediasCache.downloadIdFromUrl(((ImageMessage) message).getUrl());
        }
    }

    // Use Glide library to display stickers into ImageView
    // Glide support animated gif
    if (event.getType().equals(Event.EVENT_TYPE_STICKER)) {
        // Check whether the sticker url is a valid Matrix media content URI, and convert it in an actual url.
        String downloadableUrl = mSession.getContentManager()
                .getDownloadableUrl(((StickerMessage) message).getUrl());
        if (null != downloadableUrl) {
            Glide.with(mContext).load(downloadableUrl)
                    .apply(new RequestOptions().override(maxImageWidth, maxImageHeight).fitCenter()
                            .placeholder(R.drawable.sticker_placeholder))
                    .into(imageView);
        } else {
            // Display the placeholder
            imageView.setImageResource(R.drawable.sticker_placeholder);
        }
    }

    final View downloadProgressLayout = convertView.findViewById(R.id.content_download_progress_layout);

    if (null == downloadProgressLayout) {
        return;
    }

    // the tag is used to detect if the progress value is linked to this layout
    downloadProgressLayout.setTag(downloadId);

    int frameHeight = -1;
    int frameWidth = -1;

    // if the image size is known
    // compute the expected thumbnail height
    if ((thumbWidth > 0) && (thumbHeight > 0)) {

        // swap width and height if the image is side oriented
        if ((rotationAngle == 90) || (rotationAngle == 270)) {
            int tmp = thumbWidth;
            thumbWidth = thumbHeight;
            thumbHeight = tmp;
        } else if ((orientation == ExifInterface.ORIENTATION_ROTATE_90)
                || (orientation == ExifInterface.ORIENTATION_ROTATE_270)) {
            int tmp = thumbWidth;
            thumbWidth = thumbHeight;
            thumbHeight = tmp;
        }

        frameHeight = Math.min(maxImageWidth * thumbHeight / thumbWidth, maxImageHeight);
        frameWidth = frameHeight * thumbWidth / thumbHeight;
    }

    // ensure that some values are properly initialized
    if (frameHeight < 0) {
        frameHeight = mMaxImageHeight;
    }

    if (frameWidth < 0) {
        frameWidth = mMaxImageWidth;
    }

    // apply it the layout
    // it avoid row jumping when the image is downloaded
    layoutParams.height = frameHeight;
    layoutParams.width = frameWidth;

    // no download in progress
    if (null != downloadId) {
        downloadProgressLayout.setVisibility(View.VISIBLE);

        mMediasCache.addDownloadListener(downloadId, new MXMediaDownloadListener() {
            @Override
            public void onDownloadCancel(String downloadId) {
                if (TextUtils.equals(downloadId, (String) downloadProgressLayout.getTag())) {
                    downloadProgressLayout.setVisibility(View.GONE);
                }
            }

            @Override
            public void onDownloadError(String downloadId, JsonElement jsonElement) {
                if (TextUtils.equals(downloadId, (String) downloadProgressLayout.getTag())) {
                    MatrixError error = null;

                    try {
                        error = JsonUtils.toMatrixError(jsonElement);
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "Cannot cast to Matrix error " + e.getLocalizedMessage());
                    }

                    downloadProgressLayout.setVisibility(View.GONE);

                    if ((null != error) && error.isSupportedErrorCode()) {
                        Toast.makeText(mContext, error.getLocalizedMessage(), Toast.LENGTH_LONG).show();
                    } else if (null != jsonElement) {
                        Toast.makeText(mContext, jsonElement.toString(), Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onDownloadProgress(String aDownloadId, DownloadStats stats) {
                if (TextUtils.equals(aDownloadId, (String) downloadProgressLayout.getTag())) {
                    refreshDownloadViews(event, stats, downloadProgressLayout);
                }
            }

            @Override
            public void onDownloadComplete(String aDownloadId) {
                if (TextUtils.equals(aDownloadId, (String) downloadProgressLayout.getTag())) {
                    downloadProgressLayout.setVisibility(View.GONE);

                    if (null != mVectorMessagesAdapterEventsListener) {
                        mVectorMessagesAdapterEventsListener.onMediaDownloaded(position);
                    }
                }
            }
        });

        refreshDownloadViews(event, mMediasCache.getStatsForDownloadId(downloadId), downloadProgressLayout);
    } else {
        downloadProgressLayout.setVisibility(View.GONE);
    }

    imageView.setBackgroundColor(Color.TRANSPARENT);
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
}

From source file:im.vector.adapters.VectorMessagesAdapterMediasHelper.java

License:Apache License

/**
 * Manage the file download items./*from   ww  w . j  a v a 2s  . c o  m*/
 *
 * @param convertView the message cell view.
 * @param event       the event
 * @param fileMessage the file message.
 * @param position    the position in the listview.
 */
void managePendingFileDownload(View convertView, final Event event, FileMessage fileMessage,
        final int position) {
    String downloadId = mMediasCache.downloadIdFromUrl(fileMessage.getUrl());
    final View downloadProgressLayout = convertView.findViewById(R.id.content_download_progress_layout);

    if (null == downloadProgressLayout) {
        return;
    }

    downloadProgressLayout.setTag(downloadId);

    // no download in progress
    if (null != downloadId) {
        downloadProgressLayout.setVisibility(View.VISIBLE);

        mMediasCache.addDownloadListener(downloadId, new MXMediaDownloadListener() {
            @Override
            public void onDownloadCancel(String downloadId) {
                if (TextUtils.equals(downloadId, (String) downloadProgressLayout.getTag())) {
                    downloadProgressLayout.setVisibility(View.GONE);
                }
            }

            @Override
            public void onDownloadError(String downloadId, JsonElement jsonElement) {
                if (TextUtils.equals(downloadId, (String) downloadProgressLayout.getTag())) {
                    MatrixError error = null;

                    try {
                        error = JsonUtils.toMatrixError(jsonElement);
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "Cannot cast to Matrix error " + e.getLocalizedMessage());
                    }

                    downloadProgressLayout.setVisibility(View.GONE);

                    if ((null != error) && error.isSupportedErrorCode()) {
                        Toast.makeText(mContext, error.getLocalizedMessage(), Toast.LENGTH_LONG).show();
                    } else if (null != jsonElement) {
                        Toast.makeText(mContext, jsonElement.toString(), Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onDownloadProgress(String aDownloadId, DownloadStats stats) {
                if (TextUtils.equals(aDownloadId, (String) downloadProgressLayout.getTag())) {
                    refreshDownloadViews(event, stats, downloadProgressLayout);
                }
            }

            @Override
            public void onDownloadComplete(String aDownloadId) {
                if (TextUtils.equals(aDownloadId, (String) downloadProgressLayout.getTag())) {
                    downloadProgressLayout.setVisibility(View.GONE);

                    if (null != mVectorMessagesAdapterEventsListener) {
                        mVectorMessagesAdapterEventsListener.onMediaDownloaded(position);
                    }
                }
            }
        });
        refreshDownloadViews(event, mMediasCache.getStatsForDownloadId(downloadId), downloadProgressLayout);
    } else {
        downloadProgressLayout.setVisibility(View.GONE);
    }
}

From source file:in.mtap.iincube.mongoser.codec.JsonArrayDecoder.java

License:Apache License

@Override
public List<DBObject> getAsDBObject() {
    List<DBObject> dbObjects = new LinkedList<DBObject>();
    if (!isValid())
        throw new IllegalArgumentException("Parse error invalid json: \n" + dataBuilder.toString());

    if (jsonElement.isJsonArray()) {
        JsonArray jsonArray = jsonElement.getAsJsonArray();
        for (JsonElement element : jsonArray) {
            dbObjects.add((DBObject) JSON.parse(element.toString()));
        }//from ww  w .  j  a v a  2s  .c om
    } else {
        dbObjects.add((DBObject) JSON.parse(jsonElement.toString()));
    }
    return dbObjects;
}

From source file:io.brooklyn.ambari.server.AmbariServerImpl.java

License:Apache License

Function<JsonElement, List<String>> getHosts() {
    Function<JsonElement, List<String>> path = new Function<JsonElement, List<String>>() {
        @Nullable/*from  w  ww.  j a  v  a 2  s  . c om*/
        @Override
        public List<String> apply(@Nullable JsonElement jsonElement) {
            String jsonString = jsonElement.toString();
            return JsonPath.read(jsonString, "$.items[*].Hosts.host_name");
        }
    };
    return path;
}

From source file:io.brooklyn.ambari.server.AmbariServerImpl.java

License:Apache License

Function<JsonElement, String> getRequestState() {
    Function<JsonElement, String> path = new Function<JsonElement, String>() {
        @Nullable/*from w  ww . j  ava  2s .  com*/
        @Override
        public String apply(@Nullable JsonElement jsonElement) {
            String jsonString = jsonElement.toString();
            return JsonPath.read(jsonString, "$.Requests.request_status");
        }
    };
    return path;
}

From source file:io.dockstore.common.ToolWorkflowDeserializer.java

License:Apache License

@Override
public SearchClient.ElasticSearchObject.HitsInternal deserialize(JsonElement json, Type typeOfT,
        JsonDeserializationContext context) throws JsonParseException {
    Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new DateDeserializer()).create();

    SearchClient.ElasticSearchObject.HitsInternal internalHit = gson.fromJson(json,
            SearchClient.ElasticSearchObject.HitsInternal.class);

    JsonObject jsonObject = json.getAsJsonObject();
    JsonElement jsonType = jsonObject.get("_type");
    String type = jsonType.getAsString();

    JsonElement sourceElement = jsonObject.get("_source");
    String sourceString = sourceElement.toString();

    if ("workflow".equals(type)) {
        internalHit.source = gson.fromJson(sourceString, Workflow.class);
    } else if ("tool".equals(type)) {
        internalHit.source = gson.fromJson(sourceString, ToolV1.class);
    }/*from  ww  w.  j  a va  2s  .  co  m*/

    return internalHit;
}

From source file:io.kodokojo.commons.utils.servicelocator.consul.ConsulServiceLocator.java

License:Open Source License

@Override
public Set<Service> getService(String type, String name) {
    if (isBlank(type)) {
        throw new IllegalArgumentException("type must be defined.");
    }//from   ww w. ja  v a 2 s.  c o m
    if (isBlank(name)) {
        throw new IllegalArgumentException("name must be defined.");
    }
    String serviceName = name;
    StringBuilder tags = new StringBuilder().append(kodokojoTags).append(",").append(COMPONENT_NAME_KEY)
            .append("=").append(name).append(",").append(COMPONENT_TYPE_KEY).append("=").append(type);
    JsonArray resultsJson = consulRest.getServices(serviceName, kodokojoTags);

    if (resultsJson == null || resultsJson.size() == 0) {
        return null; //Search not return any service. return null.
    }

    // Iterate to extra multiples tag->entrypoint.
    Set<Service> entryPoints = new HashSet<>();
    for (JsonElement jsonElement : resultsJson) {
        if (!jsonElement.isJsonObject())
            throw new IllegalStateException("Unexpected response return by consul. Waiting a json object, get "
                    + jsonElement.toString());

        JsonObject jsonObject = jsonElement.getAsJsonObject();

        String host = jsonObject.get(ADDRESS_KEY).getAsString();
        int servicePort = jsonObject.get(SERVICE_PORT_KEY).getAsInt();

        Service entryPoint = new Service(host, host, servicePort);
        entryPoints.add(entryPoint);
    }

    return entryPoints;
}

From source file:io.openvidu.server.core.SessionEventsHandler.java

License:Apache License

public void onStreamPropertyChanged(Participant participant, Integer transactionId,
        Set<Participant> participants, String streamId, String property, JsonElement newValue, String reason) {

    JsonObject params = new JsonObject();
    params.addProperty(ProtocolElements.STREAMPROPERTYCHANGED_CONNECTIONID_PARAM,
            participant.getParticipantPublicId());
    params.addProperty(ProtocolElements.STREAMPROPERTYCHANGED_STREAMID_PARAM, streamId);
    params.addProperty(ProtocolElements.STREAMPROPERTYCHANGED_PROPERTY_PARAM, property);
    params.addProperty(ProtocolElements.STREAMPROPERTYCHANGED_NEWVALUE_PARAM, newValue.toString());
    params.addProperty(ProtocolElements.STREAMPROPERTYCHANGED_REASON_PARAM, reason);

    for (Participant p : participants) {
        if (p.getParticipantPrivateId().equals(participant.getParticipantPrivateId())) {
            rpcNotificationService.sendResponse(participant.getParticipantPrivateId(), transactionId,
                    new JsonObject());
        } else {/*from  w  w  w.  j ava  2s  .  c  o m*/
            rpcNotificationService.sendNotification(p.getParticipantPrivateId(),
                    ProtocolElements.STREAMPROPERTYCHANGED_METHOD, params);
        }
    }
}