Example usage for com.google.gson JsonObject has

List of usage examples for com.google.gson JsonObject has

Introduction

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

Prototype

public boolean has(String memberName) 

Source Link

Document

Convenience method to check if a member with the specified name is present in this object.

Usage

From source file:com.facebook.ads.sdk.WindowsPhoneAppLink.java

License:Open Source License

public static APINodeList<WindowsPhoneAppLink> parseResponse(String json, APIContext context,
        APIRequest request) throws MalformedResponseException {
    APINodeList<WindowsPhoneAppLink> windowsPhoneAppLinks = new APINodeList<WindowsPhoneAppLink>(request, json);
    JsonArray arr;/*w  ww .  j a  v  a  2  s  .  c  om*/
    JsonObject obj;
    JsonParser parser = new JsonParser();
    Exception exception = null;
    try {
        JsonElement result = parser.parse(json);
        if (result.isJsonArray()) {
            // First, check if it's a pure JSON Array
            arr = result.getAsJsonArray();
            for (int i = 0; i < arr.size(); i++) {
                windowsPhoneAppLinks.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context));
            }
            ;
            return windowsPhoneAppLinks;
        } else if (result.isJsonObject()) {
            obj = result.getAsJsonObject();
            if (obj.has("data")) {
                if (obj.has("paging")) {
                    JsonObject paging = obj.get("paging").getAsJsonObject().get("cursors").getAsJsonObject();
                    String before = paging.has("before") ? paging.get("before").getAsString() : null;
                    String after = paging.has("after") ? paging.get("after").getAsString() : null;
                    windowsPhoneAppLinks.setPaging(before, after);
                }
                if (obj.get("data").isJsonArray()) {
                    // Second, check if it's a JSON array with "data"
                    arr = obj.get("data").getAsJsonArray();
                    for (int i = 0; i < arr.size(); i++) {
                        windowsPhoneAppLinks.add(loadJSON(arr.get(i).getAsJsonObject().toString(), context));
                    }
                    ;
                } else if (obj.get("data").isJsonObject()) {
                    // Third, check if it's a JSON object with "data"
                    obj = obj.get("data").getAsJsonObject();
                    boolean isRedownload = false;
                    for (String s : new String[] { "campaigns", "adsets", "ads" }) {
                        if (obj.has(s)) {
                            isRedownload = true;
                            obj = obj.getAsJsonObject(s);
                            for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
                                windowsPhoneAppLinks.add(loadJSON(entry.getValue().toString(), context));
                            }
                            break;
                        }
                    }
                    if (!isRedownload) {
                        windowsPhoneAppLinks.add(loadJSON(obj.toString(), context));
                    }
                }
                return windowsPhoneAppLinks;
            } else if (obj.has("images")) {
                // Fourth, check if it's a map of image objects
                obj = obj.get("images").getAsJsonObject();
                for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
                    windowsPhoneAppLinks.add(loadJSON(entry.getValue().toString(), context));
                }
                return windowsPhoneAppLinks;
            } else {
                // Fifth, check if it's an array of objects indexed by id
                boolean isIdIndexedArray = true;
                for (Map.Entry entry : obj.entrySet()) {
                    String key = (String) entry.getKey();
                    if (key.equals("__fb_trace_id__")) {
                        continue;
                    }
                    JsonElement value = (JsonElement) entry.getValue();
                    if (value != null && value.isJsonObject() && value.getAsJsonObject().has("id")
                            && value.getAsJsonObject().get("id") != null
                            && value.getAsJsonObject().get("id").getAsString().equals(key)) {
                        windowsPhoneAppLinks.add(loadJSON(value.toString(), context));
                    } else {
                        isIdIndexedArray = false;
                        break;
                    }
                }
                if (isIdIndexedArray) {
                    return windowsPhoneAppLinks;
                }

                // Sixth, check if it's pure JsonObject
                windowsPhoneAppLinks.clear();
                windowsPhoneAppLinks.add(loadJSON(json, context));
                return windowsPhoneAppLinks;
            }
        }
    } catch (Exception e) {
        exception = e;
    }
    throw new MalformedResponseException("Invalid response string: " + json, exception);
}

From source file:com.facebook.buck.apple.XctoolOutputParsing.java

License:Apache License

private static void dispatchEventCallback(Gson gson, JsonElement element, XctoolEventCallback eventCallback)
        throws JsonParseException {
    LOG.debug("Parsing xctool event: %s", element);
    if (!element.isJsonObject()) {
        LOG.warn("Couldn't parse JSON object from xctool event: %s", element);
        return;//from  w  w w  .  j a v  a  2  s  .c  om
    }
    JsonObject object = element.getAsJsonObject();
    if (!object.has("event")) {
        LOG.warn("Couldn't parse JSON event from xctool event: %s", element);
        return;
    }
    JsonElement event = object.get("event");
    if (event == null || !event.isJsonPrimitive()) {
        LOG.warn("Couldn't parse event field from xctool event: %s", element);
        return;
    }
    switch (event.getAsString()) {
    case "begin-ocunit":
        eventCallback.handleBeginOcunitEvent(gson.fromJson(element, BeginOcunitEvent.class));
        break;
    case "end-ocunit":
        eventCallback.handleEndOcunitEvent(gson.fromJson(element, EndOcunitEvent.class));
        break;
    case "begin-test-suite":
        eventCallback.handleBeginTestSuiteEvent(gson.fromJson(element, BeginTestSuiteEvent.class));
        break;
    case "end-test-suite":
        eventCallback.handleEndTestSuiteEvent(gson.fromJson(element, EndTestSuiteEvent.class));
        break;
    case "begin-test":
        eventCallback.handleBeginTestEvent(gson.fromJson(element, BeginTestEvent.class));
        break;
    case "end-test":
        eventCallback.handleEndTestEvent(gson.fromJson(element, EndTestEvent.class));
        break;
    }
}

