Example usage for com.google.gson JsonElement getAsString

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

Introduction

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

Prototype

public String getAsString() 

Source Link

Document

convenience method to get this element as a string value.

Usage

From source file:com.ikanow.infinit.e.data_model.index.ElasticSearchManager.java

License:Apache License

public boolean addDocument(JsonElement docJson, String _id, boolean bAllowOverwrite, String sParentId) {

    if (null != _multiIndex) {
        throw new RuntimeException("addDocument not supported on multi-index manager");
    }// w  w w  .j  av  a 2 s  .com
    IndexRequestBuilder irb = _elasticClient.prepareIndex(_sIndexName, _sIndexType)
            .setSource(docJson.toString());
    if (null != _id) {
        irb.setId(_id);
    } //TESTED
    else { // If an _id is already specified use that
        JsonElement _idJson = docJson.getAsJsonObject().get("_id");
        if (null != _idJson) {
            _id = _idJson.getAsString();
            if (null != _id) {
                irb.setId(_id);
            }
        }
    } //TOTEST

    if (!bAllowOverwrite) {
        irb.setOpType(OpType.CREATE);
    } //TESTED

    if (null != sParentId) {
        irb.setParent(sParentId);
    }

    // This ensures that the write goes through if I can write to any nodes, which seems sensible
    // You could always check the response and handle minimal success like failure if you want
    irb.setConsistencyLevel(WriteConsistencyLevel.ONE);

    try {
        irb.execute().actionGet();
    } catch (org.elasticsearch.transport.RemoteTransportException e) {
        boolean bDocAlreadyExists = e
                .contains(org.elasticsearch.index.engine.DocumentAlreadyExistsEngineException.class) // 0.18
                || e.contains(org.elasticsearch.index.engine.DocumentAlreadyExistsException.class); // 0.19

        if (!bDocAlreadyExists) {
            throw e;
        }
        return false;
    }
    return true;
}

From source file:com.impetus.client.couchdb.CouchDBClient.java

License:Apache License

@Override
public <E> List<E> getColumnsById(String schemaName, String tableName, String pKeyColumnName,
        String inverseJoinColumnName, Object pKeyColumnValue, Class columnJavaType) {
    List<E> foreignKeys = new ArrayList<E>();

    URI uri = null;//from  www  . j  av a 2 s.c o m
    HttpResponse response = null;
    try {
        String q = "key=" + CouchDBUtils.appendQuotes(pKeyColumnValue);
        uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
                CouchDBConstants.URL_SEPARATOR + schemaName.toLowerCase() + CouchDBConstants.URL_SEPARATOR
                        + CouchDBConstants.DESIGN + tableName + CouchDBConstants.VIEW + pKeyColumnName,
                q, null);
        HttpGet get = new HttpGet(uri);
        get.addHeader("Accept", "application/json");
        response = httpClient.execute(get);

        InputStream content = response.getEntity().getContent();
        Reader reader = new InputStreamReader(content);
        JsonObject json = gson.fromJson(reader, JsonObject.class);

        JsonElement jsonElement = json.get("rows");

        if (jsonElement == null) {
            return foreignKeys;
        }

        JsonArray array = jsonElement.getAsJsonArray();
        for (JsonElement element : array) {
            JsonElement value = element.getAsJsonObject().get("value").getAsJsonObject()
                    .get(inverseJoinColumnName);
            if (value != null) {
                foreignKeys.add((E) PropertyAccessorHelper.fromSourceToTargetClass(columnJavaType, String.class,
                        value.getAsString()));
            }
        }
    } catch (Exception e) {
        log.error("Error while fetching column by id {}, Caused by {}.", pKeyColumnValue, e);
        throw new KunderaException(e);
    } finally {
        closeContent(response);
    }
    return foreignKeys;
}

From source file:com.impetus.client.couchdb.CouchDBClient.java

License:Apache License

