Example usage for com.google.gson JsonPrimitive getAsString

List of usage examples for com.google.gson JsonPrimitive getAsString

Introduction

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

Prototype

@Override
public String getAsString() 

Source Link

Document

convenience method to get this element as a String.

Usage

From source file:org.runbuddy.libtomahawk.resolver.ScriptResolver.java

License:Open Source License

private void onTestConfigFinished(JsonPrimitive results) {
    int type = -1;
    String message = null;/* w  w  w . j a  v  a  2s  .  co  m*/
    if (results.isString()) {
        type = AuthenticatorManager.CONFIG_TEST_RESULT_TYPE_OTHER;
        message = results.getAsString();
    } else if (results.isNumber() && results.getAsInt() > 0 && results.getAsInt() < 8) {
        type = results.getAsInt();
    }
    Log.d(TAG, getName() + ": Config test result received. type: " + type + ", message:" + message);
    if (type == AuthenticatorManager.CONFIG_TEST_RESULT_TYPE_SUCCESS) {
        setEnabled(true);
    } else {
        setEnabled(false);
    }
    AuthenticatorManager.ConfigTestResultEvent event = new AuthenticatorManager.ConfigTestResultEvent();
    event.mComponent = ScriptResolver.this;
    event.mType = type;
    event.mMessage = message;
    EventBus.getDefault().post(event);
    AuthenticatorManager.showToast(getPrettyName(), event);
}

From source file:org.socraticgrid.workbench.classifier.ProcessClassifier.java

License:Apache License

protected ProcessClassifierResult parseAndClassifyProcess(String xmlDefinition) throws Exception {

    ProcessClassifierResult result = new ProcessClassifierResult();

    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader reader = factory.createXMLStreamReader(new ByteArrayInputStream(xmlDefinition.getBytes()));

    JsonParser jsonParser = new JsonParser();

    boolean parsingTextAnnotation = false;
    boolean parsingStartEvent = false;

    String currentTextAnnotationId = null;

    String startEventType = "Simple";

    String startEventNodeId = null;

    //Map of <textAnnotation's id, Fact Type name>
    Map<String, String> factTypeNodesIds = new HashMap<String, String>();

    //A List of <association's targetRef and association's sourceRef>
    List<Map<String, String>> associations = new ArrayList<Map<String, String>>();

    while (reader.hasNext()) {
        switch (reader.next()) {
        case XMLStreamReader.START_ELEMENT:
            if ("bpmn2".equals(reader.getName().getPrefix())
                    && "textAnnotation".equals(reader.getName().getLocalPart())) {
                parsingTextAnnotation = true;
                currentTextAnnotationId = reader.getAttributeValue("", "id");
            } else if ("bpmn2".equals(reader.getName().getPrefix())
                    && "startEvent".equals(reader.getName().getLocalPart())) {
                parsingStartEvent = true;
                startEventNodeId = reader.getAttributeValue("", "id");
            } else if ("bpmn2".equals(reader.getName().getPrefix())
                    && "association".equals(reader.getName().getLocalPart())) {
                String sourceRef = reader.getAttributeValue("", "sourceRef");
                String targetRef = reader.getAttributeValue("", "targetRef");

                Map<String, String> references = new HashMap<String, String>();
                references.put(targetRef, sourceRef);

                associations.add(references);
            } else if ("bpmn2".equals(reader.getName().getPrefix())
                    && "task".equals(reader.getName().getLocalPart())) {
                //<bpmn2:task id="_FDBDEFA7-D789-4440-BC5E-4295A39153B3" drools:bgcolor="#b1c2d6" drools:taskName="Appointment" name="Appointment">
                String taskType = reader.getAttributeValue("http://www.jboss.org/drools", "taskName");
                String name = reader.getAttributeValue("", "name");
                if (taskType != null && !taskType.trim().isEmpty()) {
                    WorkItemEntity workItemEntity = new WorkItemEntity();
                    workItemEntity.setType(taskType);
                    workItemEntity.setName(name);
                    result.addWorkItemEntity(workItemEntity);
                }//from   w  ww . jav  a2s . c  om
            } else if (parsingStartEvent && "bpmn2".equals(reader.getName().getPrefix())
                    && reader.getName().getLocalPart().endsWith("EventDefinition")) {
                startEventType = reader.getName().getLocalPart().substring(0,
                        reader.getName().getLocalPart().indexOf("EventDefinition"));
            } else if (parsingTextAnnotation && "bpmn2".equals(reader.getName().getPrefix())
                    && "text".equals(reader.getName().getLocalPart())) {
                String text = reader.getElementText();
                if (text.startsWith("KMRCustom--")) {
                    //<bpmn2:text>KMRCustom--Diagnosis--code--49320</bpmn2:text>
                    String[] parts = text.split("--");

                    FactTypeEntity factTypeEntity = new FactTypeEntity();
                    factTypeEntity.setName(parts[1]);

                    //store the id of the annotation for further analysis
                    factTypeNodesIds.put(currentTextAnnotationId, factTypeEntity.getName());

                    result.addFactTypeEntity(factTypeEntity);
                } else if (text.startsWith("KMRCustomCohort--")) {
                    //<bpmn2:text>KMRCustomCohort--{"cohortproperty_fieldb":"","cohortproperty_fielda":"123","resourceId":"_BEF705C5-FA86-404F-A253-24140C56BED1","fieldb_name":"fieldB","name":"","fielda_name":"fieldA","documentation":"","cohortentity":"ClassA"}</bpmn2:text>
                    String[] parts = text.split("--");
                    JsonPrimitive cohortEntity = jsonParser.parse(parts[1]).getAsJsonObject()
                            .getAsJsonPrimitive("cohortentity");
                    if (cohortEntity != null) {
                        CohortTypeEntity cohortTypeEntity = new CohortTypeEntity();
                        cohortTypeEntity.setName(cohortEntity.getAsString());
                        result.addCohortTypeEntity(cohortTypeEntity);
                    }
                }
            }
            break;
        case XMLStreamReader.END_ELEMENT:
            if ("bpmn2".equals(reader.getName().getPrefix())
                    && "textAnnotation".equals(reader.getName().getLocalPart())) {
                parsingTextAnnotation = false;
                currentTextAnnotationId = null;
            } else if ("bpmn2".equals(reader.getName().getPrefix())
                    && "startEvent".equals(reader.getName().getLocalPart())) {
                parsingStartEvent = false;
            }
        }
    }

    //process associations
    for (Map<String, String> associationRefs : associations) {
        String sourceRef = associationRefs.get(startEventNodeId);
        //has this association StartEvent as target?
        if (sourceRef != null) {
            //get the Fact Type
            String factTypeName = factTypeNodesIds.get(sourceRef);
            //mark sourceRef as starting Fact Type
            result.getFactsMap().get(factTypeName).setStarting(true);
        }
    }

    result.setStartEventType(startEventType);

    return result;
}