From source file:com.flipkart.android.proteus.parser.ViewParser.java

License:Apache License

protected void prepareHandlers() {

    addHandler(Attributes.View.OnClick, new EventProcessor<V>() {
        @Override/*from   w  ww .j  ava  2  s.c  o m*/
        public void setOnEventListener(final V view, final JsonElement attributeValue) {
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    fireEvent((ProteusView) view, EventType.OnClick, attributeValue);
                }
            });
        }
    });
    addHandler(Attributes.View.Background, new DrawableResourceProcessor<V>() {
        @Override
        public void setDrawable(V view, Drawable drawable) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                //noinspection deprecation
                view.setBackgroundDrawable(drawable);
            } else {
                view.setBackground(drawable);
            }
        }
    });
    addHandler(Attributes.View.Height, new DimensionAttributeProcessor<V>() {
        @Override
        public void setDimension(float dimension, V view, String key, JsonElement value) {
            ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
            if (layoutParams != null) {
                layoutParams.height = (int) dimension;
                view.setLayoutParams(layoutParams);
            }
        }
    });
    addHandler(Attributes.View.Width, new DimensionAttributeProcessor<V>() {
        @Override
        public void setDimension(float dimension, V view, String key, JsonElement value) {
            ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
            if (layoutParams != null) {
                layoutParams.width = (int) dimension;
                view.setLayoutParams(layoutParams);
            }
        }
    });
    addHandler(Attributes.View.Weight, new StringAttributeProcessor<V>() {
        @Override
        public void handle(String attributeKey, String attributeValue, V view) {
            LinearLayout.LayoutParams layoutParams;
            if (view.getLayoutParams() instanceof LinearLayout.LayoutParams) {
                layoutParams = (LinearLayout.LayoutParams) view.getLayoutParams();
                layoutParams.weight = ParseHelper.parseFloat(attributeValue);
                view.setLayoutParams(layoutParams);
            } else {
                if (ProteusConstants.isLoggingEnabled()) {
                    Log.e(TAG, attributeKey + " is only supported for LinearLayouts");
                }
            }
        }
    });
    addHandler(Attributes.View.LayoutGravity, new StringAttributeProcessor<V>() {
        @Override
        public void handle(String attributeKey, String attributeValue, V view) {
            ViewGroup.LayoutParams layoutParams = view.getLayoutParams();

            if (layoutParams instanceof LinearLayout.LayoutParams) {
                LinearLayout.LayoutParams linearLayoutParams = (LinearLayout.LayoutParams) layoutParams;
                //noinspection ResourceType
                linearLayoutParams.gravity = ParseHelper.parseGravity(attributeValue);
                view.setLayoutParams(layoutParams);
            } else if (layoutParams instanceof FrameLayout.LayoutParams) {
                FrameLayout.LayoutParams linearLayoutParams = (FrameLayout.LayoutParams) layoutParams;
                linearLayoutParams.gravity = ParseHelper.parseGravity(attributeValue);
                view.setLayoutParams(layoutParams);
            } else {
                if (ProteusConstants.isLoggingEnabled()) {
                    Log.e(TAG, attributeKey + " is only supported for LinearLayout and FrameLayout");
                }
            }
        }
    });
    addHandler(Attributes.View.Padding, new DimensionAttributeProcessor<V>() {
        @Override
        public void setDimension(float dimension, V view, String key, JsonElement value) {
            view.setPadding((int) dimension, (int) dimension, (int) dimension, (int) dimension);
        }
    });
    addHandler(Attributes.View.PaddingLeft, new DimensionAttributeProcessor<V>() {
        @Override
        public void setDimension(float dimension, V view, String key, JsonElement value) {
            view.setPadding((int) dimension, view.getPaddingTop(), view.getPaddingRight(),
                    view.getPaddingBottom());
        }
    });
    addHandler(Attributes.View.PaddingTop, new DimensionAttributeProcessor<V>() {
        @Override
        public void setDimension(float dimension, V view, String key, JsonElement value) {
            view.setPadding(view.getPaddingLeft(), (int) dimension, view.getPaddingRight(),
                    view.getPaddingBottom());
        }
    });
    addHandler(Attributes.View.PaddingRight, new DimensionAttributeProcessor<V>() {
        @Override
        public void setDimension(float dimension, V view, String key, JsonElement value) {
            view.setPadding(view.getPaddingLeft(), view.getPaddingTop(), (int) dimension,
                    view.getPaddingBottom());
        }
    });
    addHandler(Attributes.View.PaddingBottom, new DimensionAttributeProcessor<V>() {
        @Override
        public void setDimension(float dimension, V view, String key, JsonElement value) {
            view.setPadding(view.getPaddingLeft(), view.getPaddingTop(), view.getPaddingRight(),
                    (int) dimension);
        }
    });
    addHandler(Attributes.View.Margin, new DimensionAttributeProcessor<V>() {
        @Override
        public void setDimension(float dimension, V view, String key, JsonElement value) {
            if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
                ViewGroup.MarginLayoutParams layoutParams;
                layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
                layoutParams.setMargins((int) dimension, (int) dimension, (int) dimension, (int) dimension);
                view.setLayoutParams(layoutParams);
            } else {
                if (ProteusConstants.isLoggingEnabled()) {
                    Log.e(TAG, "margins can only be applied to views with parent ViewGroup");
                }
            }
        }
    });
    addHandler(Attributes.View.MarginLeft, new DimensionAttributeProcessor<V>() {
        @Override
        public void setDimension(float dimension, V view, String key, JsonElement value) {
            if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
                ViewGroup.MarginLayoutParams layoutParams;
                layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
                layoutParams.setMargins((int) dimension, layoutParams.topMargin, layoutParams.rightMargin,
                        layoutParams.bottomMargin);
                view.setLayoutParams(layoutParams);
            } else {
                if (ProteusConstants.isLoggingEnabled()) {
                    Log.e(TAG, "margins can only be applied to views with parent ViewGroup");
                }
            }
        }
    });
    addHandler(Attributes.View.MarginTop, new DimensionAttributeProcessor<V>() {
        @Override
        public void setDimension(float dimension, V view, String key, JsonElement value) {
            if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
                ViewGroup.MarginLayoutParams layoutParams;
                layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
                layoutParams.setMargins(layoutParams.leftMargin, (int) dimension, layoutParams.rightMargin,
                        layoutParams.bottomMargin);
                view.setLayoutParams(layoutParams);
            } else {
                if (ProteusConstants.isLoggingEnabled()) {
                    Log.e(TAG, "margins can only be applied to views with parent ViewGroup");
                }
            }
        }
    });
    addHandler(Attributes.View.MarginRight, new DimensionAttributeProcessor<V>() {
        @Override
        public void setDimension(float dimension, V view, String key, JsonElement value) {
            if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
                ViewGroup.MarginLayoutParams layoutParams;
                layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
                layoutParams.setMargins(layoutParams.leftMargin, layoutParams.topMargin, (int) dimension,
                        layoutParams.bottomMargin);
                view.setLayoutParams(layoutParams);
            } else {
                if (ProteusConstants.isLoggingEnabled()) {
                    Log.e(TAG, "margins can only be applied to views with parent ViewGroup");
                }
            }
        }
    });
    addHandler(Attributes.View.MarginBottom, new DimensionAttributeProcessor<V>() {
        @Override
        public void setDimension(float dimension, V view, String key, JsonElement value) {
            if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
                ViewGroup.MarginLayoutParams layoutParams;
                layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
                layoutParams.setMargins(layoutParams.leftMargin, layoutParams.topMargin,
                        layoutParams.rightMargin, (int) dimension);
                view.setLayoutParams(layoutParams);
            } else {
                if (ProteusConstants.isLoggingEnabled()) {
                    Log.e(TAG, "margins can only be applied to views with parent ViewGroup");
                }
            }
        }
    });

    addHandler(Attributes.View.MinHeight, new DimensionAttributeProcessor<V>() {
        @Override
        public void setDimension(float dimension, V view, String key, JsonElement value) {
            view.setMinimumHeight((int) dimension);
        }
    });

    addHandler(Attributes.View.MinWidth, new DimensionAttributeProcessor<V>() {
        @Override
        public void setDimension(float dimension, V view, String key, JsonElement value) {
            view.setMinimumWidth((int) dimension);
        }
    });

    addHandler(Attributes.View.Elevation, new DimensionAttributeProcessor<V>() {
        @Override
        public void setDimension(float dimension, V view, String key, JsonElement value) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                view.setElevation(dimension);
            }
        }
    });
    addHandler(Attributes.View.Alpha, new StringAttributeProcessor<V>() {
        @Override
        public void handle(String attributeKey, String attributeValue, V view) {
            view.setAlpha(ParseHelper.parseFloat(attributeValue));
        }
    });
    addHandler(Attributes.View.Visibility, new JsonDataProcessor<V>() {
        @Override
        public void handle(String key, JsonElement value, V view) {
            // noinspection ResourceType
            view.setVisibility(ParseHelper.parseVisibility(value));
        }
    });
    addHandler(Attributes.View.Invisibility, new JsonDataProcessor<V>() {
        @Override
        public void handle(String key, JsonElement value, V view) {
            // noinspection ResourceType
            view.setVisibility(ParseHelper.parseInvisibility(value));
        }
    });
    addHandler(Attributes.View.Id, new StringAttributeProcessor<V>() {
        @Override
        public void handle(String attributeKey, String attributeValue, final V view) {
            if (view instanceof ProteusView) {
                view.setId(((ProteusView) view).getViewManager().getUniqueViewId(attributeValue));
            }

            // set view id resource name
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                final String resourceName = attributeValue;
                view.setAccessibilityDelegate(new View.AccessibilityDelegate() {
                    @Override
                    public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
                        super.onInitializeAccessibilityNodeInfo(host, info);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                            String normalizedResourceName;
                            if (!TextUtils.isEmpty(resourceName)) {
                                String id;
                                if (resourceName.startsWith(ID_STRING_START_PATTERN)) {
                                    id = resourceName.substring(ID_STRING_START_PATTERN.length());
                                } else if (resourceName.startsWith(ID_STRING_START_PATTERN1)) {
                                    id = resourceName.substring(ID_STRING_START_PATTERN1.length());
                                } else {
                                    id = resourceName;
                                }
                                normalizedResourceName = view.getContext().getPackageName()
                                        + ID_STRING_NORMALIZED_PATTERN + id;
                            } else {
                                normalizedResourceName = "";
                            }
                            info.setViewIdResourceName(normalizedResourceName);
                        }
                    }
                });
            }
        }
    });
    addHandler(Attributes.View.ContentDescription, new StringAttributeProcessor<V>() {
        @Override
        public void handle(String attributeKey, String attributeValue, V view) {
            view.setContentDescription(attributeValue);
        }
    });
    addHandler(Attributes.View.Clickable, new StringAttributeProcessor<V>() {
        @Override
        public void handle(String attributeKey, String attributeValue, V view) {
            boolean clickable = ParseHelper.parseBoolean(attributeValue);
            view.setClickable(clickable);
        }
    });
    addHandler(Attributes.View.Tag, new StringAttributeProcessor<V>() {
        @Override
        public void handle(String attributeKey, String attributeValue, V view) {
            view.setTag(attributeValue);
        }
    });
    addHandler(Attributes.View.Border, new JsonDataProcessor<V>() {
        @Override
        public void handle(String key, JsonElement value, V view) {
            Drawable border = Utils.getBorderDrawable(value, view.getContext());
            if (border == null) {
                return;
            }

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                //noinspection deprecation
                view.setBackgroundDrawable(border);
            } else {
                view.setBackground(border);
            }
        }
    });

    addHandler(Attributes.View.Enabled, new StringAttributeProcessor<V>() {
        @Override
        public void handle(String attributeKey, String attributeValue, V view) {
            boolean enabled = ParseHelper.parseBoolean(attributeValue);
            view.setEnabled(enabled);
        }
    });

    addHandler(Attributes.View.Style, new StringAttributeProcessor<V>() {
        @Override
        public void handle(String attributeKey, String attributeValue, V view) {
            ProteusViewManager viewManager = ((ProteusView) view).getViewManager();
            Styles styles = viewManager.getStyles();

            LayoutHandler handler = viewManager.getLayoutBuilder()
                    .getHandler(Utils.getPropertyAsString(viewManager.getLayout(), ProteusConstants.TYPE));
            if (styles == null) {
                return;
            }

            String[] styleSet = attributeValue.split(ProteusConstants.STYLE_DELIMITER);
            for (String styleName : styleSet) {
                if (styles.contains(styleName)) {
                    process(styles.getStyle(styleName), viewManager.getLayout(), (ProteusView) view,
                            (handler != null ? handler : ViewParser.this), viewManager.getLayoutBuilder());
                }
            }
        }

        private void process(Map<String, JsonElement> style, JsonObject layout, ProteusView proteusView,
                LayoutHandler handler, LayoutBuilder builder) {
            for (Map.Entry<String, JsonElement> attribute : style.entrySet()) {
                if (layout.has(attribute.getKey())) {
                    continue;
                }
                builder.handleAttribute(handler, proteusView, attribute.getKey(), attribute.getValue());
            }
        }
    });

    addHandler(Attributes.View.TransitionName, new StringAttributeProcessor<V>() {
        @Override
        public void handle(String attributeKey, String attributeValue, V view) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                view.setTransitionName(attributeValue);
            }
        }
    });

    addHandler(Attributes.View.RequiresFadingEdge, new StringAttributeProcessor<V>() {

        private final String NONE = "none";
        private final String BOTH = "both";
        private final String VERTICAL = "vertical";
        private final String HORIZONTAL = "horizontal";

        @Override
        public void handle(String attributeKey, String attributeValue, V view) {

            switch (attributeValue) {
            case NONE:
                view.setVerticalFadingEdgeEnabled(false);
                view.setHorizontalFadingEdgeEnabled(false);
                break;
            case BOTH:
                view.setVerticalFadingEdgeEnabled(true);
                view.setHorizontalFadingEdgeEnabled(true);
                break;
            case VERTICAL:
                view.setVerticalFadingEdgeEnabled(true);
                view.setHorizontalFadingEdgeEnabled(false);
                break;
            case HORIZONTAL:
                view.setVerticalFadingEdgeEnabled(false);
                view.setHorizontalFadingEdgeEnabled(true);
                break;
            default:
                view.setVerticalFadingEdgeEnabled(false);
                view.setHorizontalFadingEdgeEnabled(false);
                break;
            }
        }
    });

    addHandler(Attributes.View.FadingEdgeLength, new StringAttributeProcessor<V>() {
        @Override
        public void handle(String attributeKey, String attributeValue, V view) {
            view.setFadingEdgeLength(ParseHelper.parseInt(attributeValue));
        }
    });

    final HashMap<String, Integer> relativeLayoutParams = new HashMap<>();
    relativeLayoutParams.put(Attributes.View.Above.getName(), RelativeLayout.ABOVE);
    relativeLayoutParams.put(Attributes.View.AlignBaseline.getName(), RelativeLayout.ALIGN_BASELINE);
    relativeLayoutParams.put(Attributes.View.AlignBottom.getName(), RelativeLayout.ALIGN_BOTTOM);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        relativeLayoutParams.put(Attributes.View.AlignEnd.getName(), RelativeLayout.ALIGN_END);
    }

    relativeLayoutParams.put(Attributes.View.AlignLeft.getName(), RelativeLayout.ALIGN_LEFT);
    relativeLayoutParams.put(Attributes.View.AlignParentBottom.getName(), RelativeLayout.ALIGN_PARENT_BOTTOM);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        relativeLayoutParams.put(Attributes.View.AlignParentEnd.getName(), RelativeLayout.ALIGN_PARENT_END);
    }
    relativeLayoutParams.put(Attributes.View.AlignParentLeft.getName(), RelativeLayout.ALIGN_PARENT_LEFT);
    relativeLayoutParams.put(Attributes.View.AlignParentRight.getName(), RelativeLayout.ALIGN_PARENT_RIGHT);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        relativeLayoutParams.put(Attributes.View.AlignParentStart.getName(), RelativeLayout.ALIGN_PARENT_START);
    }
    relativeLayoutParams.put(Attributes.View.AlignParentTop.getName(), RelativeLayout.ALIGN_PARENT_TOP);
    relativeLayoutParams.put(Attributes.View.AlignRight.getName(), RelativeLayout.ALIGN_RIGHT);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        relativeLayoutParams.put(Attributes.View.AlignStart.getName(), RelativeLayout.ALIGN_START);
    }
    relativeLayoutParams.put(Attributes.View.AlignTop.getName(), RelativeLayout.ALIGN_TOP);

    relativeLayoutParams.put(Attributes.View.Below.getName(), RelativeLayout.BELOW);
    relativeLayoutParams.put(Attributes.View.CenterHorizontal.getName(), RelativeLayout.CENTER_HORIZONTAL);
    relativeLayoutParams.put(Attributes.View.CenterInParent.getName(), RelativeLayout.CENTER_IN_PARENT);
    relativeLayoutParams.put(Attributes.View.CenterVertical.getName(), RelativeLayout.CENTER_VERTICAL);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        relativeLayoutParams.put(Attributes.View.ToEndOf.getName(), RelativeLayout.END_OF);
    }
    relativeLayoutParams.put(Attributes.View.ToLeftOf.getName(), RelativeLayout.LEFT_OF);
    relativeLayoutParams.put(Attributes.View.ToRightOf.getName(), RelativeLayout.RIGHT_OF);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        relativeLayoutParams.put(Attributes.View.ToStartOf.getName(), RelativeLayout.START_OF);
    }

    StringAttributeProcessor<V> relativeLayoutProcessor = new StringAttributeProcessor<V>() {
        @Override
        public void handle(String attributeKey, String attributeValue, V view) {
            if (view instanceof ProteusView) {
                int id = ((ProteusView) view).getViewManager().getUniqueViewId(attributeValue);
                Integer rule = relativeLayoutParams.get(attributeKey);
                if (rule != null) {
                    ParseHelper.addRelativeLayoutRule(view, rule, id);
                }
            }
        }
    };

    StringAttributeProcessor<V> relativeLayoutBooleanProcessor = new StringAttributeProcessor<V>() {
        @Override
        public void handle(String attributeKey, String attributeValue, V view) {
            int trueOrFalse = ParseHelper.parseRelativeLayoutBoolean(attributeValue);
            Integer rule = relativeLayoutParams.get(attributeKey);
            if (rule != null) {
                ParseHelper.addRelativeLayoutRule(view, rule, trueOrFalse);
            }
        }
    };

    addHandler(Attributes.View.Above, relativeLayoutProcessor);
    addHandler(Attributes.View.AlignBaseline, relativeLayoutProcessor);
    addHandler(Attributes.View.AlignBottom, relativeLayoutProcessor);
    addHandler(Attributes.View.AlignEnd, relativeLayoutProcessor);
    addHandler(Attributes.View.AlignLeft, relativeLayoutProcessor);
    addHandler(Attributes.View.AlignRight, relativeLayoutProcessor);
    addHandler(Attributes.View.AlignStart, relativeLayoutProcessor);
    addHandler(Attributes.View.AlignTop, relativeLayoutProcessor);
    addHandler(Attributes.View.Below, relativeLayoutProcessor);
    addHandler(Attributes.View.ToEndOf, relativeLayoutProcessor);
    addHandler(Attributes.View.ToLeftOf, relativeLayoutProcessor);
    addHandler(Attributes.View.ToRightOf, relativeLayoutProcessor);
    addHandler(Attributes.View.ToStartOf, relativeLayoutProcessor);

    addHandler(Attributes.View.AlignParentBottom, relativeLayoutBooleanProcessor);
    addHandler(Attributes.View.AlignParentEnd, relativeLayoutBooleanProcessor);
    addHandler(Attributes.View.AlignParentLeft, relativeLayoutBooleanProcessor);
    addHandler(Attributes.View.AlignParentRight, relativeLayoutBooleanProcessor);
    addHandler(Attributes.View.AlignParentStart, relativeLayoutBooleanProcessor);
    addHandler(Attributes.View.AlignParentTop, relativeLayoutBooleanProcessor);
    addHandler(Attributes.View.CenterHorizontal, relativeLayoutBooleanProcessor);
    addHandler(Attributes.View.CenterInParent, relativeLayoutBooleanProcessor);
    addHandler(Attributes.View.CenterVertical, relativeLayoutBooleanProcessor);

    addHandler(Attributes.View.Animation, new TweenAnimationResourceProcessor<V>() {

        @Override
        public void setAnimation(V view, Animation animation) {
            view.setAnimation(animation);
        }
    });

    addHandler(Attributes.View.TextAlignment, new StringAttributeProcessor<V>() {

        @Override
        public void handle(String attributeKey, String attributeValue, V view) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                Integer textAlignment = ParseHelper.parseTextAlignment(attributeValue);
                if (null != textAlignment) {
                    //noinspection ResourceType
                    view.setTextAlignment(textAlignment);
                }
            }
        }
    });
}

