use of org.json.JSONTokener in project google-cloud-java by GoogleCloudPlatform.
the class ServiceOptions method getServiceAccountProjectId.
protected static String getServiceAccountProjectId() {
String project = null;
String credentialsPath = System.getenv("GOOGLE_APPLICATION_CREDENTIALS");
if (credentialsPath != null) {
try (InputStream credentialsStream = new FileInputStream(credentialsPath)) {
JSONObject json = new JSONObject(new JSONTokener(credentialsStream));
project = json.getString("project_id");
} catch (IOException | JSONException ex) {
// ignore
}
}
return project;
}
use of org.json.JSONTokener in project weex-example by KalicyZhou.
the class BookResultInfoRetriever method retrieveSupplementalInfo.
@Override
void retrieveSupplementalInfo() throws IOException {
CharSequence contents = HttpHelper.downloadViaHttp("https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn, HttpHelper.ContentType.JSON);
if (contents.length() == 0) {
return;
}
String title;
String pages;
Collection<String> authors = null;
try {
JSONObject topLevel = (JSONObject) new JSONTokener(contents.toString()).nextValue();
JSONArray items = topLevel.optJSONArray("items");
if (items == null || items.isNull(0)) {
return;
}
JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
if (volumeInfo == null) {
return;
}
title = volumeInfo.optString("title");
pages = volumeInfo.optString("pageCount");
JSONArray authorsArray = volumeInfo.optJSONArray("authors");
if (authorsArray != null && !authorsArray.isNull(0)) {
authors = new ArrayList<>(authorsArray.length());
for (int i = 0; i < authorsArray.length(); i++) {
authors.add(authorsArray.getString(i));
}
}
} catch (JSONException e) {
throw new IOException(e);
}
Collection<String> newTexts = new ArrayList<>();
maybeAddText(title, newTexts);
maybeAddTextSeries(authors, newTexts);
maybeAddText(pages == null || pages.isEmpty() ? null : pages + "pp.", newTexts);
String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context) + "/search?tbm=bks&source=zxing&q=";
append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
}
use of org.json.JSONTokener in project phoenix by apache.
the class CsvEventSerializer method upsertEvents.
@Override
public void upsertEvents(List<Event> events) throws SQLException {
Preconditions.checkNotNull(events);
Preconditions.checkNotNull(connection);
Preconditions.checkNotNull(this.upsertStatement);
boolean wasAutoCommit = connection.getAutoCommit();
connection.setAutoCommit(false);
try (PreparedStatement colUpsert = connection.prepareStatement(upsertStatement)) {
String value = null;
Integer sqlType = null;
for (Event event : events) {
byte[] payloadBytes = event.getBody();
if (payloadBytes == null || payloadBytes.length == 0) {
continue;
}
String payload = new String(payloadBytes);
CSVRecord csvRecord = csvLineParser.parse(payload);
if (colNames.size() != csvRecord.size()) {
logger.debug("payload data {} doesn't match the fields mapping {} ", payload, colNames);
continue;
}
Map<String, String> data = new HashMap<String, String>();
for (int i = 0; i < csvRecord.size(); i++) {
data.put(colNames.get(i), csvRecord.get(i));
}
Collection<String> values = data.values();
if (values.contains(null)) {
logger.debug("payload data {} doesn't match the fields mapping {} ", payload, colNames);
continue;
}
int index = 1;
int offset = 0;
for (int i = 0; i < colNames.size(); i++, offset++) {
if (columnMetadata[offset] == null) {
continue;
}
String colName = colNames.get(i);
value = data.get(colName);
sqlType = columnMetadata[offset].getSqlType();
PDataType pDataType = PDataType.fromTypeId(sqlType);
Object upsertValue;
if (pDataType.isArrayType()) {
String arrayJson = Arrays.toString(value.split(csvArrayDelimiter));
JSONArray jsonArray = new JSONArray(new JSONTokener(arrayJson));
Object[] vals = new Object[jsonArray.length()];
for (int x = 0; x < jsonArray.length(); x++) {
vals[x] = jsonArray.get(x);
}
String baseTypeSqlName = PDataType.arrayBaseType(pDataType).getSqlTypeName();
Array array = connection.createArrayOf(baseTypeSqlName, vals);
upsertValue = pDataType.toObject(array, pDataType);
} else {
upsertValue = pDataType.toObject(value);
}
if (upsertValue != null) {
colUpsert.setObject(index++, upsertValue, sqlType);
} else {
colUpsert.setNull(index++, sqlType);
}
}
// add headers if necessary
Map<String, String> headerValues = event.getHeaders();
for (int i = 0; i < headers.size(); i++, offset++) {
String headerName = headers.get(i);
String headerValue = headerValues.get(headerName);
sqlType = columnMetadata[offset].getSqlType();
Object upsertValue = PDataType.fromTypeId(sqlType).toObject(headerValue);
if (upsertValue != null) {
colUpsert.setObject(index++, upsertValue, sqlType);
} else {
colUpsert.setNull(index++, sqlType);
}
}
if (autoGenerateKey) {
sqlType = columnMetadata[offset].getSqlType();
String generatedRowValue = this.keyGenerator.generate();
Object rowkeyValue = PDataType.fromTypeId(sqlType).toObject(generatedRowValue);
colUpsert.setObject(index++, rowkeyValue, sqlType);
}
colUpsert.execute();
}
connection.commit();
} catch (Exception ex) {
logger.error("An error {} occurred during persisting the event ", ex.getMessage());
throw new SQLException(ex.getMessage());
} finally {
if (wasAutoCommit) {
connection.setAutoCommit(true);
}
}
}
use of org.json.JSONTokener in project phoenix by apache.
the class JsonEventSerializer method upsertEvents.
@Override
public void upsertEvents(List<Event> events) throws SQLException {
Preconditions.checkNotNull(events);
Preconditions.checkNotNull(connection);
Preconditions.checkNotNull(this.upsertStatement);
Preconditions.checkArgument(isProperMapping, "Please verify fields mapping is not properly done..");
boolean wasAutoCommit = connection.getAutoCommit();
connection.setAutoCommit(false);
try (PreparedStatement colUpsert = connection.prepareStatement(upsertStatement)) {
String value = null;
Integer sqlType = null;
JSONObject inputJson = new JSONObject();
for (Event event : events) {
byte[] payloadBytes = event.getBody();
if (payloadBytes == null || payloadBytes.length == 0) {
continue;
}
String payload = new String(payloadBytes);
try {
inputJson = new JSONObject(payload);
} catch (Exception e) {
logger.debug("payload is not proper json");
continue;
}
Map<String, String> data = new HashMap<String, String>();
for (String colName : colNames) {
String pattern = colName;
if (jsonSchema.has(colName)) {
Object obj = jsonSchema.opt(colName);
if (null != obj) {
pattern = obj.toString();
}
}
pattern = "$." + pattern;
value = getPatternData(inputJson, pattern);
// if field mapping data is null then look for column data
if (null == value && partialSchema) {
pattern = "$." + colName;
value = getPatternData(inputJson, pattern);
}
data.put(colName, value);
}
Collection<String> values = data.values();
if (values.contains(null)) {
logger.debug("payload data {} doesn't match the fields mapping {} ", inputJson, jsonSchema);
continue;
}
int index = 1;
int offset = 0;
for (int i = 0; i < colNames.size(); i++, offset++) {
if (columnMetadata[offset] == null) {
continue;
}
String colName = colNames.get(i);
value = data.get(colName);
sqlType = columnMetadata[offset].getSqlType();
PDataType pDataType = PDataType.fromTypeId(sqlType);
Object upsertValue;
if (pDataType.isArrayType()) {
JSONArray jsonArray = new JSONArray(new JSONTokener(value));
Object[] vals = new Object[jsonArray.length()];
for (int x = 0; x < jsonArray.length(); x++) {
vals[x] = jsonArray.get(x);
}
String baseTypeSqlName = PDataType.arrayBaseType(pDataType).getSqlTypeName();
Array array = connection.createArrayOf(baseTypeSqlName, vals);
upsertValue = pDataType.toObject(array, pDataType);
} else {
upsertValue = pDataType.toObject(value);
}
if (upsertValue != null) {
colUpsert.setObject(index++, upsertValue, sqlType);
} else {
colUpsert.setNull(index++, sqlType);
}
}
// add headers if necessary
Map<String, String> headerValues = event.getHeaders();
for (int i = 0; i < headers.size(); i++, offset++) {
String headerName = headers.get(i);
String headerValue = headerValues.get(headerName);
sqlType = columnMetadata[offset].getSqlType();
Object upsertValue = PDataType.fromTypeId(sqlType).toObject(headerValue);
if (upsertValue != null) {
colUpsert.setObject(index++, upsertValue, sqlType);
} else {
colUpsert.setNull(index++, sqlType);
}
}
if (autoGenerateKey) {
sqlType = columnMetadata[offset].getSqlType();
String generatedRowValue = this.keyGenerator.generate();
Object rowkeyValue = PDataType.fromTypeId(sqlType).toObject(generatedRowValue);
colUpsert.setObject(index++, rowkeyValue, sqlType);
}
colUpsert.execute();
}
connection.commit();
} catch (Exception ex) {
logger.error("An error {} occurred during persisting the event ", ex.getMessage());
throw new SQLException(ex.getMessage());
} finally {
if (wasAutoCommit) {
connection.setAutoCommit(true);
}
}
}
use of org.json.JSONTokener in project qi4j-sdk by Qi4j.
the class JSONMapEntityStoreMixin method readEntityState.
protected JSONEntityState readEntityState(DefaultEntityStoreUnitOfWork unitOfWork, Reader entityState) throws EntityStoreException {
try {
Module module = unitOfWork.module();
JSONObject jsonObject = new JSONObject(new JSONTokener(entityState));
EntityStatus status = EntityStatus.LOADED;
String version = jsonObject.getString(JSONKeys.VERSION);
long modified = jsonObject.getLong(JSONKeys.MODIFIED);
String identity = jsonObject.getString(JSONKeys.IDENTITY);
// Check if NamedAssociation is supported
if (!jsonObject.has(JSONKeys.NAMED_ASSOCIATIONS)) {
jsonObject.put(JSONKeys.NAMED_ASSOCIATIONS, new JSONObject());
}
// Check if version is correct
String currentAppVersion = jsonObject.optString(JSONKeys.APPLICATION_VERSION, "0.0");
if (!currentAppVersion.equals(application.version())) {
if (migration != null) {
migration.migrate(jsonObject, application.version(), this);
} else {
// Do nothing - set version to be correct
jsonObject.put(JSONKeys.APPLICATION_VERSION, application.version());
}
LoggerFactory.getLogger(getClass()).debug("Updated version nr on " + identity + " from " + currentAppVersion + " to " + application.version());
// State changed
status = EntityStatus.UPDATED;
}
String type = jsonObject.getString(JSONKeys.TYPE);
EntityDescriptor entityDescriptor = module.entityDescriptor(type);
if (entityDescriptor == null) {
throw new EntityTypeNotFoundException(type);
}
return new JSONEntityState(unitOfWork, valueSerialization, version, modified, EntityReference.parseEntityReference(identity), status, entityDescriptor, jsonObject);
} catch (JSONException e) {
throw new EntityStoreException(e);
}
}
Aggregations