From source file:org.sonarqube.wsgenerator.Helper.java

License:Open Source License

public String setterParameterType(String parameter, JsonPrimitive parameterDescription) {
    if (parameter.equals("values") || parameter.equals("fieldValues") || parameter.equals("keys")) {
        return "List<String>";
    }/*from  w w w  .j  av  a  2s.  co m*/
    if (parameterDescription != null
            && parameterDescription.getAsString().matches(".*[Cc]omma.?separated.*|.*[Ll]ist of.*")) {
        return "List<String>";
    }
    return "String";
}

From source file:org.spongepowered.common.util.persistence.JsonTranslator.java

License:MIT License

private static Object convert(JsonElement element) {
    if (element.isJsonObject()) {
        MemoryDataView container = new MemoryDataContainer();
        for (Entry<String, JsonElement> entry : ((JsonObject) element).entrySet()) {
            Object value = convert(entry.getValue());
            if (value != null) {
                container.set(DataQuery.of(entry.getKey()), value);
            }/* ww w.  java2 s  . co m*/
        }
        return container;
    } else if (element.isJsonArray()) {
        return Lists.newArrayList(Iterables.transform((JsonArray) element, JsonTranslator::convert));
    } else if (element.isJsonPrimitive()) {
        JsonPrimitive primitive = (JsonPrimitive) element;
        if (primitive.isString()) {
            return primitive.getAsString();
        } else if (primitive.isBoolean()) {
            return primitive.getAsBoolean();
        } else if (primitive.isNumber()) {
            return primitive.getAsNumber();
        }
    }
    return null;
}

From source file:org.springframework.data.cloudant.core.UnmappedDataAdapter.java

License:Apache License