From source file:com.flipkart.android.proteus.toolbox.Utils.java

License:Apache License

public static JsonObject mergeLayouts(JsonObject destination, JsonObject source) {
    JsonObject layout = new JsonObject();
    for (Map.Entry<String, JsonElement> entry : destination.entrySet()) {
        layout.add(entry.getKey(), entry.getValue());
    }//  w ww  . j  av  a  2s.c om
    boolean hasType = layout.has(ProteusConstants.TYPE);
    for (Map.Entry<String, JsonElement> entry : source.entrySet()) {
        if (ProteusConstants.TYPE.equals(entry.getKey()) && hasType) {
            continue;
        }
        if (ProteusConstants.DATA_CONTEXT.equals(entry.getKey())) {
            continue;
        }
        layout.add(entry.getKey(), entry.getValue());
    }
    return layout;
}

From source file:com.football.site.getdata.ScoreWebService.java

public static Fixtures GetFixture(String url) {
    Fixtures result = null;/*from  w  ww.  j av  a  2 s . co  m*/
    try {
        JsonParser parser = new JsonParser();
        String response = GetHttpClientResponse(url);
        Gson gson = new Gson();
        result = gson.fromJson(response, Fixtures.class);
        LinksFixtures lf = new LinksFixtures();
        JsonObject obj = parser.parse(response).getAsJsonObject();
        JsonObject linkler = obj.getAsJsonObject("_links");
        lf.setSelf(linkler.getAsJsonObject("self").get("href").getAsString());
        if (linkler.has("soccerseason")) {
            lf.setSoccerseason(linkler.getAsJsonObject("soccerseason").get("href").getAsString());
        }
        if (linkler.has("team")) {
            lf.setTeam(linkler.getAsJsonObject("team").get("href").getAsString());
        }
        result.setLinks(lf);
    } catch (Exception e) {
        HelperUtil.AddErrorLog(logger, e);
    }
    return result;
}

