use of com.google.gson.GsonBuilder in project cryptonomica by Cryptonomica.
the class EthNodeAPI method ethAddDoc.
@ApiMethod(name = "addDoc", path = "addDoc", httpMethod = ApiMethod.HttpMethod.POST)
@SuppressWarnings("unused")
public // stores provided document on the Ethereum blockchain
Object ethAddDoc(// final HttpServletRequest httpServletRequest,
final User googleUser, //
final EthAddDocForm ethAddDocForm) throws IllegalArgumentException, UnauthorizedException {
// ensure registered user ( - may be later only for verified users):
CryptonomicaUser cryptonomicaUser = UserTools.ensureCryptonomicaRegisteredUser(googleUser);
// check form:
LOG.warning("ethAddDocForm" + ethAddDocForm + " from " + cryptonomicaUser.getEmail().getEmail());
if (ethAddDocForm == null || ethAddDocForm.getDocText() == null || ethAddDocForm.getDocText().length() < 12 || ethAddDocForm.getDocText().equals("")) {
throw new IllegalArgumentException("Provided text is to short or empty");
}
if (ethAddDocForm.getDocText() != null && ethAddDocForm.getDocText().length() > 1700) {
throw new IllegalArgumentException("Provided text is to long");
}
/* ---- Send request to Ethereum node: */
// make request obj:
EthNodeAPI.AddDocRequestObj addDocRequestObj = new EthNodeAPI.AddDocRequestObj();
String ethnodeApiKey = ofy().load().key(Key.create(AppSettings.class, "EthnodeApiKey")).now().getValue();
addDocRequestObj.setApikey(ethnodeApiKey);
addDocRequestObj.setPublisher(cryptonomicaUser.getEmail().getEmail());
addDocRequestObj.setText(ethAddDocForm.getDocText());
String urlAddress = "https://ethnode.cryptonomica.net/api/proofofexistence-add";
HTTPResponse httpResponse = HttpService.postWithPayload(urlAddress, addDocRequestObj.publisher, addDocRequestObj.text, ethnodeApiKey);
LOG.warning("httpResponse: " + new Gson().toJson(httpResponse));
// httpResponse: {"responseCode":200,"headers":[{"name":"Content-Type","value":"application/json"},
// {"name":"Date","value":"Mon, 11 Jul 2016 00:55:47 GMT"},{"name":"Connection","value":"keep-alive"},
// {"name":"Content-Length","value":"3448"}],"combinedHeadersMap":{"Content-Type":"application/json","Date":
// "Mon, 11 Jul 2016 00:55:47 GMT","Connection":"keep-alive","Content-Length":"3448"},
// "content":[123,34,116,120,72,97,115,104,34,58,34,48,120,99
// --- valid JSON with headers, and 'content' encoded
byte[] httpResponseContentBytes = httpResponse.getContent();
String httpResponseContentString = new String(httpResponseContentBytes, StandardCharsets.UTF_8);
// Test:
Object resObj = new Gson().fromJson(httpResponseContentString, Object.class);
LOG.warning("resObj: " + new Gson().toJson(resObj));
// resObj: {"txHash":"0xc1897ca491e7dec1537be5935734d863f0c17e3e154f22fa06a7e4d66384b6e2","tx":{"blockHash":"
// -- valid JSON !!!
// if success send an email to user:
final Queue queue = QueueFactory.getDefaultQueue();
Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
queue.add(TaskOptions.Builder.withUrl("/_ah/SendGridServlet").param("email", googleUser.getEmail()).param("messageSubject", "You have stored document on blockchain").param("messageText", "Hello! \n\n" + WordUtils.capitalize(cryptonomicaUser.getFirstName()) + " " + WordUtils.capitalize(cryptonomicaUser.getLastName()) + ",\n\n" + "You sent a document to the blockchain!" + "\n\n" + "Document text: " + "\n" + ethAddDocForm.getDocText() + "\n\n" + "with the following result: " + "\n" + httpResponseContentString + "\n\n" + "Best regards, \n\n" + "Cryptonomica team\n\n" + "if you think it's wrong or it is an error, please write to admin@cryptonomica.net \n"));
//
return resObj;
}
use of com.google.gson.GsonBuilder in project cryptonomica by Cryptonomica.
the class NewUserRegistrationAPI method registerNewUser.
@ApiMethod(name = "registerNewUser", path = "registerNewUser", httpMethod = ApiMethod.HttpMethod.POST)
@SuppressWarnings("unused")
public // creates a new cryptonomica user and saves him/her to database
NewUserRegistrationReturn registerNewUser(final HttpServletRequest httpServletRequest, final User googleUser, final NewUserRegistrationForm newUserRegistrationForm) throws Exception {
/* --- Ensure 1) user login, 2) not already registered:: */
UserTools.ensureNewCryptonomicaUser(googleUser);
/* --- Check form:*/
if (newUserRegistrationForm.getArmoredPublicPGPkeyBlock() == null || newUserRegistrationForm.getArmoredPublicPGPkeyBlock().length() == 0) {
throw new Exception("ASCII-armored PGP public key can not be empty");
// } else if (newUserRegistrationForm.getUserInfo() == null) {
// throw new Exception("Info can not be empty");
} else if (newUserRegistrationForm.getBirthday() == null) {
throw new Exception("Birthdate can not be empty");
}
/* --- user BirthDate */
Date userBirthDate = newUserRegistrationForm.getBirthday();
// TODO: add check
/* --- create PGPPublicKey from armored PGP key block: */
String userId = googleUser.getUserId();
String armoredPublicPGPkeyBlock = newUserRegistrationForm.getArmoredPublicPGPkeyBlock();
LOG.warning("[armoredPublicPGPkeyBlock]:");
LOG.warning(armoredPublicPGPkeyBlock);
PGPPublicKey pgpPublicKey = PGPTools.readPublicKeyFromString(armoredPublicPGPkeyBlock);
// create PGPPublicKeyData (Entity in DS) from PGPPublicKey:
PGPPublicKeyData pgpPublicKeyData = new PGPPublicKeyData(pgpPublicKey, armoredPublicPGPkeyBlock, userId);
pgpPublicKeyData.setUserBirthday(userBirthDate);
/* --- Check PGPPublic Key: */
// --- check key creation date/time:
Date creationTime = pgpPublicKey.getCreationTime();
if (creationTime.after(new Date())) {
throw new Exception("Invalid key creation Date/Time");
}
// -- bits size check:
if (pgpPublicKeyData.getBitStrength() < 2048) {
throw new Exception("Key Strength (bits size) should be min 2048 bits");
}
// -- email check:
if (!pgpPublicKeyData.getUserEmail().getEmail().toLowerCase().equals(googleUser.getEmail().toLowerCase())) {
throw new Exception("Email in the key's user ID should be the same as in account");
}
// -- key validity period check
Integer validDays = pgpPublicKey.getValidDays();
if (validDays > 366 * 2) {
throw new Exception("This key valid for more than 2 years");
} else if (validDays <= 0) {
//
throw new Exception("This key's validity term is incorrect");
}
// --- check for dublicates in DS:
List<PGPPublicKeyData> duplicates = ofy().load().type(PGPPublicKeyData.class).filter("fingerprintStr", pgpPublicKeyData.getFingerprint()).list();
if (!duplicates.isEmpty()) {
throw new Exception("The key with fingerprint" + pgpPublicKeyData.getFingerprint() + "already registered");
}
// create CryptonomicaUser:
CryptonomicaUser cryptonomicaUser = new CryptonomicaUser(googleUser, pgpPublicKeyData, newUserRegistrationForm);
// save new user and his key
Key<CryptonomicaUser> cryptonomicaUserKey = ofy().save().entity(cryptonomicaUser).now();
cryptonomicaUser = // ?
ofy().load().key(cryptonomicaUserKey).now();
Key<PGPPublicKeyData> pgpPublicKeyDataKey = ofy().save().entity(pgpPublicKeyData).now();
pgpPublicKeyData = ofy().load().key(pgpPublicKeyDataKey).now();
//
Login login = UserTools.registerLogin(httpServletRequest, googleUser);
//
ArrayList<PGPPublicKeyData> pgpPublicKeyDataArrayList = new ArrayList<>();
pgpPublicKeyDataArrayList.add(pgpPublicKeyData);
UserProfileGeneralView userProfileGeneralView = new UserProfileGeneralView(cryptonomicaUser, pgpPublicKeyDataArrayList);
// - for $rootScope.currentUser
userProfileGeneralView.setRegisteredCryptonomicaUser(Boolean.TRUE);
//
String messageToUser;
if (cryptonomicaUser != null) {
messageToUser = "User created successful";
} else {
messageToUser = "Error creating new user";
}
NewUserRegistrationReturn result = new NewUserRegistrationReturn(messageToUser, new PGPPublicKeyGeneralView(pgpPublicKeyData), userProfileGeneralView, new LoginView(login));
// send an email to user:
final Queue queue = QueueFactory.getDefaultQueue();
Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
queue.add(TaskOptions.Builder.withUrl("/_ah/SendGridServlet").param("email", googleUser.getEmail()).param("messageSubject", "You are registered on Cryptonomica server").param("messageText", "Congratulation! \n\n" + userProfileGeneralView.getFirstName().toUpperCase() + " " + userProfileGeneralView.getLastName().toUpperCase() + ",\n\n" + "You are registered on Cryptonomica server" + "\n\n" + "To verify your key online:" + "\n" + "1) go to 'My profile', 2) click on key ID and go to page with key data , " + "3) click green button 'Verify online' and follow instructions provided by web application" + "\n\n" + "Best regards, \n\n" + "Cryptonomica team\n\n" + new Date().toString() + "\n\n" + "if you think it's wrong or it is an error, please write to admin@cryptonomica.net \n"));
//
return result;
}
use of com.google.gson.GsonBuilder in project Robot by fo0.
the class Parser method read.
public static <T> T read(File file, Class<T> clazz) {
if (file == null || !file.exists())
return null;
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
T obj = new GsonBuilder().setPrettyPrinting().create().fromJson(new InputStreamReader(fis, "UTF-8"), TypeToken.getParameterized(clazz).getType());
if (obj == null)
return null;
return obj;
} catch (Exception e) {
Logger.error("failed parse File: " + file + " " + e);
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException e) {
Logger.error("failed to close FileInputStream " + e);
}
}
return null;
}
use of com.google.gson.GsonBuilder in project summer-bean by cn-cerc.
the class UserList method init.
private void init() {
if (buff.size() > 0)
return;
// 从缓存中读取
Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
IMemcache cache = Application.getMemcache();
String data = (String) cache.get(buffKey);
if (data != null && !"".equals(data)) {
Type type = new TypeToken<Map<String, UserRecord>>() {
}.getType();
Map<String, UserRecord> items = gson.fromJson(data, type);
for (String key : items.keySet()) {
buff.put(key, items.get(key));
}
log.debug(this.getClass().getName() + " 缓存成功!");
return;
}
// 从数据库中读取
SqlQuery ds = new SqlQuery(handle);
ds.add("select ID_,CorpNo_,Code_,Name_,QQ_,Mobile_,SuperUser_,");
ds.add("LastRemindDate_,EmailAddress_,RoleCode_,ProxyUsers_,Enabled_,DiyRole_ ");
ds.add("from %s ", SystemTable.get(SystemTable.getUserInfo));
ds.add("where CorpNo_='%s'", handle.getCorpNo());
ds.open();
while (ds.fetch()) {
String key = ds.getString("Code_");
UserRecord value = new UserRecord();
value.setId(ds.getString("ID_"));
value.setCorpNo(ds.getString("CorpNo_"));
value.setCode(ds.getString("Code_"));
value.setName(ds.getString("Name_"));
Map<String, Integer> priceValue = getPriceValue(ds.getString("Code_"));
value.setShowInUP(priceValue.get(UserOptions.ShowInUP));
value.setShowOutUP(priceValue.get(UserOptions.ShowOutUP));
value.setShowWholesaleUP(priceValue.get(UserOptions.ShowWholesaleUP));
value.setShowBottomUP(priceValue.get(UserOptions.ShowBottomUP));
value.setQq(ds.getString("QQ_"));
value.setMobile(ds.getString("Mobile_"));
value.setAdmin(ds.getBoolean("SuperUser_"));
value.setLastRemindDate(ds.getDateTime("LastRemindDate_").getDate());
value.setEmail(ds.getString("EmailAddress_"));
if (ds.getBoolean("DiyRole_"))
value.setRoleCode(ds.getString("Code_"));
else
value.setRoleCode(ds.getString("RoleCode_"));
value.setProxyUsers(ds.getString("ProxyUsers_"));
value.setEnabled(ds.getBoolean("Enabled_"));
buff.put(key, value);
}
// 存入到缓存中
cache.set(buffKey, gson.toJson(buff));
log.debug(this.getClass().getName() + " 缓存初始化!");
}
use of com.google.gson.GsonBuilder in project ranger by apache.
the class RangerAdminClientImpl method init.
public void init(String serviceName, String appId, String configPropertyPrefix) {
Gson gson = null;
try {
gson = new GsonBuilder().setDateFormat("yyyyMMdd-HH:mm:ss.SSS-Z").setPrettyPrinting().create();
} catch (Throwable excp) {
LOG.error("RangerAdminClientImpl: failed to create GsonBuilder object", excp);
}
this.gson = gson;
}
Aggregations