@Override
public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
            .registerTypeAdapter(DateTime.class, new DateTimeDataAdapter()).create();
    T doc = gson.fromJson(json, typeOfT);
    Map<String, Object> unmapped = new HashMap<>();
    List<String> nameList = getNestedField(doc.getClass());
    JsonObject object = json.getAsJsonObject();

    //add support for annotated fields ...hack for now
    nameList.add("_id");
    nameList.add("_rev");
    nameList.add("doc_type");
    for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
        if (!nameList.contains(entry.getKey())) {
            if (entry.getValue().isJsonArray()) {
                unmapped.put(entry.getKey(), entry.getValue().getAsJsonArray());
            } else if (entry.getValue().isJsonObject()) {
                unmapped.put(entry.getKey(), entry.getValue().getAsJsonObject());
            } else if (entry.getValue().isJsonPrimitive()) {
                JsonPrimitive v = entry.getValue().getAsJsonPrimitive();
                if (v.isBoolean()) {
                    unmapped.put(entry.getKey(), v.getAsBoolean());
                } else if (v.isNumber()) {
                    unmapped.put(entry.getKey(), v.getAsNumber());
                } else if (v.isString()) {
                    unmapped.put(entry.getKey(), v.getAsString());
                } else if (v.isJsonNull()) {
                    unmapped.put(entry.getKey(), null);
                }// w w w . ja  v a 2 s. c  om
            } else if (entry.getValue().isJsonNull()) {
                unmapped.put(entry.getKey(), null);
            } else {
                unmapped.put(entry.getKey(), entry.getValue().getAsString());
            }
        }

    }
    doc.setUnmappedFields(unmapped);
    return doc;
}

From source file:org.structr.core.JsonInputGSONAdapter.java

License:Open Source License

private static Object fromPrimitive(final JsonPrimitive p) {

    if (p.isNumber()) {

        Number number = p.getAsNumber();
        if (number instanceof Integer) {
            return number.intValue();
        } else {//  ww w  .  j av a 2 s . c om
            return number.doubleValue();
        }

    }

    return p.getAsString();
}

From source file:org.structr.core.rest.JsonInputGSONAdapter.java

License:Open Source License

public static Object fromPrimitive(final JsonPrimitive p) {

    if (p.isNumber()) {

        Number number = p.getAsNumber();

        // Detect if value is floating point
        if (p.getAsString().contains(".")) {

            return number.doubleValue();

        } else {/*from  w  w  w  . j  a  v  a  2  s .  co  m*/

            return number.longValue();

        }

    } else if (p.isBoolean()) {

        return p.getAsBoolean();

    }

    return p.getAsString();
}

From source file:org.tallison.gramreaper.ingest.schema.IndexSchemaDeserializer.java

License:Apache License

private NamedAnalyzer getAnalyzer(FieldDef fieldDef, JsonObject jsonObject, String whichAnalyzer,
        boolean allowNull, IndexSchema schema) {
    JsonPrimitive el = jsonObject.getAsJsonPrimitive(whichAnalyzer);
    if (el == null) {
        if (!fieldDef.fieldType.tokenized() || allowNull) {
            return null;
        } else {/*from  ww w  .j  av a 2 s  .com*/
            throw new IllegalArgumentException(
                    whichAnalyzer + " cannot be null for field: " + fieldDef.fieldName);
        }
    }
    String analyzerName = el.getAsString();
    Analyzer analyzer = schema.getAnalyzerByName(analyzerName);
    if (analyzer == null) {
        throw new IllegalArgumentException(
                "Must define analyzer named \"" + analyzerName + "\" " + "for field: " + fieldDef.fieldName);
    }
    return new NamedAnalyzer(analyzerName, analyzer);
}

From source file:org.thingsboard.rule.engine.action.TbCopyAttributesToEntityViewNode.java

License:Apache License