From source file:com.gcm.samples.friendlyping.GcmServer.java

License:Open Source License

public GcmServer(String apiKey, String senderId, String serviceName) {
    jsonParser = new JsonParser();
    gson = new GsonBuilder().create();
    String username = senderId + "@" + GCM_HOST;
    smackCcsClient = new SmackCcsClient(apiKey, username, serviceName, GCM_HOST, GCM_CCS_PORT);

    // Add the GcmPacketExtension as an extension provider.
    ProviderManager.addExtensionProvider(GCM_ELEMENT_NAME, GCM_NAMESPACE,
            new ExtensionElementProvider<GcmPacketExtension>() {
                @Override/*from w  ww  .  j  a v a 2 s. c  om*/
                public GcmPacketExtension parse(XmlPullParser parser, int initialDepth)
                        throws XmlPullParserException, IOException, SmackException {
                    String json = parser.nextText();
                    return new GcmPacketExtension(json);
                }
            });

    stanzaFilter = new StanzaFilter() {
        @Override
        public boolean accept(Stanza stanza) {
            // Accept messages from GCM CCS.
            if (stanza.hasExtension(GCM_ELEMENT_NAME, GCM_NAMESPACE)) {
                return true;
            }
            // Reject messages that are not from GCM CCS.
            return false;
        }
    };

    stanzaListener = new StanzaListener() {
        @Override
        public void processPacket(Stanza packet) throws SmackException.NotConnectedException {
            // Extract the GCM message from the packet.
            GcmPacketExtension packetExtension = (GcmPacketExtension) packet.getExtension(GCM_NAMESPACE);

            JsonObject jGcmMessage = jsonParser.parse(packetExtension.getJson()).getAsJsonObject();
            String from = jGcmMessage.get("from").getAsString();

            // If there is no message_type normal GCM message is assumed.
            if (!jGcmMessage.has("message_type")) {
                if (StringUtils.isNotEmpty(from)) {
                    JsonObject jData = jGcmMessage.get("data").getAsJsonObject();
                    onMessage(from, jData);

                    // Send Ack to CCS to confirm receipt of upstream message.
                    String messageId = jGcmMessage.get("message_id").getAsString();
                    if (StringUtils.isNotEmpty(messageId)) {
                        sendAck(from, messageId);
                    } else {
                        logger.log(Level.SEVERE, "Message ID is null or empty.");
                    }
                } else {
                    logger.log(Level.SEVERE, "From is null or empty.");
                }
            } else {
                // Handle message_type here.
                String messageType = jGcmMessage.get("message_type").getAsString();
                if (messageType.equals("ack")) {
                    // Handle ACK. Here the ack is logged, you may want to further process the ACK at this
                    // point.
                    String messageId = jGcmMessage.get("message_id").getAsString();
                    logger.info("ACK received for message " + messageId + " from " + from);
                } else if (messageType.equals("nack")) {
                    // Handle NACK. Here the nack is logged, you may want to further process the NACK at
                    // this point.
                    String messageId = jGcmMessage.get("message_id").getAsString();
                    logger.info("NACK received for message " + messageId + " from " + from);
                } else if (messageType.equals("control")) {
                    logger.info("Control message received.");
                    String controlType = jGcmMessage.get("control_type").getAsString();
                    if (controlType.equals("CONNECTION_DRAINING")) {
                        // Handle connection draining
                        // SmackCcsClient only maintains one connection the CCS to reduce complexity. A real
                        // world application should be capable of maintaining multiple connections to GCM,
                        // allowing the application to continue to onMessage for incoming messages on the
                        // draining connection and sending all new out going messages on a newly created
                        // connection.
                        logger.info("Current connection will be closed soon.");
                    } else {
                        // Currently the only control_type is CONNECTION_DRAINING, if new control messages
                        // are added they should be handled here.
                        logger.info("New control message has been received.");
                    }
                }
            }
        }
    };

    smackCcsClient.listen(stanzaListener, stanzaFilter);
}

