List of usage examples for com.google.gson JsonElement getAsLong
public long getAsLong()
From source file:com.fooock.shodan.model.banner.BannerDeserializer.java
License:Open Source License
@Override public List<Banner> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { final List<Banner> banners = new ArrayList<>(); if (json.isJsonNull()) { return banners; }/*from w w w. j ava 2 s . c o m*/ JsonArray jsonArray = json.getAsJsonArray(); if (jsonArray.isJsonNull()) { return banners; } for (JsonElement element : jsonArray) { JsonObject jsonObject = element.getAsJsonObject(); JsonElement port = jsonObject.get("port"); JsonElement ip = jsonObject.get("ip"); JsonElement asn = jsonObject.get("asn"); JsonElement data = jsonObject.get("data"); JsonElement ipStr = jsonObject.get("ip_str"); JsonElement ipv6 = jsonObject.get("ipv6"); JsonElement timestamp = jsonObject.get("timestamp"); JsonElement hostnames = jsonObject.get("hostnames"); JsonElement domains = jsonObject.get("domains"); JsonElement location = jsonObject.get("location"); JsonElement options = jsonObject.get("opts"); JsonElement metadata = jsonObject.get("_shodan"); JsonElement ssl = jsonObject.get("ssl"); JsonElement uptime = jsonObject.get("uptime"); JsonElement link = jsonObject.get("link"); JsonElement title = jsonObject.get("title"); JsonElement html = jsonObject.get("html"); JsonElement product = jsonObject.get("product"); JsonElement version = jsonObject.get("version"); JsonElement isp = jsonObject.get("isp"); JsonElement os = jsonObject.get("os"); JsonElement transport = jsonObject.get("transport"); JsonElement devicetype = jsonObject.get("devicetype"); JsonElement info = jsonObject.get("info"); JsonElement cpe = jsonObject.get("cpe"); final Banner banner = new Banner(); if (port == null || port.isJsonNull()) { banner.setPort(0); } else { banner.setPort(port.getAsInt()); } if (ip == null || ip.isJsonNull()) { banner.setIp(0); } else { banner.setIp(ip.getAsLong()); } if (asn == null || asn.isJsonNull()) { banner.setAsn("unknown"); } else { banner.setAsn(asn.getAsString()); } if (data == null || data.isJsonNull()) { banner.setData("unknown"); } else { banner.setData(data.getAsString()); } if (ipStr == null || ipStr.isJsonNull()) { banner.setIpStr("unknown"); } else { banner.setIpStr(ipStr.getAsString()); } if (ipv6 == null || ipv6.isJsonNull()) { banner.setIpv6("unknown"); } else { banner.setIpv6(ipv6.getAsString()); } if (timestamp == null || timestamp.isJsonNull()) { banner.setTimestamp("unknown"); } else { banner.setTimestamp(timestamp.getAsString()); } if (hostnames == null || hostnames.isJsonNull()) { banner.setHostnames(new String[0]); } else { JsonArray hostnamesAsJsonArray = hostnames.getAsJsonArray(); String[] hostnameArray = new String[hostnamesAsJsonArray.size()]; for (int i = 0; i < hostnamesAsJsonArray.size(); i++) { hostnameArray[i] = hostnamesAsJsonArray.get(i).getAsString(); } banner.setHostnames(hostnameArray); } if (domains == null || domains.isJsonNull()) { banner.setDomains(new String[0]); } else { JsonArray domainsAsJsonArray = domains.getAsJsonArray(); String[] domainsArray = new String[domainsAsJsonArray.size()]; for (int i = 0; i < domainsAsJsonArray.size(); i++) { domainsArray[i] = domainsAsJsonArray.get(i).getAsString(); } banner.setDomains(domainsArray); } if (location == null || location.isJsonNull()) { banner.setLocation(new Location()); } else { JsonObject locationAsJsonObject = location.getAsJsonObject(); JsonElement areaCode = locationAsJsonObject.get("area_code"); JsonElement latitude = locationAsJsonObject.get("latitude"); JsonElement longitude = locationAsJsonObject.get("longitude"); JsonElement city = locationAsJsonObject.get("city"); JsonElement regionCode = locationAsJsonObject.get("region_code"); JsonElement postalCode = locationAsJsonObject.get("postal_code"); JsonElement dmaCode = locationAsJsonObject.get("dma_code"); JsonElement countryCode = locationAsJsonObject.get("country_code"); JsonElement countryCode3 = locationAsJsonObject.get("country_code3"); JsonElement countryName = locationAsJsonObject.get("country_name"); Location locationObject = new Location(); if (areaCode == null || areaCode.isJsonNull()) { locationObject.setAreaCode(0); } else { locationObject.setAreaCode(areaCode.getAsInt()); } if (latitude == null || latitude.isJsonNull()) { locationObject.setLatitude(0.0); } else { locationObject.setLatitude(latitude.getAsDouble()); } if (longitude == null || location.isJsonNull()) { locationObject.setLongitude(0.0); } else { locationObject.setLongitude(longitude.getAsDouble()); } if (city == null || city.isJsonNull()) { locationObject.setCity("unknown"); } else { locationObject.setCity(city.getAsString()); } if (regionCode == null || regionCode.isJsonNull()) { locationObject.setRegionCode("unknown"); } else { locationObject.setRegionCode(regionCode.getAsString()); } if (postalCode == null || postalCode.isJsonNull()) { locationObject.setPostalCode("unknown"); } else { locationObject.setPostalCode(postalCode.getAsString()); } if (dmaCode == null || dmaCode.isJsonNull()) { locationObject.setDmaCode("unknown"); } else { locationObject.setDmaCode(dmaCode.getAsString()); } if (countryCode == null || countryCode.isJsonNull()) { locationObject.setCountryCode("unknown"); } else { locationObject.setCountryCode(countryCode.getAsString()); } if (countryCode3 == null || countryCode3.isJsonNull()) { locationObject.setCountryCode3("unknown"); } else { locationObject.setCountryCode3(countryCode3.getAsString()); } if (countryName == null || countryName.isJsonNull()) { locationObject.setCountryName("unknown"); } else { locationObject.setCountryName(countryName.getAsString()); } banner.setLocation(locationObject); } final Options opts = new Options(); if (options == null || options.isJsonNull()) { opts.setRaw("unknown"); } else { JsonObject object = options.getAsJsonObject(); JsonElement raw = object.get("raw"); if (raw == null || raw.isJsonNull()) { opts.setRaw("unknown"); } else { opts.setRaw(raw.getAsString()); } } banner.setOptions(opts); final Metadata shodanMetadata = new Metadata(); if (metadata == null || metadata.isJsonNull()) { shodanMetadata.setCrawler("unknown"); shodanMetadata.setId("unknown"); shodanMetadata.setModule("unknown"); } else { JsonObject metadataAsJsonObject = metadata.getAsJsonObject(); JsonElement crawler = metadataAsJsonObject.get("crawler"); JsonElement id = metadataAsJsonObject.get("id"); JsonElement module = metadataAsJsonObject.get("module"); if (crawler == null || crawler.isJsonNull()) { shodanMetadata.setCrawler("unknown"); } else { shodanMetadata.setCrawler(crawler.getAsString()); } if (id == null || id.isJsonNull()) { shodanMetadata.setId("unknown"); } else { shodanMetadata.setId(id.getAsString()); } if (module == null || module.isJsonNull()) { shodanMetadata.setModule("unknown"); } else { shodanMetadata.setModule(module.getAsString()); } } banner.setMetadata(shodanMetadata); final SslInfo sslInfo = new SslInfo(); if (ssl == null || ssl.isJsonNull()) { banner.setSslEnabled(false); } else { banner.setSslEnabled(true); JsonObject sslAsJsonObject = ssl.getAsJsonObject(); JsonElement chain = sslAsJsonObject.get("chain"); JsonArray chainAsJsonArray = chain.getAsJsonArray(); String[] chainArray = new String[chainAsJsonArray.size()]; for (int i = 0; i < chainAsJsonArray.size(); i++) { chainArray[i] = chainAsJsonArray.get(i).getAsString(); } sslInfo.setChain(chainArray); JsonElement versions = sslAsJsonObject.get("versions"); JsonArray versionAsJsonArray = versions.getAsJsonArray(); String[] versionsArray = new String[versionAsJsonArray.size()]; for (int i = 0; i < versionsArray.length; i++) { versionsArray[i] = versionAsJsonArray.get(i).getAsString(); } sslInfo.setVersions(versionsArray); JsonElement cipher = sslAsJsonObject.get("cipher"); JsonObject cipherAsJsonObject = cipher.getAsJsonObject(); JsonElement bits = cipherAsJsonObject.get("bits"); JsonElement cipherVersion = cipherAsJsonObject.get("version"); JsonElement name = cipherAsJsonObject.get("name"); final Cipher cipherObject = new Cipher(); if (bits != null && !bits.isJsonNull()) { cipherObject.setBits(bits.getAsInt()); } if (cipherVersion != null && !cipherVersion.isJsonNull()) { cipherObject.setVersion(cipherVersion.getAsString()); } else { cipherObject.setVersion("unknown"); } if (name == null || name.isJsonNull()) { cipherObject.setName("unknown"); } else { cipherObject.setName(name.getAsString()); } sslInfo.setCipher(cipherObject); JsonElement dhparams = sslAsJsonObject.get("dhparams"); if (dhparams != null && !dhparams.isJsonNull()) { JsonObject dhparamsAsJsonObject = dhparams.getAsJsonObject(); JsonElement bits1 = dhparamsAsJsonObject.get("bits"); JsonElement prime = dhparamsAsJsonObject.get("prime"); JsonElement publicKey = dhparamsAsJsonObject.get("public_key"); JsonElement generator = dhparamsAsJsonObject.get("generator"); JsonElement fingerprint = dhparamsAsJsonObject.get("fingerprint"); final DiffieHellmanParams diffieHellmanParams = new DiffieHellmanParams(); if (bits1 != null && !bits1.isJsonNull()) { diffieHellmanParams.setBits(bits1.getAsInt()); } if (prime == null || prime.isJsonNull()) { diffieHellmanParams.setPrime("unknown"); } else { diffieHellmanParams.setPrime(prime.getAsString()); } if (publicKey == null || publicKey.isJsonNull()) { diffieHellmanParams.setPublicKey("unknown"); } else { diffieHellmanParams.setPublicKey(publicKey.getAsString()); } if (generator == null || generator.isJsonNull()) { diffieHellmanParams.setGenerator("unknown"); } else { diffieHellmanParams.setGenerator(generator.getAsString()); } if (fingerprint == null || fingerprint.isJsonNull()) { diffieHellmanParams.setFingerprint("unknown"); } else { diffieHellmanParams.setFingerprint(fingerprint.getAsString()); } sslInfo.setDiffieHellmanParams(diffieHellmanParams); } } banner.setSslInfo(sslInfo); if (uptime == null || uptime.isJsonNull()) { banner.setUptime(0); } else { banner.setUptime(uptime.getAsInt()); } if (link == null || link.isJsonNull()) { banner.setLink("unknown"); } else { banner.setLink(link.getAsString()); } if (title == null || title.isJsonNull()) { banner.setTitle("unknown"); } else { banner.setTitle(title.getAsString()); } if (html == null || html.isJsonNull()) { banner.setHtml("unknown"); } else { banner.setHtml(html.getAsString()); } if (product == null || product.isJsonNull()) { banner.setProduct("unknown"); } else { banner.setProduct(product.getAsString()); } if (version == null || version.isJsonNull()) { banner.setVersion("unknown"); } else { banner.setVersion(version.getAsString()); } if (isp == null || isp.isJsonNull()) { banner.setIsp("unknown"); } else { banner.setIsp(isp.getAsString()); } if (os == null || os.isJsonNull()) { banner.setOs("unknown"); } else { banner.setOs(os.getAsString()); } if (transport == null || transport.isJsonNull()) { banner.setTransport("unknown"); } else { banner.setTransport(transport.getAsString()); } if (devicetype == null || devicetype.isJsonNull()) { banner.setDeviceType("unknown"); } else { banner.setDeviceType(devicetype.getAsString()); } if (info == null || info.isJsonNull()) { banner.setInfo("unknown"); } else { banner.setInfo(info.getAsString()); } if (cpe == null || cpe.isJsonNull()) { banner.setCpe(new String[0]); } else { // cpe can be string or string[]. Fix for #4 if (cpe.isJsonObject()) { banner.setCpe(new String[] { cpe.getAsString() }); } else { JsonArray cpeAsJsonArray = cpe.getAsJsonArray(); String[] cpeArray = new String[cpeAsJsonArray.size()]; for (int i = 0; i < cpeAsJsonArray.size(); i++) { cpeArray[i] = cpeAsJsonArray.get(i).getAsString(); } banner.setCpe(cpeArray); } } banners.add(banner); } return banners; }
From source file:com.getperka.flatpack.codexes.NumberCodex.java
License:Apache License
@Override public N readNotNull(JsonElement element, DeserializationContext context) { Object toReturn;//ww w . j av a 2s . com if (BigDecimal.class.equals(clazz)) { toReturn = element.getAsBigDecimal(); } else if (BigInteger.class.equals(clazz)) { toReturn = element.getAsBigInteger(); } else if (Byte.class.equals(clazz)) { toReturn = element.getAsByte(); } else if (Double.class.equals(clazz)) { toReturn = element.getAsDouble(); } else if (Float.class.equals(clazz)) { toReturn = element.getAsFloat(); } else if (Integer.class.equals(clazz)) { toReturn = element.getAsInt(); } else if (Long.class.equals(clazz)) { toReturn = element.getAsLong(); } else if (Short.class.equals(clazz)) { toReturn = element.getAsShort(); } else { throw new UnsupportedOperationException("Unimplemented Number type " + clazz.getName()); } return clazz.cast(toReturn); }
From source file:com.gmail.tracebachi.DeltaSkins.Shared.Storage.SkinData.java
License:Open Source License
public static SkinData deserialize(JsonObject object) { String uuid = object.get("uuid").getAsString(); String value = object.get("value").getAsString(); String signature = object.get("signature").getAsString(); JsonElement createdAt = object.get("createdAt"); if (createdAt != null) { return new SkinData(uuid, value, signature, createdAt.getAsLong()); } else {//from www.j av a 2s.co m return new SkinData(uuid, value, signature); } }
From source file:com.google.code.stackexchange.client.impl.StackExchangeApiJsonClient.java
License:Apache License
protected GsonBuilder getGsonBuilder() { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { @Override/* ww w . java 2s. c o m*/ public Date deserialize(JsonElement source, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return new Date(source.getAsLong() * 1000); } }); builder.registerTypeAdapter(BadgeRank.class, new JsonDeserializer<BadgeRank>() { @Override public BadgeRank deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return BadgeRank.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(PostType.class, new JsonDeserializer<PostType>() { @Override public PostType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return PostType.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(PostTimelineType.class, new JsonDeserializer<PostTimelineType>() { @Override public PostTimelineType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return PostTimelineType.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(UserTimelineType.class, new JsonDeserializer<UserTimelineType>() { @Override public UserTimelineType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return UserTimelineType.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(UserType.class, new JsonDeserializer<UserType>() { @Override public UserType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return UserType.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(RevisionType.class, new JsonDeserializer<RevisionType>() { @Override public RevisionType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return RevisionType.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(TagRestriction.class, new JsonDeserializer<TagRestriction>() { @Override public TagRestriction deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return TagRestriction.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(SiteState.class, new JsonDeserializer<SiteState>() { @Override public SiteState deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return SiteState.fromValue(arg0.getAsString()); } }); builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); return builder; }
From source file:com.graphaware.module.es.Neo4jElasticVerifier.java
License:Open Source License
private void checkLongArray(JsonObject source, String key, Map<String, Object> properties) { assertTrue(source.get(key) instanceof JsonArray); JsonArray jsonArray = source.get(key).getAsJsonArray(); TreeSet<Long> esSet = new TreeSet(); for (JsonElement element : jsonArray) { esSet.add(element.getAsLong()); }//from ww w. ja va 2 s .c o m TreeSet<Long> nodeSet = new TreeSet(); long[] propertyArray = (long[]) properties.get(key); for (long element : propertyArray) { nodeSet.add(element); } assertEquals(esSet, nodeSet); }
From source file:com.gst.useradministration.service.AppUserWritePlatformServiceJpaRepositoryImpl.java
License:Apache License
@Transactional @Override//from w w w . j ava2 s .c o m @Caching(evict = { @CacheEvict(value = "users", allEntries = true), @CacheEvict(value = "usersByUsername", allEntries = true) }) public CommandProcessingResult createUser(final JsonCommand command) { try { this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForCreate(command.json()); final String officeIdParamName = "officeId"; final Long officeId = command.longValueOfParameterNamed(officeIdParamName); final Office userOffice = this.officeRepositoryWrapper.findOneWithNotFoundDetection(officeId); final String[] roles = command.arrayValueOfParameterNamed("roles"); final Set<Role> allRoles = assembleSetOfRoles(roles); AppUser appUser; final String staffIdParamName = "staffId"; final Long staffId = command.longValueOfParameterNamed(staffIdParamName); Staff linkedStaff = null; if (staffId != null) { linkedStaff = this.staffRepositoryWrapper.findByOfficeWithNotFoundDetection(staffId, userOffice.getId()); } Collection<Client> clients = null; if (command.hasParameter(AppUserConstants.IS_SELF_SERVICE_USER) && command.booleanPrimitiveValueOfParameterNamed(AppUserConstants.IS_SELF_SERVICE_USER) && command.hasParameter(AppUserConstants.CLIENTS)) { JsonArray clientsArray = command.arrayOfParameterNamed(AppUserConstants.CLIENTS); Collection<Long> clientIds = new HashSet<>(); for (JsonElement clientElement : clientsArray) { clientIds.add(clientElement.getAsLong()); } clients = this.clientRepositoryWrapper.findAll(clientIds); } appUser = AppUser.fromJson(userOffice, linkedStaff, allRoles, clients, command); final Boolean sendPasswordToEmail = command.booleanObjectValueOfParameterNamed("sendPasswordToEmail"); this.userDomainService.create(appUser, sendPasswordToEmail); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withEntityId(appUser.getId()) // .withOfficeId(userOffice.getId()) // .build(); } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); } catch (final PersistenceException | AuthenticationServiceException dve) { Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .build(); } catch (final PlatformEmailSendException e) { final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final String email = command.stringValueOfParameterNamed("email"); final ApiParameterError error = ApiParameterError.parameterError("error.msg.user.email.invalid", "The parameter email is invalid.", "email", email); dataValidationErrors.add(error); throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); } }
From source file:com.gst.useradministration.service.AppUserWritePlatformServiceJpaRepositoryImpl.java
License:Apache License
@Transactional @Override/*from w w w. j a va 2 s .c o m*/ @Caching(evict = { @CacheEvict(value = "users", allEntries = true), @CacheEvict(value = "usersByUsername", allEntries = true) }) public CommandProcessingResult updateUser(final Long userId, final JsonCommand command) { try { this.context.authenticatedUser(new CommandWrapperBuilder().updateUser(null).build()); this.fromApiJsonDeserializer.validateForUpdate(command.json()); final AppUser userToUpdate = this.appUserRepository.findOne(userId); if (userToUpdate == null) { throw new UserNotFoundException(userId); } final AppUserPreviousPassword currentPasswordToSaveAsPreview = getCurrentPasswordToSaveAsPreview( userToUpdate, command); Collection<Client> clients = null; boolean isSelfServiceUser = userToUpdate.isSelfServiceUser(); if (command.hasParameter(AppUserConstants.IS_SELF_SERVICE_USER)) { isSelfServiceUser = command .booleanPrimitiveValueOfParameterNamed(AppUserConstants.IS_SELF_SERVICE_USER); } if (isSelfServiceUser && command.hasParameter(AppUserConstants.CLIENTS)) { JsonArray clientsArray = command.arrayOfParameterNamed(AppUserConstants.CLIENTS); Collection<Long> clientIds = new HashSet<>(); for (JsonElement clientElement : clientsArray) { clientIds.add(clientElement.getAsLong()); } clients = this.clientRepositoryWrapper.findAll(clientIds); } final Map<String, Object> changes = userToUpdate.update(command, this.platformPasswordEncoder, clients); if (changes.containsKey("officeId")) { final Long officeId = (Long) changes.get("officeId"); final Office office = this.officeRepositoryWrapper.findOneWithNotFoundDetection(officeId); userToUpdate.changeOffice(office); } if (changes.containsKey("staffId")) { final Long staffId = (Long) changes.get("staffId"); Staff linkedStaff = null; if (staffId != null) { linkedStaff = this.staffRepositoryWrapper.findByOfficeWithNotFoundDetection(staffId, userToUpdate.getOffice().getId()); } userToUpdate.changeStaff(linkedStaff); } if (changes.containsKey("roles")) { final String[] roleIds = (String[]) changes.get("roles"); final Set<Role> allRoles = assembleSetOfRoles(roleIds); userToUpdate.updateRoles(allRoles); } if (!changes.isEmpty()) { this.appUserRepository.saveAndFlush(userToUpdate); if (currentPasswordToSaveAsPreview != null) { this.appUserPreviewPasswordRepository.save(currentPasswordToSaveAsPreview); } } return new CommandProcessingResultBuilder() // .withEntityId(userId) // .withOfficeId(userToUpdate.getOffice().getId()) // .with(changes) // .build(); } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); } catch (final PersistenceException | AuthenticationServiceException dve) { Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .build(); } }
From source file:com.gst.useradministration.service.UserDataValidator.java
License:Apache License
public void validateForCreate(final String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }/*from w w w. jav a 2s . com*/ final Type typeOfMap = new TypeToken<Map<String, Object>>() { }.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource("user"); final JsonElement element = this.fromApiJsonHelper.parse(json); final String username = this.fromApiJsonHelper.extractStringNamed("username", element); baseDataValidator.reset().parameter("username").value(username).notBlank().notExceedingLengthOf(100); final String firstname = this.fromApiJsonHelper.extractStringNamed("firstname", element); baseDataValidator.reset().parameter("firstname").value(firstname).notBlank().notExceedingLengthOf(100); final String lastname = this.fromApiJsonHelper.extractStringNamed("lastname", element); baseDataValidator.reset().parameter("lastname").value(lastname).notBlank().notExceedingLengthOf(100); final Boolean sendPasswordToEmail = this.fromApiJsonHelper.extractBooleanNamed("sendPasswordToEmail", element); if (sendPasswordToEmail != null) { if (sendPasswordToEmail.booleanValue()) { final String email = this.fromApiJsonHelper.extractStringNamed("email", element); baseDataValidator.reset().parameter("email").value(email).notBlank().notExceedingLengthOf(100); } else { final String password = this.fromApiJsonHelper.extractStringNamed("password", element); final String repeatPassword = this.fromApiJsonHelper.extractStringNamed("repeatPassword", element); final PasswordValidationPolicy validationPolicy = this.passwordValidationPolicy .findActivePasswordValidationPolicy(); final String regex = validationPolicy.getRegex(); final String description = validationPolicy.getDescription(); baseDataValidator.reset().parameter("password").value(password).matchesRegularExpression(regex, description); if (StringUtils.isNotBlank(password)) { baseDataValidator.reset().parameter("password").value(password) .equalToParameter("repeatPassword", repeatPassword); } } } else { baseDataValidator.reset().parameter("sendPasswordToEmail").value(sendPasswordToEmail) .trueOrFalseRequired(false); } final Long officeId = this.fromApiJsonHelper.extractLongNamed("officeId", element); baseDataValidator.reset().parameter("officeId").value(officeId).notNull().integerGreaterThanZero(); if (this.fromApiJsonHelper.parameterExists("staffId", element)) { final Long staffId = this.fromApiJsonHelper.extractLongNamed("staffId", element); baseDataValidator.reset().parameter("staffId").value(staffId).notNull().integerGreaterThanZero(); } if (this.fromApiJsonHelper.parameterExists(AppUserConstants.PASSWORD_NEVER_EXPIRES, element)) { final boolean passwordNeverExpire = this.fromApiJsonHelper .extractBooleanNamed(AppUserConstants.PASSWORD_NEVER_EXPIRES, element); baseDataValidator.reset().parameter("passwordNeverExpire").value(passwordNeverExpire) .validateForBooleanValue(); } Boolean isSelfServiceUser = null; if (this.fromApiJsonHelper.parameterExists(AppUserConstants.IS_SELF_SERVICE_USER, element)) { isSelfServiceUser = this.fromApiJsonHelper.extractBooleanNamed(AppUserConstants.IS_SELF_SERVICE_USER, element); if (isSelfServiceUser == null) { baseDataValidator.reset().parameter(AppUserConstants.IS_SELF_SERVICE_USER) .trueOrFalseRequired(false); } } if (this.fromApiJsonHelper.parameterExists(AppUserConstants.CLIENTS, element)) { if (isSelfServiceUser == null || !isSelfServiceUser) { baseDataValidator.reset().parameter(AppUserConstants.CLIENTS).failWithCode( "not.supported.when.isSelfServiceUser.is.false", "clients parameter is not supported when isSelfServiceUser parameter is false"); } else { final JsonArray clientsArray = this.fromApiJsonHelper .extractJsonArrayNamed(AppUserConstants.CLIENTS, element); baseDataValidator.reset().parameter(AppUserConstants.CLIENTS).value(clientsArray) .jsonArrayNotEmpty(); for (JsonElement client : clientsArray) { Long clientId = client.getAsLong(); baseDataValidator.reset().parameter(AppUserConstants.CLIENTS).value(clientId) .longGreaterThanZero(); } } } final String[] roles = this.fromApiJsonHelper.extractArrayNamed("roles", element); baseDataValidator.reset().parameter("roles").value(roles).arrayNotEmpty(); throwExceptionIfValidationWarningsExist(dataValidationErrors); }
From source file:com.gst.useradministration.service.UserDataValidator.java
License:Apache License
public void validateForUpdate(final String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }//from w ww . j a v a 2 s.co m final Type typeOfMap = new TypeToken<Map<String, Object>>() { }.getType(); this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource("user"); final JsonElement element = this.fromApiJsonHelper.parse(json); if (this.fromApiJsonHelper.parameterExists("officeId", element)) { final Long officeId = this.fromApiJsonHelper.extractLongNamed("officeId", element); baseDataValidator.reset().parameter("officeId").value(officeId).notNull().integerGreaterThanZero(); } if (this.fromApiJsonHelper.parameterExists("staffId", element)) { final Long staffId = this.fromApiJsonHelper.extractLongNamed("staffId", element); baseDataValidator.reset().parameter("staffId").value(staffId).ignoreIfNull().integerGreaterThanZero(); } if (this.fromApiJsonHelper.parameterExists("username", element)) { final String username = this.fromApiJsonHelper.extractStringNamed("username", element); baseDataValidator.reset().parameter("username").value(username).notBlank().notExceedingLengthOf(100); } if (this.fromApiJsonHelper.parameterExists("firstname", element)) { final String firstname = this.fromApiJsonHelper.extractStringNamed("firstname", element); baseDataValidator.reset().parameter("firstname").value(firstname).notBlank().notExceedingLengthOf(100); } if (this.fromApiJsonHelper.parameterExists("lastname", element)) { final String lastname = this.fromApiJsonHelper.extractStringNamed("lastname", element); baseDataValidator.reset().parameter("lastname").value(lastname).notBlank().notExceedingLengthOf(100); } if (this.fromApiJsonHelper.parameterExists("email", element)) { final String email = this.fromApiJsonHelper.extractStringNamed("email", element); baseDataValidator.reset().parameter("email").value(email).notBlank().notExceedingLengthOf(100); } if (this.fromApiJsonHelper.parameterExists("roles", element)) { final String[] roles = this.fromApiJsonHelper.extractArrayNamed("roles", element); baseDataValidator.reset().parameter("roles").value(roles).arrayNotEmpty(); } if (this.fromApiJsonHelper.parameterExists("password", element)) { final String password = this.fromApiJsonHelper.extractStringNamed("password", element); final String repeatPassword = this.fromApiJsonHelper.extractStringNamed("repeatPassword", element); final PasswordValidationPolicy validationPolicy = this.passwordValidationPolicy .findActivePasswordValidationPolicy(); final String regex = validationPolicy.getRegex(); final String description = validationPolicy.getDescription(); baseDataValidator.reset().parameter("password").value(password).matchesRegularExpression(regex, description); if (StringUtils.isNotBlank(password)) { baseDataValidator.reset().parameter("password").value(password).equalToParameter("repeatPassword", repeatPassword); } } if (this.fromApiJsonHelper.parameterExists("passwordNeverExpire", element)) { final boolean passwordNeverExpire = this.fromApiJsonHelper.extractBooleanNamed("passwordNeverExpire", element); baseDataValidator.reset().parameter("passwordNeverExpire").value(passwordNeverExpire) .validateForBooleanValue(); } Boolean isSelfServiceUser = null; if (this.fromApiJsonHelper.parameterExists(AppUserConstants.IS_SELF_SERVICE_USER, element)) { isSelfServiceUser = this.fromApiJsonHelper.extractBooleanNamed(AppUserConstants.IS_SELF_SERVICE_USER, element); if (isSelfServiceUser == null) { baseDataValidator.reset().parameter(AppUserConstants.IS_SELF_SERVICE_USER) .trueOrFalseRequired(false); } } if (this.fromApiJsonHelper.parameterExists(AppUserConstants.CLIENTS, element)) { if (isSelfServiceUser != null && !isSelfServiceUser) { baseDataValidator.reset().parameter(AppUserConstants.CLIENTS).failWithCode( "not.supported.when.isSelfServiceUser.is.false", "clients parameter is not supported when isSelfServiceUser parameter is false"); } else { final JsonArray clientsArray = this.fromApiJsonHelper .extractJsonArrayNamed(AppUserConstants.CLIENTS, element); baseDataValidator.reset().parameter(AppUserConstants.CLIENTS).value(clientsArray) .jsonArrayNotEmpty(); for (JsonElement client : clientsArray) { Long clientId = client.getAsLong(); baseDataValidator.reset().parameter(AppUserConstants.CLIENTS).value(clientId) .longGreaterThanZero(); } } } throwExceptionIfValidationWarningsExist(dataValidationErrors); }
From source file:com.heroiclabs.sdk.android.util.json.JsonDeserializerUtils.java
License:Apache License
/** * Extract a JsonElement member as a Long from a JsonObject, if it exists. * * @param object The JsonObject to extract from. * @param memberName The member name to extract. * @return A Long representation of the corresponding JsonElement. *//* w ww . j av a2 s . co m*/ protected static Long extractAsLong(final @NonNull JsonObject object, final @NonNull String memberName) { if (object.has(memberName)) { final JsonElement member = object.get(memberName); if (member.isJsonNull()) { return null; } return member.getAsLong(); } return null; }