@Override
public void onMsg(TbContext ctx, TbMsg msg) {
    if (DataConstants.ATTRIBUTES_UPDATED.equals(msg.getType())
            || DataConstants.ATTRIBUTES_DELETED.equals(msg.getType())
            || SessionMsgType.POST_ATTRIBUTES_REQUEST.name().equals(msg.getType())) {
        if (!msg.getMetaData().getData().isEmpty()) {
            long now = System.currentTimeMillis();
            String scope = msg.getType().equals(SessionMsgType.POST_ATTRIBUTES_REQUEST.name())
                    ? DataConstants.CLIENT_SCOPE
                    : msg.getMetaData().getValue("scope");

            ListenableFuture<List<EntityView>> entityViewsFuture = ctx.getEntityViewService()
                    .findEntityViewsByTenantIdAndEntityIdAsync(ctx.getTenantId(), msg.getOriginator());

            DonAsynchron.withCallback(entityViewsFuture, entityViews -> {
                for (EntityView entityView : entityViews) {
                    long startTime = entityView.getStartTimeMs();
                    long endTime = entityView.getEndTimeMs();
                    if ((endTime != 0 && endTime > now && startTime < now)
                            || (endTime == 0 && startTime < now)) {
                        if (DataConstants.ATTRIBUTES_UPDATED.equals(msg.getType())
                                || SessionMsgType.POST_ATTRIBUTES_REQUEST.name().equals(msg.getType())) {
                            Set<AttributeKvEntry> attributes = JsonConverter
                                    .convertToAttributes(new JsonParser().parse(msg.getData()));
                            List<AttributeKvEntry> filteredAttributes = attributes.stream().filter(
                                    attr -> attributeContainsInEntityView(scope, attr.getKey(), entityView))
                                    .collect(Collectors.toList());
                            ctx.getTelemetryService().saveAndNotify(ctx.getTenantId(), entityView.getId(),
                                    scope, filteredAttributes, new FutureCallback<Void>() {
                                        @Override
                                        public void onSuccess(@Nullable Void result) {
                                            transformAndTellNext(ctx, msg, entityView);
                                        }

                                        @Override
                                        public void onFailure(Throwable t) {
                                            ctx.tellFailure(msg, t);
                                        }
                                    });/*  w ww  .j  a  v a  2  s  .  c o m*/
                        } else if (DataConstants.ATTRIBUTES_DELETED.equals(msg.getType())) {
                            List<String> attributes = new ArrayList<>();
                            for (JsonElement element : new JsonParser().parse(msg.getData()).getAsJsonObject()
                                    .get("attributes").getAsJsonArray()) {
                                if (element.isJsonPrimitive()) {
                                    JsonPrimitive value = element.getAsJsonPrimitive();
                                    if (value.isString()) {
                                        attributes.add(value.getAsString());
                                    }
                                }
                            }
                            List<String> filteredAttributes = attributes.stream()
                                    .filter(attr -> attributeContainsInEntityView(scope, attr, entityView))
                                    .collect(Collectors.toList());
                            if (filteredAttributes != null && !filteredAttributes.isEmpty()) {
                                ctx.getAttributesService().removeAll(ctx.getTenantId(), entityView.getId(),
                                        scope, filteredAttributes);
                                transformAndTellNext(ctx, msg, entityView);
                            }
                        }
                    }
                }
            }, t -> ctx.tellFailure(msg, t));
        } else {
            ctx.tellFailure(msg, new IllegalArgumentException("Message metadata is empty"));
        }
    } else {
        ctx.tellFailure(msg, new IllegalArgumentException("Unsupported msg type [" + msg.getType() + "]"));
    }
}

From source file:org.thingsboard.server.common.transport.adaptor.JsonConverter.java

License:Apache License

private static List<KeyValueProto> parseProtoValues(JsonObject valuesObject) {
    List<KeyValueProto> result = new ArrayList<>();
    for (Entry<String, JsonElement> valueEntry : valuesObject.entrySet()) {
        JsonElement element = valueEntry.getValue();
        if (element.isJsonPrimitive()) {
            JsonPrimitive value = element.getAsJsonPrimitive();
            if (value.isString()) {
                if (maxStringValueLength > 0 && value.getAsString().length() > maxStringValueLength) {
                    String message = String.format(
                            "String value length [%d] for key [%s] is greater than maximum allowed [%d]",
                            value.getAsString().length(), valueEntry.getKey(), maxStringValueLength);
                    throw new JsonSyntaxException(message);
                }//  ww w  . j a v a 2  s  .  co m
                if (isTypeCastEnabled && NumberUtils.isParsable(value.getAsString())) {
                    try {
                        result.add(buildNumericKeyValueProto(value, valueEntry.getKey()));
                    } catch (RuntimeException th) {
                        result.add(KeyValueProto.newBuilder().setKey(valueEntry.getKey())
                                .setType(KeyValueType.STRING_V).setStringV(value.getAsString()).build());
                    }
                } else {
                    result.add(KeyValueProto.newBuilder().setKey(valueEntry.getKey())
                            .setType(KeyValueType.STRING_V).setStringV(value.getAsString()).build());
                }
            } else if (value.isBoolean()) {
                result.add(KeyValueProto.newBuilder().setKey(valueEntry.getKey())
                        .setType(KeyValueType.BOOLEAN_V).setBoolV(value.getAsBoolean()).build());
            } else if (value.isNumber()) {
                result.add(buildNumericKeyValueProto(value, valueEntry.getKey()));
            } else {
                throw new JsonSyntaxException(CAN_T_PARSE_VALUE + value);
            }
        } else {
            throw new JsonSyntaxException(CAN_T_PARSE_VALUE + element);
        }
    }
    return result;
}