下面列出了怎么用com.fasterxml.jackson.databind.node.JsonNodeFactory的API类实例代码及写法,或者点击链接到github查看源代码。
@RequestMapping("/submitCommentsAjax")
@ResponseBody
@SuppressWarnings("unchecked")
public String submitCommentsAjax(HttpServletRequest request, HttpServletResponse response, HttpSession session)
throws IOException, ServletException {
String sessionMapID = request.getParameter(PeerreviewConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) session.getAttribute(sessionMapID);
request.setAttribute(PeerreviewConstants.ATTR_SESSION_MAP_ID, sessionMapID);
PeerreviewUser user = (PeerreviewUser) sessionMap.get(PeerreviewConstants.ATTR_USER);
Long toolSessionId = (Long) sessionMap.get(PeerreviewConstants.PARAM_TOOL_SESSION_ID);
Peerreview peerreview = service.getPeerreviewBySessionId(toolSessionId);
Long criteriaId = WebUtil.readLongParam(request, "criteriaId");
RatingCriteria criteria = service.getCriteriaByCriteriaId(criteriaId);
int countCommentsSaved = saveComments(request, toolSessionId, peerreview, user, criteria);
ObjectNode responsedata = JsonNodeFactory.instance.objectNode();
int countRatedQuestions = service.getCountItemsRatedByUserByCriteria(criteriaId, user.getUserId().intValue());
responsedata.put(AttributeNames.ATTR_COUNT_RATED_ITEMS, countRatedQuestions);
responsedata.put("countCommentsSaved", countCommentsSaved);
response.setContentType("application/json;charset=utf-8");
return responsedata.toString();
}
@Test
public void shouldTestShouldCreateFirstLevelColumnMappingSuccessfully() throws IOException {
ProtoField protoField = new ProtoField(new ArrayList<ProtoField>() {{
add(new ProtoField("order_number", 1));
add(new ProtoField("order_url", 2));
add(new ProtoField("order_details", 3));
add(new ProtoField("created_at", 4));
add(new ProtoField("status", 5));
}});
ObjectNode objNode = JsonNodeFactory.instance.objectNode();
objNode.put("1", "order_number");
objNode.put("2", "order_url");
objNode.put("3", "order_details");
objNode.put("4", "created_at");
objNode.put("5", "status");
String columnMapping = converter.generateColumnMappings(protoField.getFields());
String expectedProtoMapping = objectMapper.writeValueAsString(objNode);
assertEquals(expectedProtoMapping, columnMapping);
}
@Test
void testIOSOutput()
{
String androidValue = "path/to/file.apk";
String iOSValue = "path/to/file.ipa";
ObjectNode options = JsonNodeFactory.instance.objectNode();
ObjectNode android = JsonNodeFactory.instance.objectNode();
android.set(AIROptions.OUTPUT, JsonNodeFactory.instance.textNode(androidValue));
options.set(AIRPlatform.ANDROID, android);
ObjectNode ios = JsonNodeFactory.instance.objectNode();
ios.set(AIROptions.OUTPUT, JsonNodeFactory.instance.textNode(iOSValue));
options.set(AIRPlatform.IOS, ios);
ArrayList<String> result = new ArrayList<>();
parser.parse(AIRPlatform.IOS, false, "application.xml", "content.swf", options, result);
Assertions.assertNotEquals(-1, result.indexOf(iOSValue));
Assertions.assertEquals(-1, result.indexOf(androidValue));
}
@Test
void testSizeReport()
{
String value = "path/to/file.xml";
ObjectNode options = JsonNodeFactory.instance.objectNode();
options.set(CompilerOptions.SIZE_REPORT, JsonNodeFactory.instance.textNode(value));
ArrayList<String> result = new ArrayList<>();
try
{
parser.parse(options, null, result);
}
catch(UnknownCompilerOptionException e) {}
Assertions.assertEquals(1, result.size(),
"CompilerOptionsParser.parse() created incorrect number of options.");
Assertions.assertEquals("--" + CompilerOptions.SIZE_REPORT + "=" + value, result.get(0),
"CompilerOptionsParser.parse() incorrectly formatted compiler option.");
}
@Test
void testKeepGeneratedActionScript()
{
boolean value = true;
ObjectNode options = JsonNodeFactory.instance.objectNode();
options.set(CompilerOptions.KEEP_GENERATED_ACTIONSCRIPT, JsonNodeFactory.instance.booleanNode(value));
ArrayList<String> result = new ArrayList<>();
try
{
parser.parse(options, null, result);
}
catch(UnknownCompilerOptionException e) {}
Assertions.assertEquals(1, result.size(),
"CompilerOptionsParser.parse() created incorrect number of options.");
Assertions.assertEquals("--" + CompilerOptions.KEEP_GENERATED_ACTIONSCRIPT + "=" + Boolean.toString(value), result.get(0),
"CompilerOptionsParser.parse() incorrectly formatted compiler option.");
}
@RequestMapping("/removeLike")
@ResponseStatus(HttpStatus.OK)
private void removeLike(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException, ScratchieApplicationException {
String sessionMapID = WebUtil.readStrParam(request, ScratchieConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession()
.getAttribute(sessionMapID);
final Long sessionId = (Long) sessionMap.get(AttributeNames.PARAM_TOOL_SESSION_ID);
ScratchieSession toolSession = scratchieService.getScratchieSessionBySessionId(sessionId);
Long burningQuestionUid = WebUtil.readLongParam(request, ScratchieConstants.PARAM_BURNING_QUESTION_UID);
ScratchieUser leader = this.getCurrentUser(sessionId);
// only leader is allowed to scratch answers
if (!toolSession.isUserGroupLeader(leader.getUid())) {
return;
}
scratchieService.removeLike(burningQuestionUid, sessionId);
ObjectNode ObjectNode = JsonNodeFactory.instance.objectNode();
ObjectNode.put("added", true);
response.setContentType("application/json;charset=utf-8");
response.getWriter().print(ObjectNode);
}
public static Optional<ObjectNode> fromAnnotations(Class<?> objType) {
ObjectNode generatedContext = JsonNodeFactory.withExactBigDecimals(true).objectNode();
generateNamespaces(objType).forEach((name, uri) -> generatedContext.set(name, new TextNode(uri)));
//TODO: This is bad...it does not consider other Jackson annotations. Need to use a AnnotationIntrospector?
final Map<String, JsonNode> fieldContexts = generateContextsForFields(objType);
fieldContexts.forEach(generatedContext::set);
//add links
JsonldLink[] links = objType.getAnnotationsByType(JsonldLink.class);
if (links != null) {
for (int i = 0; i < links.length; i++) {
com.fasterxml.jackson.databind.node.ObjectNode linkNode = JsonNodeFactory.withExactBigDecimals(true)
.objectNode();
linkNode.set("@id", new TextNode(links[i].rel()));
linkNode.set("@type", new TextNode("@id"));
generatedContext.set(links[i].name(), linkNode);
}
}
//Return absent optional if context is empty
return generatedContext.size() != 0 ? Optional.of(generatedContext) : Optional.empty();
}
@Test
void resolveArgument_withValidMessagePayload_shouldReturnNotificationMessage()
throws Exception {
// Arrange
NotificationMessageArgumentResolver notificationMessageArgumentResolver = new NotificationMessageArgumentResolver(
new StringMessageConverter());
Method methodWithNotificationMessageArgument = this.getClass()
.getDeclaredMethod("methodWithNotificationMessageArgument", String.class);
MethodParameter methodParameter = new MethodParameter(
methodWithNotificationMessageArgument, 0);
ObjectNode jsonObject = JsonNodeFactory.instance.objectNode();
jsonObject.put("Type", "Notification");
jsonObject.put("Message", "Hello World!");
String payload = jsonObject.toString();
Message<String> message = MessageBuilder.withPayload(payload).build();
// Act
Object result = notificationMessageArgumentResolver
.resolveArgument(methodParameter, message);
// Assert
assertThat(String.class.isInstance(result)).isTrue();
assertThat(result).isEqualTo("Hello World!");
}
@Test
void buildSetCustomFieldsUpdateActions_WithDifferentOrderOfCustomFieldValues_ShouldNotBuildUpdateActions() {
final Map<String, JsonNode> oldCustomFields = new HashMap<>();
oldCustomFields.put("backgroundColor",
JsonNodeFactory.instance.objectNode().put("de", "rot").put("es", "rojo"));
final Map<String, JsonNode> newCustomFields = new HashMap<>();
newCustomFields.put("backgroundColor",
JsonNodeFactory.instance.objectNode().put("es", "rojo").put("de", "rot"));
final List<UpdateAction<Category>> setCustomFieldsUpdateActions =
buildSetCustomFieldsUpdateActions(oldCustomFields, newCustomFields, mock(Category.class),
new CategoryCustomActionBuilder(),null, category -> null);
assertThat(setCustomFieldsUpdateActions).isNotNull();
assertThat(setCustomFieldsUpdateActions).isEmpty();
}
/**
* Save selected user as a leader.
*/
@RequestMapping(path = "/changeLeader", method = RequestMethod.POST)
@ResponseBody
public String changeLeader(HttpServletRequest request, HttpServletResponse response) {
Long leaderUserId = WebUtil.readLongParam(request, AttributeNames.PARAM_USER_ID);
Long toolContentId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID);
LeaderselectionUser user = leaderselectionService.getUserByUserIdAndContentId(leaderUserId, toolContentId);
// save selected user as a leader
boolean isSuccessful = false;
if (user != null) {
Long toolSessionId = user.getLeaderselectionSession().getSessionId();
log.info("Changing group leader for toolSessionId=" + toolSessionId + ". New leader's userUid="
+ leaderUserId);
isSuccessful = leaderselectionService.setGroupLeader(user.getUid(), toolSessionId);
}
// build JSON
ObjectNode responseJSON = JsonNodeFactory.instance.objectNode();
responseJSON.put("isSuccessful", isSuccessful);
response.setContentType("application/json;charset=UTF-8");
return responseJSON.toString();
}
@Test
void resolveReferences_WithNullIdFieldInCustomerReferenceAttribute_ShouldNotResolveReferences() {
// preparation
final ObjectNode attributeValue = JsonNodeFactory.instance.objectNode();
attributeValue.put(REFERENCE_TYPE_ID_FIELD, Customer.referenceTypeId());
final AttributeDraft customerReferenceAttribute = AttributeDraft.of("attributeName", attributeValue);
final ProductVariantDraft productVariantDraft = ProductVariantDraftBuilder
.of()
.attributes(customerReferenceAttribute)
.build();
// test
final ProductVariantDraft resolvedAttributeDraft =
referenceResolver.resolveReferences(productVariantDraft)
.toCompletableFuture()
.join();
// assertions
assertThat(resolvedAttributeDraft).isEqualTo(productVariantDraft);
}
/**
* Returns the serialized XML of the Mindmap Nodes from Database
*/
@RequestMapping("/setMindmapContentJSON")
@ResponseBody
public String setMindmapContentJSON(HttpServletRequest request, HttpServletResponse response) throws IOException {
Long mindmapId = WebUtil.readLongParam(request, "mindmapId", false);
List mindmapNodeList = mindmapService.getAuthorRootNodeByMindmapId(mindmapId);
if (mindmapNodeList != null && mindmapNodeList.size() > 0) {
MindmapNode rootMindmapNode = (MindmapNode) mindmapNodeList.get(0);
String rootMindmapUser = messageService.getMessage("node.instructor.label");
NodeModel rootNodeModel = new NodeModel(new NodeConceptModel(rootMindmapNode.getUniqueId(),
rootMindmapNode.getText(), rootMindmapNode.getColor(), rootMindmapUser, 1));
NodeModel currentNodeModel = mindmapService.getMindmapXMLFromDatabase(rootMindmapNode.getNodeId(),
mindmapId, rootNodeModel, null, false, true, false);
ObjectNode jsonObject = JsonNodeFactory.instance.objectNode();
jsonObject.set("mindmap", new RootJSON(currentNodeModel, false));
response.setContentType("application/json;charset=UTF-8");
return jsonObject.toString();
}
return null;
}
@Test
void testDefaultSize()
{
int width = 828;
int height = 367;
ObjectNode options = JsonNodeFactory.instance.objectNode();
ObjectNode defaultSize = JsonNodeFactory.instance.objectNode();
defaultSize.set(CompilerOptions.DEFAULT_SIZE__WIDTH, JsonNodeFactory.instance.numberNode(width));
defaultSize.set(CompilerOptions.DEFAULT_SIZE__HEIGHT, JsonNodeFactory.instance.numberNode(height));
options.set(CompilerOptions.DEFAULT_SIZE, defaultSize);
ArrayList<String> result = new ArrayList<>();
try
{
parser.parse(options, null, result);
}
catch(UnknownCompilerOptionException e) {}
Assertions.assertEquals(3, result.size(),
"CompilerOptionsParser.parse() created incorrect number of options.");
Assertions.assertEquals("--" + CompilerOptions.DEFAULT_SIZE, result.get(0),
"CompilerOptionsParser.parse() incorrectly formatted compiler option.");
Assertions.assertEquals(Integer.toString(width), result.get(1),
"CompilerOptionsParser.parse() incorrectly formatted compiler option.");
Assertions.assertEquals(Integer.toString(height), result.get(2),
"CompilerOptionsParser.parse() incorrectly formatted compiler option.");
}
@Test
public void fromJsonNodeShouldReturnNoErrorWhenPatchIsValid() {
UpdateMessagePatchValidator mockValidator = mock(UpdateMessagePatchValidator.class);
when(mockValidator.isValid(any(ObjectNode.class))).thenReturn(true);
when(mockValidator.validate(any(ObjectNode.class))).thenReturn(ImmutableSet.of());
verify(mockValidator, never()).validate(any(ObjectNode.class));
ObjectMapper jsonParser = new ObjectMapper();
UpdateMessagePatchConverter sut = new UpdateMessagePatchConverter(jsonParser, mockValidator);
ObjectNode dummynode = JsonNodeFactory.instance.objectNode();
UpdateMessagePatch result = sut.fromJsonNode(dummynode);
assertThat(result.getValidationErrors().isEmpty()).isTrue();
}
@Test
public void fromJsonNodeShouldSetValidationResultWhenPatchIsInvalid() {
UpdateMessagePatchValidator stubValidator = mock(UpdateMessagePatchValidator.class);
when(stubValidator.isValid(any(ObjectNode.class))).thenReturn(false);
ImmutableSet<ValidationResult> nonEmptyValidationResult = ImmutableSet.of(ValidationResult.builder().build());
when(stubValidator.validate(any(ObjectNode.class))).thenReturn(nonEmptyValidationResult);
UpdateMessagePatchConverter sut = new UpdateMessagePatchConverter(null, stubValidator);
ObjectNode dummynode = JsonNodeFactory.instance.objectNode();
UpdateMessagePatch result = sut.fromJsonNode(dummynode);
assertThat(result).extracting(UpdateMessagePatch::getValidationErrors)
.asList()
.isNotEmpty();
}
@Test
void buildActions_WithSameCustomTypeWithNewCustomFields_ShouldBuildUpdateAction() {
final CustomFieldsDraft sameCustomFieldDraftWithNewCustomField =
CustomFieldsDraftBuilder.ofTypeId(CUSTOM_TYPE_ID)
.addObject(CUSTOM_FIELD_NAME, CUSTOM_FIELD_VALUE)
.addObject("name_2", "value_2")
.build();
final CartDiscountDraft cartDiscountDraftWithCustomField =
CartDiscountDraftBuilder.of(cartDiscountDraft)
.custom(sameCustomFieldDraftWithNewCustomField)
.build();
final List<UpdateAction<CartDiscount>> actions =
buildActions(cartDiscount, cartDiscountDraftWithCustomField,
CartDiscountSyncOptionsBuilder.of(mock(SphereClient.class)).build());
assertThat(actions).containsExactly(
SetCustomField.ofJson("name_2", JsonNodeFactory.instance.textNode("value_2")));
}
@Test
void fromMessage_withNumberAttribute_shouldReturnMessage() throws Exception {
// Arrange
ObjectNode jsonObject = JsonNodeFactory.instance.objectNode();
jsonObject.put("Type", "Notification");
jsonObject.put("Message", "World");
ObjectNode messageAttributes = JsonNodeFactory.instance.objectNode();
messageAttributes.set("number-attribute", JsonNodeFactory.instance.objectNode()
.put("Value", "30").put("Type", "Number.long"));
jsonObject.set("MessageAttributes", messageAttributes);
String payload = jsonObject.toString();
// Act
Object notificationRequest = new NotificationRequestConverter(
new StringMessageConverter()).fromMessage(
MessageBuilder.withPayload(payload).build(), String.class);
// Assert
assertThat(notificationRequest).isNotNull();
}
@Test
void testHTMLOutputFilename()
{
String value = "html-output.html";
ObjectNode options = JsonNodeFactory.instance.objectNode();
options.set(CompilerOptions.HTML_OUTPUT_FILENAME, JsonNodeFactory.instance.textNode(value));
ArrayList<String> result = new ArrayList<>();
try
{
parser.parse(options, null, result);
}
catch(UnknownCompilerOptionException e) {}
Assertions.assertEquals(1, result.size(),
"CompilerOptionsParser.parse() created incorrect number of options.");
Assertions.assertEquals("--" + CompilerOptions.HTML_OUTPUT_FILENAME + "=" + value, result.get(0),
"CompilerOptionsParser.parse() incorrectly formatted compiler option.");
}
/**
* Fixes incorrect Skype mention text. This will change the text value for all
* Skype mention entities.
*
* @param activity The Activity to correct.
*/
public static void normalizeSkypeMentionText(Activity activity) {
if (
StringUtils.equals(activity.getChannelId(), Channels.SKYPE)
&& StringUtils.equals(activity.getType(), ActivityTypes.MESSAGE)
) {
for (Entity entity : activity.getEntities()) {
if (StringUtils.equals(entity.getType(), "mention")) {
String text = entity.getProperties().get("text").asText();
int closingBracket = text.indexOf(">");
if (closingBracket != -1) {
int openingBracket = text.indexOf("<", closingBracket);
if (openingBracket != -1) {
String mention = text.substring(closingBracket + 1, openingBracket)
.trim();
// create new JsonNode with new mention value
JsonNode node = JsonNodeFactory.instance.textNode(mention);
entity.setProperties("text", node);
}
}
}
}
}
}
@Test
void getReferencedProductKeysFromSet_WithNullAndOtherRefsInSet_ShouldReturnSetOfNonNullIds() {
final ObjectNode objectNode = JsonNodeFactory.instance.objectNode();
objectNode.put("key", "value");
final AttributeDraft productReferenceSetAttribute =
getReferenceSetAttributeDraft("foo", getProductReferenceWithId("foo"),
getProductReferenceWithId("bar"), objectNode);
final ProductVariantDraft productVariantDraft = ProductVariantDraftBuilder
.of()
.attributes(productReferenceSetAttribute)
.build();
final Set<String> result = getReferencedProductKeys(productVariantDraft);
assertThat(result).containsExactlyInAnyOrder("foo", "bar");
}
@Test
void testKeepAllTypeSelectors()
{
boolean value = true;
ObjectNode options = JsonNodeFactory.instance.objectNode();
options.set(CompilerOptions.KEEP_ALL_TYPE_SELECTORS, JsonNodeFactory.instance.booleanNode(value));
ArrayList<String> result = new ArrayList<>();
try
{
parser.parse(options, null, result);
}
catch(UnknownCompilerOptionException e) {}
Assertions.assertEquals(1, result.size(),
"CompilerOptionsParser.parse() created incorrect number of options.");
Assertions.assertEquals("--" + CompilerOptions.KEEP_ALL_TYPE_SELECTORS + "=" + Boolean.toString(value), result.get(0),
"CompilerOptionsParser.parse() incorrectly formatted compiler option.");
}
/**
* Shows Teams page
*
* @throws JSONException
*/
@RequestMapping(value = "/isBurningQuestionsEnabled")
@ResponseBody
public String isBurningQuestionsEnabled(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
long toolContentId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID);
Scratchie scratchie = scratchieService.getScratchieByContentId(toolContentId);
// build JSON
ObjectNode responseJSON = JsonNodeFactory.instance.objectNode();
responseJSON.put("isBurningQuestionsEnabled", scratchie.isBurningQuestionsEnabled());
response.setContentType("application/json;charset=UTF-8");
return responseJSON.toString();
}
@Override
public CompletableFuture<Void> reorderRoles(List<Role> roles, String reason) {
roles = new ArrayList<>(roles); // Copy the list to safely modify it
ArrayNode body = JsonNodeFactory.instance.arrayNode();
roles.removeIf(Role::isEveryoneRole);
for (int i = 0; i < roles.size(); i++) {
body.addObject()
.put("id", roles.get(i).getIdAsString())
.put("position", i + 1);
}
return new RestRequest<Void>(getApi(), RestMethod.PATCH, RestEndpoint.ROLE)
.setUrlParameters(getIdAsString())
.setBody(body)
.setAuditLogReason(reason)
.execute(result -> null);
}
@Test
void testOmitTraceStatements()
{
boolean value = true;
ObjectNode options = JsonNodeFactory.instance.objectNode();
options.set(CompilerOptions.OMIT_TRACE_STATEMENTS, JsonNodeFactory.instance.booleanNode(value));
ArrayList<String> result = new ArrayList<>();
try
{
parser.parse(options, null, result);
}
catch(UnknownCompilerOptionException e) {}
Assertions.assertEquals(1, result.size(),
"CompilerOptionsParser.parse() created incorrect number of options.");
Assertions.assertEquals("--" + CompilerOptions.OMIT_TRACE_STATEMENTS + "=" + Boolean.toString(value), result.get(0),
"CompilerOptionsParser.parse() incorrectly formatted compiler option.");
}
/**
* Creates a productDraft with a master variant containing the following priceDrafts:
* <ul>
* <li>DE_111_EUR</li>
* <li>DE_222_EUR_CUST1</li>
* <li>DE_111_EUR_01_02</li>
* <li>DE_111_EUR_03_04</li>
* <li>DE_100_EUR_01_02_CHANNEL1_CUSTOMTYPE1_CUSTOMFIELD{en, de}</li>
* <li>DE_100_EUR_01_02_CHANNEL2_CUSTOMTYPE1_CUSTOMFIELD{en, de}</li>
* <li>DE_333_USD_CUST1</li>
* <li>DE_22_USD</li>
* <li>UK_111_GBP_01_02</li>
* <li>UK_999_GBP</li>
* <li>US_666_USD_CUST2_01_02,</li>
* <li>FR_888_EUR_01_03</li>
* <li>FR_999_EUR_03_06</li>
* <li>NE_777_EUR_01_04</li>
* <li>NE_777_EUR_05_07</li>
* </ul>
*/
private ProductDraft createProductDraftWithNewPrices() {
final ObjectNode lTextWithEnDe = JsonNodeFactory.instance.objectNode()
.put("de", "rot")
.put("en", "red");
final CustomFieldsDraft customType1WithEnDeOfKey = CustomFieldsDraft.ofTypeIdAndJson("customType1",
createCustomFieldsJsonMap(LOCALISED_STRING_CUSTOM_FIELD_NAME, lTextWithEnDe));
final PriceDraft withChannel1CustomType1WithEnDeOfKey = getPriceDraft(BigDecimal.valueOf(100), EUR,
DE, null, byMonth(1), byMonth(2), "channel1", customType1WithEnDeOfKey);
final PriceDraft withChannel2CustomType1WithEnDeOfKey = getPriceDraft(BigDecimal.valueOf(100), EUR,
DE, null, byMonth(1), byMonth(2), "channel2", customType1WithEnDeOfKey);
final List<PriceDraft> newPrices = asList(
DRAFT_DE_111_EUR,
DRAFT_DE_222_EUR_CUST1,
DRAFT_DE_111_EUR_01_02,
DRAFT_DE_111_EUR_03_04,
withChannel1CustomType1WithEnDeOfKey,
withChannel2CustomType1WithEnDeOfKey,
DRAFT_DE_333_USD_CUST1,
DRAFT_DE_22_USD,
DRAFT_UK_111_GBP_01_02,
DRAFT_UK_999_GBP,
DRAFT_US_666_USD_CUST2_01_02,
DRAFT_FR_888_EUR_01_03,
DRAFT_FR_999_EUR_03_06,
DRAFT_NE_777_EUR_01_04,
DRAFT_NE_777_EUR_05_07);
return ProductDraftBuilder
.of(referenceOfId(productType.getKey()), ofEnglish("foo"), ofEnglish("bar"),
createVariantDraft("foo", null, newPrices))
.key("bar")
.build();
}
public void moveJob(ServerConfig serverConfig, String jobId, String jobType) {
String jobUrl = getJobUrl(jobType);
HttpPost post = clientUtil.createPost(jobUrl + jobId, serverConfig);
ObjectNode node = JsonNodeFactory.instance.objectNode();
node.put("action", "move");
post.setEntity(clientUtil.createStringEntity(node));
clientUtil.executeRequestNoResponseBody(post, serverConfig, HttpStatus.SC_NO_CONTENT);
}
@Query
public JsonResult getJsonArray(int count) {
JsonNodeFactory jsonNodeFactory = JsonNodeFactory.instance;
ArrayNode arrayNode = new ArrayNode(jsonNodeFactory);
for (int i = 0; i < count; i++) {
arrayNode.add(i);
}
JsonResult jsonResult = new JsonResult();
jsonResult.jsonNode = arrayNode;
return jsonResult;
}
private URLFilter createFilter() {
ObjectNode filterParams = new ObjectNode(JsonNodeFactory.instance);
filterParams.put("files", "fast.urlfilter.json");
FastURLFilter filter = new FastURLFilter();
Map<String, Object> conf = new HashMap<>();
filter.configure(conf, filterParams);
return filter;
}
@Test
public void shouldUseNewSchemaIfProtoChanges() throws IOException {
ProtoField returnedProtoField = new ProtoField();
when(protoFieldFactory.getProtoField()).thenReturn(returnedProtoField);
returnedProtoField.addField(new ProtoField("order_number", 1));
returnedProtoField.addField(new ProtoField("order_url", 2));
HashMap<String, DescriptorAndTypeName> descriptorsMap = new HashMap<String, DescriptorAndTypeName>() {{
put(String.format("%s.%s", TestKey.class.getPackage(), TestKey.class.getName()), new DescriptorAndTypeName(TestKey.getDescriptor(), String.format(".%s.%s", TestKey.getDescriptor().getFile().getPackage(), TestKey.getDescriptor().getName())));
}};
when(protoMappingParser.parseFields(returnedProtoField, stencilConfig.getProtoSchema(), StencilUtils.getAllProtobufDescriptors(descriptorsMap), StencilUtils.getTypeNameToPackageNameMap(descriptorsMap))).thenReturn(returnedProtoField);
ObjectNode objNode = JsonNodeFactory.instance.objectNode();
objNode.put("1", "order_number");
objNode.put("2", "order_url");
String expectedProtoMapping = objectMapper.writeValueAsString(objNode);
when(protoMappingConverter.generateColumnMappings(returnedProtoField.getFields())).thenReturn(expectedProtoMapping);
ArrayList<Field> returnedSchemaFields = new ArrayList<Field>() {{
add(Field.newBuilder("order_number", LegacySQLTypeName.STRING).setMode(Field.Mode.NULLABLE).build());
add(Field.newBuilder("order_url", LegacySQLTypeName.STRING).setMode(Field.Mode.NULLABLE).build());
}};
when(protoMappingConverter.generateBigquerySchema(returnedProtoField)).thenReturn(returnedSchemaFields);
ArrayList<Field> bqSchemaFields = new ArrayList<Field>() {{
add(Field.newBuilder("order_number", LegacySQLTypeName.STRING).setMode(Field.Mode.NULLABLE).build());
add(Field.newBuilder("order_url", LegacySQLTypeName.STRING).setMode(Field.Mode.NULLABLE).build());
add(Field.newBuilder(Constants.OFFSET_COLUMN_NAME, LegacySQLTypeName.INTEGER).setMode(Field.Mode.NULLABLE).build());
add(Field.newBuilder(Constants.TOPIC_COLUMN_NAME, LegacySQLTypeName.STRING).setMode(Field.Mode.NULLABLE).build());
add(Field.newBuilder(Constants.LOAD_TIME_COLUMN_NAME, LegacySQLTypeName.TIMESTAMP).setMode(Field.Mode.NULLABLE).build());
add(Field.newBuilder(Constants.TIMESTAMP_COLUMN_NAME, LegacySQLTypeName.TIMESTAMP).setMode(Field.Mode.NULLABLE).build());
add(Field.newBuilder(Constants.PARTITION_COLUMN_NAME, LegacySQLTypeName.INTEGER).setMode(Field.Mode.NULLABLE).build());
}};
doNothing().when(bqInstance).upsertTable(bqSchemaFields);
protoUpdateListener.onProtoUpdate(stencilConfig.getStencilUrl(), descriptorsMap);
ColumnMapping actualNewProtoMapping = protoMappingConfig.getProtoColumnMapping();
Assert.assertEquals("order_number", actualNewProtoMapping.getProperty("1"));
Assert.assertEquals("order_url", actualNewProtoMapping.getProperty("2"));
}
/**
* Converts a DynamoDB object to a JSON map.
*
* @param item
* DynamoDB object
* @param depth
* Current JSON depth
* @return JSON map representation of the DynamoDB object
* @throws JacksonConverterException
* Null DynamoDB object or JSON too deep
*/
private JsonNode mapToJsonObject(final Map<String, AttributeValue> item, final int depth)
throws JacksonConverterException {
assertDepth(depth);
if (item != null) {
final ObjectNode node = JsonNodeFactory.instance.objectNode();
for (final Entry<String, AttributeValue> entry : item.entrySet()) {
node.put(entry.getKey(), getJsonNode(entry.getValue(), depth + 1));
}
return node;
}
throw new JacksonConverterException("Item cannot be null");
}