@Override
public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,
        Object columnValue, Class entityClazz) {
    List foreignKeys = new ArrayList();
    HttpResponse response = null;/* w w w  . j  a v a 2s. c  o  m*/
    EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);
    try {
        String q = "key=" + CouchDBUtils.appendQuotes(columnValue);
        URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
                CouchDBConstants.URL_SEPARATOR + schemaName.toLowerCase() + CouchDBConstants.URL_SEPARATOR
                        + CouchDBConstants.DESIGN + tableName + CouchDBConstants.VIEW + columnName,
                q, null);
        HttpGet get = new HttpGet(uri);
        get.addHeader("Accept", "application/json");
        response = httpClient.execute(get);

        InputStream content = response.getEntity().getContent();
        Reader reader = new InputStreamReader(content);
        JsonObject json = gson.fromJson(reader, JsonObject.class);

        JsonElement jsonElement = json.get("rows");
        if (jsonElement == null) {
            return foreignKeys.toArray();
        }
        JsonArray array = jsonElement.getAsJsonArray();
        for (JsonElement element : array) {
            JsonElement value = element.getAsJsonObject().get("value").getAsJsonObject().get(pKeyName);
            if (value != null) {
                foreignKeys.add(PropertyAccessorHelper.fromSourceToTargetClass(
                        m.getIdAttribute().getBindableJavaType(), String.class, value.getAsString()));
            }
        }
    } catch (Exception e) {
        log.error("Error while fetching ids for column where column name is" + columnName
                + " and column value is {} , Caused by {}.", columnValue, e);
        throw new KunderaException(e);
    } finally {
        closeContent(response);
    }
    return foreignKeys.toArray();
}

From source file:com.impetus.client.couchdb.CouchDBClient.java

License:Apache License

@Override
public void deleteByColumn(String schemaName, String tableName, String columnName, Object columnValue) {
    URI uri = null;/*w  w w .  j  ava 2 s  .  c  om*/
    HttpResponse response = null;
    try {
        String q = "key=" + CouchDBUtils.appendQuotes(columnValue);
        uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
                CouchDBConstants.URL_SEPARATOR + schemaName.toLowerCase() + CouchDBConstants.URL_SEPARATOR
                        + CouchDBConstants.DESIGN + tableName + CouchDBConstants.VIEW + columnName,
                q, null);
        HttpGet get = new HttpGet(uri);
        get.addHeader("Accept", "application/json");
        response = httpClient.execute(get);

        InputStream content = response.getEntity().getContent();
        Reader reader = new InputStreamReader(content);

        JsonObject json = gson.fromJson(reader, JsonObject.class);

        JsonElement jsonElement = json.get("rows");

        closeContent(response);

        JsonArray array = jsonElement.getAsJsonArray();
        for (JsonElement element : array) {
            JsonObject jsonObject = element.getAsJsonObject().get("value").getAsJsonObject();

            JsonElement pkey = jsonObject.get("_id");

            onDelete(schemaName, pkey.getAsString(), response, jsonObject);
        }
    } catch (Exception e) {
        log.error("Error while deleting row by column where column name is " + columnName
                + " and column value is {}, Caused by {}.", columnValue, e);
        throw new KunderaException(e);
    } finally {
        closeContent(response);
    }
}

From source file:com.impetus.client.couchdb.CouchDBClient.java

License:Apache License

/**
 * On delete./*from w ww  .  ja va  2 s  . c om*/
 * 
 * @param schemaName
 *            the schema name
 * @param pKey
 *            the key
 * @param response
 *            the response
 * @param jsonObject
 *            the json object
 * @throws URISyntaxException
 *             the URI syntax exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ClientProtocolException
 *             the client protocol exception
 */
private void onDelete(String schemaName, Object pKey, HttpResponse response, JsonObject jsonObject)
        throws URISyntaxException, IOException, ClientProtocolException {
    URI uri;
    String q;
    JsonElement rev = jsonObject.get("_rev");

    StringBuilder builder = new StringBuilder();
    builder.append("rev=");
    builder.append(rev.getAsString());
    q = builder.toString();

    uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
            CouchDBConstants.URL_SEPARATOR + schemaName.toLowerCase() + CouchDBConstants.URL_SEPARATOR + pKey,
            q, null);

    HttpDelete delete = new HttpDelete(uri);

    response = httpClient.execute(delete);
    closeContent(response);
}

From source file:com.impetus.client.couchdb.CouchDBObjectMapper.java

License:Apache License

/**
 * Gets the entity from json./*  ww  w . j a v a 2  s .  com*/
 * 
 * @param entityClass
 *            the entity class
 * @param m
 *            the m
 * @param jsonObj
 *            the json obj
 * @param relations
 *            the relations
 * @param kunderaMetadata
 *            the kundera metadata
 * @return the entity from json
 */
