List of usage examples for io.vertx.core.json JsonObject isEmpty
public boolean isEmpty()
From source file:enmasse.kafka.bridge.converter.JsonMessageConverter.java
License:Apache License
@Override public ProducerRecord<String, byte[]> toKafkaRecord(String kafkaTopic, Message message) { Object partition = null, key = null; byte[] value = null; // root JSON/*from w ww . ja v a 2s .com*/ JsonObject json = new JsonObject(); // make JSON with AMQP properties JsonObject jsonProperties = new JsonObject(); if (message.getMessageId() != null) jsonProperties.put(JsonMessageConverter.MESSAGE_ID, message.getMessageId()); if (message.getAddress() != null) jsonProperties.put(JsonMessageConverter.TO, message.getAddress()); if (message.getSubject() != null) jsonProperties.put(JsonMessageConverter.SUBJECT, message.getSubject()); if (message.getReplyTo() != null) jsonProperties.put(JsonMessageConverter.REPLY_TO, message.getReplyTo()); if (message.getCorrelationId() != null) jsonProperties.put(JsonMessageConverter.CORRELATION_ID, message.getCorrelationId()); if (!jsonProperties.isEmpty()) json.put(JsonMessageConverter.PROPERTIES, jsonProperties); // make JSON with AMQP application properties ApplicationProperties applicationProperties = message.getApplicationProperties(); if (applicationProperties != null) { JsonObject jsonApplicationProperties = new JsonObject(); Map<String, Object> applicationPropertiesMap = (Map<String, Object>) applicationProperties.getValue(); for (Entry<String, Object> entry : applicationPropertiesMap.entrySet()) { jsonApplicationProperties.put(entry.getKey(), entry.getValue()); } json.put(JsonMessageConverter.APPLICATION_PROPERTIES, jsonApplicationProperties); } // get partition and key from AMQP message annotations // NOTE : they are not mandatory MessageAnnotations messageAnnotations = message.getMessageAnnotations(); if (messageAnnotations != null) { partition = messageAnnotations.getValue().get(Symbol.getSymbol(Bridge.AMQP_PARTITION_ANNOTATION)); key = messageAnnotations.getValue().get(Symbol.getSymbol(Bridge.AMQP_KEY_ANNOTATION)); if (partition != null && !(partition instanceof Integer)) throw new IllegalArgumentException("The partition annotation must be an Integer"); if (key != null && !(key instanceof String)) throw new IllegalArgumentException("The key annotation must be a String"); // make JSON with AMQP message annotations JsonObject jsonMessageAnnotations = new JsonObject(); Map<Symbol, Object> messageAnnotationsMap = (Map<Symbol, Object>) messageAnnotations.getValue(); for (Entry<Symbol, Object> entry : messageAnnotationsMap.entrySet()) { jsonMessageAnnotations.put(entry.getKey().toString(), entry.getValue()); } json.put(JsonMessageConverter.MESSAGE_ANNOTATIONS, jsonMessageAnnotations); } // get topic and body from AMQP message String topic = (message.getAddress() == null) ? kafkaTopic : message.getAddress().replace('/', '.'); Section body = message.getBody(); // check body null if (body != null) { JsonObject jsonBody = new JsonObject(); // section is AMQP value if (body instanceof AmqpValue) { jsonBody.put(JsonMessageConverter.SECTION_TYPE, JsonMessageConverter.SECTION_AMQP_VALUE_TYPE); Object amqpValue = ((AmqpValue) body).getValue(); // encoded as String if (amqpValue instanceof String) { String content = (String) ((AmqpValue) body).getValue(); jsonBody.put(JsonMessageConverter.SECTION, content); // encoded as a List } else if (amqpValue instanceof List) { List<?> list = (List<?>) ((AmqpValue) body).getValue(); JsonArray jsonArray = new JsonArray(list); jsonBody.put(JsonMessageConverter.SECTION, jsonArray); // encoded as an array } else if (amqpValue instanceof Object[]) { Object[] array = (Object[]) ((AmqpValue) body).getValue(); JsonArray jsonArray = new JsonArray(Arrays.asList(array)); jsonBody.put(JsonMessageConverter.SECTION, jsonArray); // encoded as a Map } else if (amqpValue instanceof Map) { Map<?, ?> map = (Map<?, ?>) ((AmqpValue) body).getValue(); value = map.toString().getBytes(); JsonObject jsonMap = new JsonObject((Map<String, Object>) map); jsonBody.put(JsonMessageConverter.SECTION, jsonMap); } // section is Data (binary) } else if (body instanceof Data) { Binary binary = (Binary) ((Data) body).getValue(); value = binary.getArray(); jsonBody.put(JsonMessageConverter.SECTION_TYPE, JsonMessageConverter.SECTION_DATA_TYPE); // put the section bytes as Base64 encoded string jsonBody.put(JsonMessageConverter.SECTION, Base64.getEncoder().encode(value)); } // put the body into the JSON root json.put(JsonMessageConverter.BODY, jsonBody); } // build the record for the KafkaProducer and then send it return new ProducerRecord<>(topic, (Integer) partition, (String) key, json.toString().getBytes()); }
From source file:io.knotx.adapter.action.http.impl.HttpActionAdapterProxyImpl.java
License:Apache License
private HttpClient getHttpClient(Vertx vertx, HttpAdapterConfiguration configuration) { JsonObject clientOptions = configuration.getClientOptions(); return clientOptions.isEmpty() ? vertx.createHttpClient() : vertx.createHttpClient(new HttpClientOptions(clientOptions)); }
From source file:io.techcode.logbulk.pipeline.input.SyslogInput.java
License:Open Source License
/** * Decode a syslog message from buffer.//from ww w .ja v a 2 s .com * * @param buf buffer involved. */ private void decode(Buffer buf) { JsonObject doc = new JsonObject(); Reader reader = new Reader(buf); // Extract priority reader.expect('<'); int priority = reader.readInt(); reader.expect('>'); // Extract version int version = reader.readInt(); reader.expect(SPACE); // Extract timestamp Object timestamp = getTimestamp(reader); // Extract all identifiers String host = reader.getIdentifier(); String app = reader.getIdentifier(); String procId = reader.getIdentifier(); String msgId = reader.getIdentifier(); // Extract data Object structuredData = (skipStructuredData) ? null : getStructuredData(reader); // Extract message String message; if (reader.is(SPACE)) { reader.getc(); message = reader.rest(); } else { message = reader.rest(); } // Convert int severity = priority & 0x7; int facility = priority >> 3; // Populate if (mapping.containsKey(SyslogHeader.FACILITY)) { doc.put(mapping.get(SyslogHeader.FACILITY), facility); } if (mapping.containsKey(SyslogHeader.SEVERITY)) { doc.put(mapping.get(SyslogHeader.SEVERITY), severity); } if (mapping.containsKey(SyslogHeader.SEVERITY_TEXT)) { doc.put(mapping.get(SyslogHeader.SEVERITY_TEXT), Severity.parseInt(severity).getLabel()); } if (timestamp != null && mapping.containsKey(SyslogHeader.TIMESTAMP)) { doc.put(mapping.get(SyslogHeader.TIMESTAMP), timestamp); } if (host != null && mapping.containsKey(SyslogHeader.HOST)) { doc.put(mapping.get(SyslogHeader.HOST), host); } if (app != null && mapping.containsKey(SyslogHeader.APPLICATION)) { doc.put(mapping.get(SyslogHeader.APPLICATION), app); } if (procId != null && mapping.containsKey(SyslogHeader.PROCESSUS)) { doc.put(mapping.get(SyslogHeader.PROCESSUS), procId); } if (msgId != null && mapping.containsKey(SyslogHeader.ID)) { doc.put(mapping.get(SyslogHeader.ID), msgId); } if (mapping.containsKey(SyslogHeader.VERSION)) { doc.put(mapping.get(SyslogHeader.VERSION), version); } if (structuredData != null && mapping.containsKey(SyslogHeader.DATA)) { doc.put(mapping.get(SyslogHeader.DATA), structuredData); } if (mapping.containsKey(SyslogHeader.MESSAGE)) { doc.put(mapping.get(SyslogHeader.MESSAGE), message); } // Send message if (!doc.isEmpty()) { createEvent(doc); } }
From source file:org.entcore.auth.controllers.SamlController.java
License:Open Source License
@Get("/saml/metadata/:idp") public void idpGar(HttpServerRequest request) { JsonObject idpConfig = config.getJsonObject("idp-metadata-mapping", new JsonObject()); String idpParam = request.getParam("idp"); if (!idpConfig.isEmpty() && idpConfig.containsKey(idpParam)) { request.response().sendFile(idpConfig.getString(idpParam)); } else {//ww w . j a v a2s. co m request.response().setStatusCode(404).setStatusMessage("idp not found").end(); } }
From source file:org.entcore.feeder.csv.CsvValidator.java
License:Open Source License
private void validateFile(final String path, final String profile, final List<String> columns, final JsonArray existExternalId, final String charset, final Handler<JsonObject> handler) { addProfile(profile);//from w w w . ja v a 2s . c om final Validator validator = profiles.get(profile); getStructure(path.substring(0, path.lastIndexOf(File.separator)), new Handler<Structure>() { @Override public void handle(final Structure structure) { if (structure == null) { addError(profile, "invalid.structure"); handler.handle(result); return; } final JsonObject checkChildExists = new JsonObject(); try { CSVReader csvParser = getCsvReader(path, charset, 1); final int nbColumns = columns.size(); String[] strings; int i = 1; csvParserWhile: while ((strings = csvParser.readNext()) != null) { if (emptyLine(strings)) { i++; continue; } if (strings.length > nbColumns) { strings = Arrays.asList(strings).subList(0, nbColumns).toArray(new String[nbColumns]); } // if (strings.length != nbColumns) { // addErrorByFile(profile, "bad.columns.number", "" + ++i); // continue; // } final JsonArray classesNames = new fr.wseduc.webutils.collections.JsonArray(); JsonObject user = new JsonObject(); user.put("structures", new fr.wseduc.webutils.collections.JsonArray().add(structure.getExternalId())); user.put("profiles", new fr.wseduc.webutils.collections.JsonArray().add(profile)); List<String[]> classes = new ArrayList<>(); for (int j = 0; j < strings.length; j++) { if (j >= columns.size()) { addErrorByFile(profile, "out.columns", "" + i); return; } final String c = columns.get(j); final String v = strings[j].trim(); if (v.isEmpty() && !c.startsWith("child")) continue; switch (validator.getType(c)) { case "string": if ("birthDate".equals(c)) { Matcher m = frenchDatePatter.matcher(v); if (m.find()) { user.put(c, m.group(3) + "-" + m.group(2) + "-" + m.group(1)); } else { user.put(c, v); } } else { user.put(c, v); } break; case "array-string": JsonArray a = user.getJsonArray(c); if (a == null) { a = new fr.wseduc.webutils.collections.JsonArray(); user.put(c, a); } if (("classes".equals(c) || "subjectTaught".equals(c) || "functions".equals(c)) && !v.startsWith(structure.getExternalId() + "$")) { a.add(structure.getExternalId() + "$" + v); } else { a.add(v); } break; case "boolean": user.put(c, "true".equals(v.toLowerCase())); break; default: Object o = user.getValue(c); final String v2; if ("childClasses".equals(c) && !v.startsWith(structure.getExternalId() + "$")) { v2 = structure.getExternalId() + "$" + v; } else { v2 = v; } if (o != null) { if (o instanceof JsonArray) { ((JsonArray) o).add(v2); } else { JsonArray array = new fr.wseduc.webutils.collections.JsonArray(); array.add(o).add(v2); user.put(c, array); } } else { user.put(c, v2); } } if ("classes".equals(c)) { String eId = structure.getExternalId() + '$' + v; String[] classId = new String[2]; classId[0] = structure.getExternalId(); classId[1] = eId; classes.add(classId); classesNames.add(v); } } String ca; long seed; JsonArray classesA; Object co = user.getValue("classes"); if (co != null && co instanceof JsonArray) { classesA = (JsonArray) co; } else if (co instanceof String) { classesA = new fr.wseduc.webutils.collections.JsonArray().add(co); } else { classesA = null; } if ("Student".equals(profile) && classesA != null && classesA.size() == 1) { seed = defaultStudentSeed; ca = classesA.getString(0); } else { ca = String.valueOf(i); seed = System.currentTimeMillis(); } final State state; final String externalId = user.getString("externalId"); if (externalId == null || externalId.trim().isEmpty()) { generateUserExternalId(user, ca, structure, seed); state = State.NEW; } else { if (existExternalId.contains(externalId)) { state = State.UPDATED; studentExternalIdMapping.put(getHashMapping(user, ca, structure, seed), externalId); } else { state = State.NEW; } } switch (profile) { case "Relative": boolean checkChildMapping = true; JsonArray linkStudents = new fr.wseduc.webutils.collections.JsonArray(); if ("Intitul".equals(strings[0]) && "Adresse Organisme".equals(strings[1])) { break csvParserWhile; } user.put("linkStudents", linkStudents); for (String attr : user.fieldNames()) { if ("childExternalId".equals(attr)) { if (checkChildMapping) { checkChildMapping = false; } Object o = user.getValue(attr); if (o instanceof JsonArray) { for (Object c : (JsonArray) o) { linkStudents.add(c); } } else { linkStudents.add(o); } } else if ("childUsername".equals(attr)) { Object childUsername = user.getValue(attr); Object childLastName = user.getValue("childLastName"); Object childFirstName = user.getValue("childFirstName"); Object childClasses; if (isNotEmpty(structure.getOverrideClass())) { childClasses = structure.getOverrideClass(); } else { childClasses = user.getValue("childClasses"); } if (childUsername instanceof JsonArray && childLastName instanceof JsonArray && childFirstName instanceof JsonArray && childClasses instanceof JsonArray && ((JsonArray) childClasses).size() == ((JsonArray) childLastName) .size() && ((JsonArray) childFirstName).size() == ((JsonArray) childLastName) .size()) { for (int j = 0; j < ((JsonArray) childUsername).size(); j++) { String mapping = structure.getExternalId() + ((JsonArray) childUsername).getString(j).trim() + ((JsonArray) childLastName).getString(j).trim() + ((JsonArray) childFirstName).getString(j).trim() + ((JsonArray) childClasses).getString(j).trim() + defaultStudentSeed; relativeStudentMapping(linkStudents, mapping); } } else if (childUsername instanceof String && childLastName instanceof String && childFirstName instanceof String && childClasses instanceof String) { String mapping = structure.getExternalId() + childLastName.toString().trim() + childFirstName.toString().trim() + childClasses.toString().trim() + defaultStudentSeed; relativeStudentMapping(linkStudents, mapping); } else { addErrorByFile(profile, "invalid.child.mapping", "" + (i + 1), "childLUsername"); handler.handle(result); return; } } else if ("childLastName".equals(attr) && !user.fieldNames().contains("childUsername")) { Object childLastName = user.getValue(attr); Object childFirstName = user.getValue("childFirstName"); Object childClasses; if (isNotEmpty(structure.getOverrideClass())) { childClasses = structure.getOverrideClass(); } else { childClasses = user.getValue("childClasses"); } if (childLastName instanceof JsonArray && childFirstName instanceof JsonArray && childClasses instanceof JsonArray && ((JsonArray) childClasses).size() == ((JsonArray) childLastName) .size() && ((JsonArray) childFirstName).size() == ((JsonArray) childLastName) .size()) { for (int j = 0; j < ((JsonArray) childLastName).size(); j++) { String mapping = structure.getExternalId() + ((JsonArray) childLastName).getString(j) + ((JsonArray) childFirstName).getString(j) + ((JsonArray) childClasses).getString(j) + defaultStudentSeed; relativeStudentMapping(linkStudents, mapping); } } else if (childLastName instanceof String && childFirstName instanceof String && childClasses instanceof String) { String mapping = structure.getExternalId() + childLastName.toString().trim() + childFirstName.toString().trim() + childClasses.toString().trim() + defaultStudentSeed; relativeStudentMapping(linkStudents, mapping); } else { addErrorByFile(profile, "invalid.child.mapping", "" + (i + 1), "childLastName & childFirstName"); handler.handle(result); return; } } } if (checkChildMapping || classesNamesMapping.size() > 0) { for (Object o : linkStudents) { if (!(o instanceof String)) continue; if (classesNamesMapping.get(o) != null) { classesNames.add(classesNamesMapping.get(o)); } } if (classesNames.size() == 0) { addSoftErrorByFile(profile, "missing.student.soft", "" + (i + 1), user.getString("firstName"), user.getString("lastName")); } } else { Object c = user.getValue("childExternalId"); JsonObject u = new JsonObject().put("lastName", user.getString("lastName")) .put("firstName", user.getString("firstName")).put("line", i); if (c instanceof String) { c = new JsonArray().add(c); } if (c instanceof JsonArray) { for (Object ceId : ((JsonArray) c)) { if (isEmpty((String) ceId)) continue; JsonArray jr = checkChildExists.getJsonArray((String) ceId); if (jr == null) { jr = new JsonArray(); checkChildExists.put((String) ceId, jr); } jr.add(u); } } } break; } String error = validator.validate(user, acceptLanguage); if (error != null) { log.warn(error); addErrorByFile(profile, "validator.errorWithLine", "" + (i + 1), error); // Note that 'error' is already translated } else { final String classesStr = Joiner.on(", ").join(classesNames); if (!"Relative".equals(profile)) { classesNamesMapping.put(user.getString("externalId"), classesStr); } addUser(profile, user.put("state", translate(state.name())) .put("translatedProfile", translate(profile)).put("classesStr", classesStr)); } i++; } } catch (Exception e) { addError(profile, "csv.exception"); log.error("csv.exception", e); } if (!checkChildExists.isEmpty()) { final String query = "MATCH (u:User) " + "WHERE u.externalId IN {childExternalIds} " + "RETURN COLLECT(u.externalId) as childExternalIds "; final JsonObject params = new JsonObject().put("childExternalIds", new JsonArray(new ArrayList<>(checkChildExists.fieldNames()))); Neo4j.getInstance().execute(query, params, new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> event) { if ("ok".equals(event.body().getString("status"))) { JsonArray existsChilds = getOrElse( getOrElse(getOrElse(event.body().getJsonArray("result"), new JsonArray()) .getJsonObject(0), new JsonObject()) .getJsonArray("childExternalIds"), new JsonArray()); for (String cexternalId : checkChildExists.fieldNames()) { if (!existsChilds.contains(cexternalId)) { for (Object o : checkChildExists.getJsonArray(cexternalId)) { if (!(o instanceof JsonObject)) continue; JsonObject user = (JsonObject) o; addSoftErrorByFile(profile, "missing.student.soft", "" + (user.getInteger("line") + 1), user.getString("firstName"), user.getString("lastName")); } } } } handler.handle(result); } }); } else { handler.handle(result); } } }); }
From source file:org.gooru.nucleus.handlers.assessment.processors.repositories.activejdbc.dbhandlers.CreateAssessmentHandler.java
@Override public ExecutionResult<MessageResponse> checkSanity() { // The user should not be anonymous if ((context.userId() == null) || context.userId().isEmpty() || context.userId().equalsIgnoreCase(MessageConstants.MSG_USER_ANONYMOUS)) { LOGGER.warn("Anonymous or invalid user attempting to create assessment"); return new ExecutionResult<>( MessageResponseFactory.createForbiddenResponse(RESOURCE_BUNDLE.getString("not.allowed")), ExecutionResult.ExecutionStatus.FAILED); }/* w w w .ja va 2 s . c om*/ // Payload should not be empty if ((context.request() == null) || context.request().isEmpty()) { LOGGER.warn("Empty payload supplied to create assessment"); return new ExecutionResult<>( MessageResponseFactory.createInvalidRequestResponse(RESOURCE_BUNDLE.getString("empty.payload")), ExecutionResult.ExecutionStatus.FAILED); } // Our validators should certify this JsonObject errors = new DefaultPayloadValidator().validatePayload(context.request(), AJEntityAssessment.createFieldSelector(), AJEntityAssessment.getValidatorRegistry()); if ((errors != null) && !errors.isEmpty()) { LOGGER.warn("Validation errors for request"); return new ExecutionResult<>(MessageResponseFactory.createValidationErrorResponse(errors), ExecutionResult.ExecutionStatus.FAILED); } return new ExecutionResult<>(null, ExecutionResult.ExecutionStatus.CONTINUE_PROCESSING); }
From source file:org.gooru.nucleus.handlers.resources.processors.repositories.activejdbc.dbhandlers.CreateResourceHandler.java
@Override public ExecutionResult<MessageResponse> validateRequest() { try {//from ww w.j a v a 2s.co m this.createRes = new AJEntityResource(); DBHelper.populateEntityFromJson(context.request(), createRes); DBHelper.setPGObject(this.createRes, AJEntityResource.MODIFIER_ID, AJEntityResource.UUID_TYPE, context.userId()); DBHelper.setPGObject(this.createRes, AJEntityResource.CREATOR_ID, AJEntityResource.UUID_TYPE, context.userId()); DBHelper.setPGObject(this.createRes, AJEntityResource.CONTENT_FORMAT, AJEntityResource.CONTENT_FORMAT_TYPE, AJEntityResource.VALID_CONTENT_FORMAT_FOR_RESOURCE); Integer licenseFromRequest = this.createRes.getInteger(AJEntityResource.LICENSE); if (licenseFromRequest == null || !DBHelper.isValidLicense(licenseFromRequest)) { this.createRes.setInteger(AJEntityResource.LICENSE, DBHelper.getDafaultLicense()); } LOGGER.debug("validateRequest : Creating resource From MAP : {}", this.createRes.toInsert()); JsonObject resourceIdWithURLDuplicates = DBHelper .getDuplicateResourcesByURL(this.createRes.getString(AJEntityResource.RESOURCE_URL)); if (resourceIdWithURLDuplicates != null && !resourceIdWithURLDuplicates.isEmpty()) { LOGGER.error( "validateRequest : Duplicate resource URL found. So cannot go ahead with creating new resource! URL : {}", createRes.getString(AJEntityResource.RESOURCE_URL)); LOGGER.error("validateRequest : Duplicate resources : {}", resourceIdWithURLDuplicates); return new ExecutionResult<>( MessageResponseFactory.createValidationErrorResponse(resourceIdWithURLDuplicates), ExecutionResult.ExecutionStatus.FAILED); } } catch (IllegalArgumentException e) { LOGGER.error("CheckSanity : {} ", e); return new ExecutionResult<>(MessageResponseFactory.createInvalidRequestResponse(), ExecutionResult.ExecutionStatus.FAILED); } return new ExecutionResult<>(null, ExecutionResult.ExecutionStatus.CONTINUE_PROCESSING); }
From source file:org.gooru.nucleus.handlers.resources.processors.repositories.activejdbc.dbhandlers.DBHelper.java
static int updateOwnerDataToCopies(AJEntityResource resource, String ownerResourceId, JsonObject dataToBePropogated, String originalCreator) throws SQLException, IllegalArgumentException { LOGGER.debug("updateOwnerDataToCopies: OwnerResourceID {}", ownerResourceId); int numRecsUpdated = 0; String mapValue;//from w w w .j a v a2s . com List<Object> params = new ArrayList<>(); String updateStmt = null; if (!dataToBePropogated.isEmpty()) { for (Map.Entry<String, Object> entry : dataToBePropogated) { mapValue = (entry.getValue() != null) ? entry.getValue().toString() : null; if (AJEntityResource.NOTNULL_FIELDS.contains(entry.getKey())) { if (mapValue == null || mapValue.isEmpty()) { throw new IllegalArgumentException("Null value input for : " + entry.getKey()); } } LOGGER.debug("updateOwnerDataToCopies: OwnerResourceID {}", entry.getKey()); updateStmt = (updateStmt == null) ? entry.getKey() + " = ?" : updateStmt + ", " + entry.getKey() + " = ?"; if (AJEntityResource.CONTENT_FORMAT.equalsIgnoreCase(entry.getKey())) { if (!AJEntityResource.VALID_CONTENT_FORMAT_FOR_RESOURCE.equalsIgnoreCase(mapValue)) { throw new IllegalArgumentException( "content format should always be a 'resource' but {} has been sent: " + mapValue); } else { PGobject contentformat = new PGobject(); contentformat.setType(AJEntityResource.CONTENT_FORMAT_TYPE); contentformat.setValue(entry.getValue().toString()); params.add(contentformat); } } else if (AJEntityResource.CONTENT_SUBFORMAT.equalsIgnoreCase(entry.getKey())) { if (mapValue == null || mapValue.isEmpty() || !mapValue.endsWith(AJEntityResource.VALID_CONTENT_FORMAT_FOR_RESOURCE)) { throw new IllegalArgumentException( "content sub format is not a valid resource format ; {} has been sent: " + mapValue); } else { PGobject contentSubformat = new PGobject(); contentSubformat.setType(AJEntityResource.CONTENT_SUBFORMAT_TYPE); contentSubformat.setValue(entry.getValue().toString()); params.add(contentSubformat); } } else if (AJEntityResource.JSONB_FIELDS.contains(entry.getKey())) { PGobject jsonbFields = new PGobject(); jsonbFields.setType(AJEntityResource.JSONB_FORMAT); jsonbFields.setValue(entry.getValue().toString()); params.add(jsonbFields); } else if (AJEntityResource.UUID_FIELDS.contains(entry.getKey())) { PGobject uuidFields = new PGobject(); uuidFields.setType(AJEntityResource.UUID_TYPE); uuidFields.setValue(mapValue); params.add(uuidFields); } else { params.add(entry.getValue()); } } LOGGER.debug("updateOwnerDataToCopies: Statement {}", updateStmt); if (updateStmt != null) { params.add(ownerResourceId); params.add(originalCreator); numRecsUpdated = AJEntityResource.update(updateStmt, AJEntityResource.SQL_UPDATEOWNERDATATOCOPIES_WHERECLAUSE, params.toArray()); LOGGER.debug("updateOwnerDataToCopies : Update successful. Number of records updated: {}", numRecsUpdated); } } return numRecsUpdated; }
From source file:org.gooru.nucleus.handlers.resources.processors.repositories.activejdbc.dbhandlers.UpdateResourceHandler.java
@Override public ExecutionResult<MessageResponse> validateRequest() { // fetch resource from DB based on Id received AJEntityResource fetchDBResourceData = DBHelper.getResourceById(context.resourceId()); if (fetchDBResourceData == null) { LOGGER.error(//from w w w .ja v a2 s. c o m "validateRequest : updateResource : Object to update is not found in DB! Input resource ID: {} ", context.resourceId()); return new ExecutionResult<>(MessageResponseFactory.createNotFoundResponse(), ExecutionResult.ExecutionStatus.FAILED); } String creator = fetchDBResourceData.getString(AJEntityResource.CREATOR_ID); String originalCreator = fetchDBResourceData.getString(AJEntityResource.ORIGINAL_CREATOR_ID); LOGGER.debug("validateRequest : updateResource : creator from DB = {}.", creator); if (originalCreator == null && creator != null && !creator.isEmpty()) { isOwner = creator.equalsIgnoreCase(context.userId()); } LOGGER.debug("validateRequest : updateResource : Ok! So, who is trying to update content? {}.", (isOwner) ? "owner" : "someone else"); String mapValue; // now mandatory field checks on input resource data and if contains // owner-Specific editable fields // compare input value and collect only changed attributes in new model // that we will use to update this.updateRes = new AJEntityResource(); DBHelper.setPGObject(this.updateRes, AJEntityResource.RESOURCE_ID, AJEntityResource.UUID_TYPE, context.resourceId()); if (this.updateRes.hasErrors()) { return new ExecutionResult<>( MessageResponseFactory.createValidationErrorResponse(this.updateRes.errors()), ExecutionResult.ExecutionStatus.FAILED); } LOGGER.debug("validateRequest updateResource : Iterate through the input Json now."); for (Map.Entry<String, Object> entry : context.request()) { LOGGER.debug("validateRequest updateResource : checking the key & values..before collection. Key: {}", entry.getKey()); mapValue = (entry.getValue() != null) ? entry.getValue().toString() : null; if (AJEntityResource.NOTNULL_FIELDS.contains(entry.getKey())) { if (mapValue == null) { LOGGER.error( "validateRequest Failed to update resource. Field : {} : is mandatory field and cannot be null.", entry.getKey()); return new ExecutionResult<>( MessageResponseFactory.createValidationErrorResponse( new JsonObject().put(entry.getKey(), entry.getValue())), ExecutionResult.ExecutionStatus.FAILED); } } if (AJEntityResource.RESOURCE_URL.equalsIgnoreCase(entry.getKey())) { JsonObject resourceIdWithURLDuplicates = DBHelper .getDuplicateResourcesByURL(entry.getValue().toString()); if (resourceIdWithURLDuplicates != null && !resourceIdWithURLDuplicates.isEmpty()) { LOGGER.error( "validateRequest : Duplicate resource URL found. So cannot go ahead with creating new resource! URL : {}", entry.getKey()); LOGGER.error("validateRequest : Duplicate resources : {}", resourceIdWithURLDuplicates); return new ExecutionResult<>( MessageResponseFactory.createValidationErrorResponse(resourceIdWithURLDuplicates), ExecutionResult.ExecutionStatus.FAILED); } } // mandatory and owner specific items may be overlapping...so do a // separate check not as ELSE condition if (!isOwner && !AJEntityResource.COPY_UPDATE_FIELDS.contains(entry.getKey())) { // LOGGER.debug("validateRequest updateResource : Not owner but // changing // owner specific fields?"); LOGGER.error("Error updating resource. Field: {} : can not be allowed to update for resource copy.", entry.getKey()); return new ExecutionResult<>(MessageResponseFactory.createForbiddenResponse(), ExecutionResult.ExecutionStatus.FAILED); } else if (isOwner && AJEntityResource.OWNER_SPECIFIC_FIELDS.contains(entry.getKey())) { // collect the DB fields to update for owner specific fields // across // all // copies of this resource LOGGER.debug("updateResource : need to propagate this : {} : to other resources. ", entry.getKey()); if (ownerDataToPropogateToCopies == null) { ownerDataToPropogateToCopies = new JsonObject(); } ownerDataToPropogateToCopies.put(entry.getKey(), entry.getValue()); } // collect the attributes and values in the model. if (AJEntityResource.CONTENT_FORMAT.equalsIgnoreCase(entry.getKey())) { if (!AJEntityResource.VALID_CONTENT_FORMAT_FOR_RESOURCE.equalsIgnoreCase(mapValue)) { LOGGER.error("updateResource : content format is invalid! : {} ", entry.getKey()); return new ExecutionResult<>( MessageResponseFactory.createValidationErrorResponse( new JsonObject().put(entry.getKey(), entry.getValue())), ExecutionResult.ExecutionStatus.FAILED); } } else if (AJEntityResource.CONTENT_SUBFORMAT.equalsIgnoreCase(entry.getKey())) { if (mapValue == null || mapValue.isEmpty() || !mapValue.endsWith(AJEntityResource.VALID_CONTENT_FORMAT_FOR_RESOURCE)) { LOGGER.error("updateResource : content subformat is invalid! : {} ", entry.getKey()); return new ExecutionResult<>( MessageResponseFactory.createValidationErrorResponse( new JsonObject().put(entry.getKey(), entry.getValue())), ExecutionResult.ExecutionStatus.FAILED); } else { DBHelper.setPGObject(this.updateRes, entry.getKey(), AJEntityResource.CONTENT_SUBFORMAT_TYPE, mapValue); if (this.updateRes.hasErrors()) { return new ExecutionResult<>( MessageResponseFactory.createValidationErrorResponse(this.updateRes.errors()), ExecutionResult.ExecutionStatus.FAILED); } } } else if (AJEntityResource.JSONB_FIELDS.contains(entry.getKey())) { DBHelper.setPGObject(this.updateRes, entry.getKey(), AJEntityResource.JSONB_FORMAT, mapValue); if (this.updateRes.hasErrors()) { return new ExecutionResult<>( MessageResponseFactory.createValidationErrorResponse(this.updateRes.errors()), ExecutionResult.ExecutionStatus.FAILED); } } else if (AJEntityResource.UUID_FIELDS.contains(entry.getKey())) { DBHelper.setPGObject(this.updateRes, entry.getKey(), AJEntityResource.UUID_TYPE, mapValue); if (this.updateRes.hasErrors()) { return new ExecutionResult<>( MessageResponseFactory.createValidationErrorResponse(this.updateRes.errors()), ExecutionResult.ExecutionStatus.FAILED); } } else { this.updateRes.set(entry.getKey(), entry.getValue()); // intentionally // kept // entry.getValue // instead of // mapValue as it // needs to handle // other datatypes // like boolean } } Integer licenseFromRequest = this.updateRes.getInteger(AJEntityResource.LICENSE); if (licenseFromRequest != null && !DBHelper.isValidLicense(licenseFromRequest)) { this.updateRes.setInteger(AJEntityResource.LICENSE, DBHelper.getDafaultLicense()); } LOGGER.debug(" \n **** Model to save: {}", this.updateRes); return new ExecutionResult<>(null, ExecutionResult.ExecutionStatus.CONTINUE_PROCESSING); }