From source file:com.getperka.client.AuthUtils.java

License:Apache License

private String getOrNull(JsonObject obj, String key) {
    return obj.has(key) ? obj.get(key).getAsString() : null;
}

From source file:com.getperka.flatpack.codexes.EntityCodex.java

License:Apache License

public void readProperties(T object, JsonObject element, DeserializationContext context) {
    context.pushPath("(EntityCodex.readProperties())" + object.getUuid());

    try {/*from   w ww . j a  va  2  s .c  o m*/
        // Ignore incoming data with just a UUID value to avoid unnecessary warnings
        if (element.entrySet().size() == 1 && element.has("uuid")) {
            return;
        }

        if (!context.checkAccess(object)) {
            return;
        }

        // Allow the object to see the data that's about to be applied
        for (Method m : preUnpackMethods) {
            if (m.getParameterTypes().length == 0) {
                m.invoke(object);
            } else {
                m.invoke(object, element);
            }
        }

        List<String> roles = context.getRoles();
        for (Property prop : typeContext.extractProperties(clazz)) {
            if (!prop.maySet(roles)) {
                continue;
            }

            String simplePropertyName = prop.getName();
            context.pushPath("." + simplePropertyName);
            try {
                Object value;
                if (prop.isEmbedded()) {
                    /*
                     * Embedded objects are never referred to by uuid in the payload, so an instance will
                     * need to be allocated before reading in the properties.
                     */
                    @SuppressWarnings("unchecked")
                    EntityCodex<HasUuid> codex = (EntityCodex<HasUuid>) prop.getCodex();
                    HasUuid embedded = codex.allocate(UUID.randomUUID(), context, false);
                    codex.readProperties(embedded, element, context);
                    value = embedded;
                } else {

                    @SuppressWarnings("unchecked")
                    Codex<Object> codex = (Codex<Object>) prop.getCodex();

                    // merchant would become merchantUuid
                    String payloadPropertyName = simplePropertyName + codex.getPropertySuffix();

                    // Ignore undefined property values, while allowing explicit nullification
                    if (!element.has(payloadPropertyName)) {
                        continue;
                    }

                    value = codex.read(element.get(payloadPropertyName), context);
                }

                if (value == null && prop.getSetter().getParameterTypes()[0].isPrimitive()) {
                    // Don't try to pass a null to a primitive setter
                    continue;
                }

                // Perhaps set the other side of a OneToMany relationship
                Property impliedPropery = prop.getImpliedProperty();
                if (impliedPropery != null && value != null) {
                    // Ensure that any linked property is also mutable
                    if (!impliedPropery.maySet(roles) || !checkAccess(value, context)) {
                        context.addWarning(object,
                                "Ignoring property %s because the inverse relationship (%s) may not be set",
                                prop.getName(), impliedPropery.getName());
                        continue;
                    }
                    context.addPostWork(new ImpliedPropertySetter(context, impliedPropery, value, object));
                }

                // Set the value
                prop.getSetter().invoke(object, value);

                // Record the value as having been set
                context.addModified(object, prop);
            } catch (Exception e) {
                context.fail(e);
            } finally {
                context.popPath();
            }
        }
    } catch (Exception e) {
        context.fail(e);
    } finally {
        context.popPath();
    }
}