static Object getEntityFromJson(Class<?> entityClass, EntityMetadata m, JsonObject jsonObj,
        List<String> relations, final KunderaMetadata kunderaMetadata) {// Entity object
    Object entity = null;

    // Map to hold property-name=>foreign-entity relations
    try {
        entity = KunderaCoreUtils.createNewInstance(entityClass);

        // Populate primary key column
        JsonElement rowKey = jsonObj.get(((AbstractAttribute) m.getIdAttribute()).getJPAColumnName());
        if (rowKey == null) {
            return null;
        }
        Class<?> idClass = null;
        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
                .getMetamodel(m.getPersistenceUnit());
        Map<String, Object> relationValue = null;
        idClass = m.getIdAttribute().getJavaType();
        if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType())) {
            Class javaType = m.getIdAttribute().getBindableJavaType();
            PropertyAccessorHelper.setId(entity, m, getObjectFromJson(rowKey.getAsJsonObject(), javaType,
                    metaModel.embeddable(javaType).getAttributes()));
        } else {
            PropertyAccessorHelper.setId(entity, m, PropertyAccessorHelper.fromSourceToTargetClass(idClass,
                    String.class, rowKey.getAsString()));
        }

        EntityType entityType = metaModel.entity(entityClass);

        String discriminatorColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();

        Set<Attribute> columns = entityType.getAttributes();

        for (Attribute column : columns) {
            JsonElement value = jsonObj.get(((AbstractAttribute) column).getJPAColumnName());
            if (!column.equals(m.getIdAttribute())
                    && !((AbstractAttribute) column).getJPAColumnName().equals(discriminatorColumn)
                    && value != null && !value.equals(JsonNull.INSTANCE)) {
                String fieldName = ((AbstractAttribute) column).getJPAColumnName();

                Class javaType = ((AbstractAttribute) column).getBindableJavaType();
                if (metaModel.isEmbeddable(javaType)) {
                    onViaEmbeddable(entityType, column, m, entity, metaModel.embeddable(javaType), jsonObj);
                } else if (!column.isAssociation()) {
                    setFieldValue(entity, column, value);
                } else if (relations != null) {
                    if (relationValue == null) {
                        relationValue = new HashMap<String, Object>();
                    }

                    if (relations.contains(fieldName)
                            && !fieldName.equals(((AbstractAttribute) m.getIdAttribute()).getJPAColumnName())) {
                        JsonElement colValue = jsonObj.get(((AbstractAttribute) column).getJPAColumnName());
                        if (colValue != null) {
                            String colFieldName = m.getFieldName(fieldName);
                            Attribute attribute = entityType.getAttribute(colFieldName);
                            EntityMetadata relationMetadata = KunderaMetadataManager
                                    .getEntityMetadata(kunderaMetadata, attribute.getJavaType());
                            Object colVal = PropertyAccessorHelper.fromSourceToTargetClass(
                                    relationMetadata.getIdAttribute().getJavaType(), String.class,
                                    colValue.getAsString());
                            relationValue.put(fieldName, colVal);
                        }
                    }
                }
            }
        }
        if (relationValue != null && !relationValue.isEmpty()) {
            EnhanceEntity e = new EnhanceEntity(entity, PropertyAccessorHelper.getId(entity, m), relationValue);
            return e;
        } else {
            return entity;
        }
    } catch (Exception e) {
        log.error("Error while extracting entity object from json, caused by {}.", e);
        throw new KunderaException(e);
    }
}

From source file:com.impetus.client.couchdb.CouchDBObjectMapper.java

License:Apache License

/**
 * Sets the field value.//from   www . j  a  v a2  s .  c  om
 * 
 * @param entity
 *            the entity
 * @param column
 *            the column
 * @param value
 *            the value
 */
private static void setFieldValue(Object entity, Attribute column, JsonElement value) {
    if (column.getJavaType().isAssignableFrom(byte[].class)) {
        PropertyAccessorHelper.set(entity, (Field) column.getJavaMember(),
                PropertyAccessorFactory.STRING.toBytes(value.getAsString()));
    } else {
        PropertyAccessorHelper.set(entity, (Field) column.getJavaMember(), PropertyAccessorHelper
                .fromSourceToTargetClass(column.getJavaType(), String.class, value.getAsString()));
    }
}

From source file:com.impetus.kundera.ycsb.benchmark.CouchDBNativeClient.java

License:Apache License

private void onDelete(String schemaName, Object pKey, HttpResponse response, JsonObject jsonObject)
        throws URISyntaxException, IOException, ClientProtocolException {
    URI uri;//w ww  . j av a2  s . c o m
    String q;
    JsonElement rev = jsonObject.get("_rev");

    StringBuilder builder = new StringBuilder();
    builder.append("rev=");
    builder.append(rev.getAsString());
    q = builder.toString();

    // uri = new URI(CouchDBConstants.PROTOCOL, null,
    // httpHost.getHostName(), httpHost.getPort(),
    // CouchDBConstants.URL_SAPRATOR + schemaName.toLowerCase() +
    // CouchDBConstants.URL_SAPRATOR + pKey, q,
    // null);

    // HttpDelete delete = new HttpDelete(uri);

    // response = httpClient.execute(delete);
    // CouchDBUtils.closeContent(response);
}