From source file:com.github.api.v2.services.impl.RepositoryServiceImpl.java

License:Apache License

@Override
public void deleteRepository(String repositoryName) {
    GitHubApiUrlBuilder builder = createGitHubApiUrlBuilder(
            GitHubApiUrls.RepositoryApiUrls.DELETE_REPOSITORY_URL);
    String apiUrl = builder.withField(ParameterNames.REPOSITORY_NAME, repositoryName).buildUrl();
    JsonObject json = unmarshall(callApiPost(apiUrl, new HashMap<String, String>()));
    if (json.has("delete_token")) {
        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put(ParameterNames.DELETE_TOKEN, json.get("delete_token").getAsString());
        callApiPost(apiUrl, parameters);
    }//w  ww . j a  va2s  . c o  m
}

From source file:com.github.consiliens.harv.gson.IRequestLogRecordDeserializer.java

License:Open Source License

@Override
public IRequestLogRecord deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    // Follow same order as serializer for sanity.
    IRequestLogRecord record = null;/*  w  w  w  .java 2  s  . c om*/

    final JsonObject recordJson = json.getAsJsonObject();

    final long requestId = recordJson.get(R.requestId).getAsLong();
    final long requestTimestamp = recordJson.get(R.timestamp).getAsLong();
    final long requestMilliseconds = recordJson.get(R.requestMilliseconds).getAsLong();

    // HttpHost
    JsonObject hostJson = recordJson.getAsJsonObject(R.httpHost);

    final String hostName = hostJson.get(R.hostName).getAsString();
    final int port = hostJson.get(R.port).getAsInt();
    final String schemeName = hostJson.get(R.schemeName).getAsString();

    final HttpHost host = new HttpHost(hostName, port, schemeName);

    // Request
    final JsonObject requestJson = recordJson.getAsJsonObject(R.request);

    String requestEntityString = "";
    HttpRequest httpRequest = null;
    if (requestJson.has(R.entity)) {
        requestEntityString = requestJson.get(R.entity).getAsString();
    }

    // Must parse headers here.
    final Header[] requestHeaders = getHeaders(requestJson.getAsJsonArray(R.allHeaders));

    // Request params
    final HttpParams requestHttpParams = new BasicHttpParams();
    setParamsFromJson(requestHttpParams, requestJson);

    // Request RequestLine
    final JsonObject requestLineJson = requestJson.getAsJsonObject(R.requestLine);

    // Request RequestLine Protocol
    final ProtocolVersion requestProtocol = getProtocolVersion(
            requestLineJson.getAsJsonObject(R.protocolVersion));

    final String method = requestLineJson.get(R.method).getAsString();
    final String uri = requestLineJson.get(R.uri).getAsString();

    // Request is finished. Build the HttpRequest Object.
    if (requestEntityString.isEmpty()) {
        // non-entity request
        httpRequest = new BasicHttpRequest(method, uri, requestProtocol);
    } else {
        httpRequest = new BasicHttpEntityEnclosingRequest(method, uri, requestProtocol);

        ByteArrayEntity requestEntity = null;
        if (entitiesExternalPath.isEmpty()) {
            // From internal string.
            try {
                requestEntity = new ByteArrayEntity(requestEntityString.getBytes(UTF8));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {
            // From file.
            final String fileName = getEntityFileName(requestEntityString);
            try {
                requestEntity = new ByteArrayEntity(
                        Files.toByteArray(new File(entitiesExternalPath, fileName)));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        ((BasicHttpEntityEnclosingRequest) httpRequest).setEntity(requestEntity);
    }

    httpRequest.setHeaders(requestHeaders);
    httpRequest.setParams(requestHttpParams);

    // HttpResponse
    final JsonObject responseJson = recordJson.getAsJsonObject(R.response);
    final Header[] responseHeaders = getHeaders(requestJson.getAsJsonArray(R.allHeaders));

    // Response Entity
    String responseEntityString = "";
    if (responseJson.has(R.entity)) {
        responseEntityString = responseJson.get(R.entity).getAsString();
    }

    // Locale
    JsonObject localeJson = responseJson.getAsJsonObject(R.locale);
    final String language = localeJson.get(R.language).getAsString();
    final String country = localeJson.get(R.country).getAsString();
    String variant = "";

    // Variant might not exist.
    if (localeJson.has(R.variant))
        variant = localeJson.get(R.variant).getAsString();

    Locale locale = new Locale(language, country, variant);

    // Response params
    final HttpParams responseHttpParams = new BasicHttpParams();
    setParamsFromJson(responseHttpParams, responseJson);

    // StatusLine
    JsonObject statusLineJson = responseJson.getAsJsonObject(R.statusLine);

    // StatusLine Protocol Version
    final ProtocolVersion responseProtocol = getProtocolVersion(
            statusLineJson.getAsJsonObject(R.protocolVersion));
    final int statusCode = statusLineJson.get(R.statusCode).getAsInt();
    final String reasonPhrase = statusLineJson.get(R.reasonPhrase).getAsString();

    StatusLine responseStatus = new BasicStatusLine(responseProtocol, statusCode, reasonPhrase);

    // Default to using EnglishReasonPhraseCatalog
    final HttpResponse httpResponse = new BasicHttpResponse(responseStatus, EnglishReasonPhraseCatalog.INSTANCE,
            locale);

    httpResponse.setHeaders(responseHeaders);
    httpResponse.setParams(responseHttpParams);

    // Ensure entity exists before processing.
    if (!requestEntityString.isEmpty()) {
        ByteArrayEntity responseEntity = null;

        try {
            if (entitiesExternalPath.isEmpty()) {
                // From internal string.
                responseEntity = new ByteArrayEntity(responseEntityString.getBytes(UTF8));
            } else {
                // From file.
                final String fileName = getEntityFileName(requestEntityString);
                responseEntity = new ByteArrayEntity(
                        Files.toByteArray(new File(entitiesExternalPath, fileName)));
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        httpResponse.setEntity(responseEntity);
    }

    // RequestLogRecord's constructors are package private so use
    // reflection.
    try {
        final Constructor<RequestLogRecord> construct = RequestLogRecord.class.getDeclaredConstructor(
                long.class, HttpRequest.class, HttpResponse.class, HttpHost.class, long.class);
        construct.setAccessible(true);
        record = (RequestLogRecord) construct.newInstance(requestId, httpRequest, httpResponse, host,
                requestMilliseconds);

        // There's no get or set timestamp so use reflection.
        final Field timestampField = RequestLogRecord.class.getDeclaredField(R.timestamp);
        timestampField.setAccessible(true);
        timestampField.set(record, requestTimestamp);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return record;
}