From source file:com.inkubator.hrm.service.impl.BioDataServiceImpl.java

@Override
@Transactional(readOnly = false, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public String saveBiodataRevisionWithApproval(Object modifiedEntity, String dataType, EmpData empData)
        throws Exception {

    //Jika Approval Definition untuk proses revisi biodata belum di buat, lempar BussinessException
    if (isApprovalDefinitionNotFound()) {
        throw new BussinessException("biodata.biodata_revision_doesnt_have_approval_def");

    }//from   w w w  .j a  va  2  s. c o m

    HrmUser requestUser = hrmUserDao.getByEmpDataId(empData.getId());

    //Dapatkan List Pending Approval Activity
    List<ApprovalActivity> listPreviousActivities = approvalActivityDao
            .getPendingRequest(requestUser.getUserId());

    //Filter hanya yang berasal dari proses request revisi biodata
    listPreviousActivities = Lambda.select(listPreviousActivities,
            Lambda.having(Lambda.on(ApprovalActivity.class).getApprovalDefinition().getName(),
                    Matchers.equalTo(HRMConstant.BIO_DATA_EDIT)));

    //Looping satu persatu
    for (ApprovalActivity approvalActivity : listPreviousActivities) {
        String pendingData = approvalActivity.getPendingData();
        Gson gson = JsonUtil.getHibernateEntityGsonBuilder().create();

        // dapatkan nilai dataType (jenis kelompok formulir biodata) dari pending approval activity
        JsonElement jsonElementDataType = gson.fromJson(pendingData, JsonObject.class).get("dataType");
        if (!jsonElementDataType.isJsonNull()) {

            String dataTypeFromJson = jsonElementDataType.getAsString();

            //Jika kelompok formulir dari pending Request sama dengan yang akan di ajukan sekarang, maka lempar BusinessException,
            //karena tidak boleh mengajukan perubahan biodata pada satu jenis kelompok formulir, 
            //jika sebelumnya sudah pernah ada pengajuan revisi pada jenis kelompok formulir tsb dan statusnya masih pending.
            if (StringUtils.equals(dataType, dataTypeFromJson)) {
                throw new BussinessException("biodata.error_revision_same_data_type_which_still_pending_found");
            }

        }

    }

    return this.saveRevision(modifiedEntity, dataType, empData, Boolean.FALSE, null);

}

From source file:com.inkubator.hrm.service.impl.BioDataServiceImpl.java

@Override
protected String getDetailSmsContentOfActivity(ApprovalActivity appActivity) {
    StringBuffer detail = new StringBuffer();
    HrmUser requester = hrmUserDao.getByUserId(appActivity.getRequestBy());
    String revisionAt = StringUtils.EMPTY;
    detail.append("Pengajuan Revisi Biodata oleh " + requester.getEmpData().getBioData().getFullName() + ". ");

    String pendingData = appActivity.getPendingData();
    Gson gson = JsonUtil.getHibernateEntityGsonBuilder().create();

    // dapatkan nilai dataType (jenis kelompok formulir biodata) dari pending approval activity
    JsonElement jsonElementDataType = gson.fromJson(pendingData, JsonObject.class).get("dataType");
    if (!jsonElementDataType.isJsonNull()) {

        String dataType = jsonElementDataType.getAsString();

        switch (dataType) {

        case HRMConstant.BIO_REV_DETAIL_BIO_DATA:
            revisionAt = "Data Detail Biodata";
            break;

        case HRMConstant.BIO_REV_ADDRESS:
            revisionAt = "Data Alamat";
            break;

        case HRMConstant.BIO_REV_CONTACT:
            revisionAt = "Data Kontak";
            break;

        case HRMConstant.BIO_REV_ID_CARD:
            revisionAt = "Data Kartu Identitas";
            break;

        case HRMConstant.BIO_REV_FAMILY:
            revisionAt = "Data Keluarga";
            break;

        case HRMConstant.BIO_REV_COMPANY_RELATION:
            revisionAt = "Data Relasi Perusahaan";
            break;

        case HRMConstant.BIO_REV_EDUCATION:
            revisionAt = "Data Pendidikan";
            break;

        case HRMConstant.BIO_REV_SKILL:
            revisionAt = "Data Keahlian";
            break;

        case HRMConstant.BIO_REV_SPESIFICATION_ABILITY:
            revisionAt = "Data Spesifikasi Kemampuan";
            break;

        case HRMConstant.BIO_REV_INTEREST:
            revisionAt = "Data Minat";
            break;

        default:/*from   w w w .  j a  va  2  s  .co  m*/
            break;
        }

    }

    detail.append("Jenis kelompok Biodata : " + revisionAt + ". ");
    return detail.toString();
}