com.fasterxml.jackson.databind.node.JsonNodeFactory Java Examples

The following examples show how to use com.fasterxml.jackson.databind.node.JsonNodeFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LearningController.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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();
   }
 
Example #2
Source File: ConverterTest.java    From beast with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: CompilerOptionsParserTests.java    From vscode-as3mxml with Apache License 2.0 6 votes vote down vote up
@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.");
}
 
Example #4
Source File: CompilerOptionsParserTests.java    From vscode-as3mxml with Apache License 2.0 6 votes vote down vote up
@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.");
}
 
Example #5
Source File: ServerImpl.java    From Javacord with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #6
Source File: CompilerOptionsParserTests.java    From vscode-as3mxml with Apache License 2.0 6 votes vote down vote up
@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.");
}
 
Example #7
Source File: AIROptionsParserTests.java    From vscode-as3mxml with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #8
Source File: TblMonitorController.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
    * 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();

   }
 
Example #9
Source File: ProductBatchProcessorTest.java    From commercetools-sync-java with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #10
Source File: LearningController.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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);
   }
 
Example #11
Source File: JsonldContextFactory.java    From jackson-jsonld with MIT License 6 votes vote down vote up
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();
}
 
Example #12
Source File: SkypeMentionNormalizeMiddleware.java    From botbuilder-java with MIT License 6 votes vote down vote up
/**
 * 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);
                    }
                }
            }
        }
    }
}
 
Example #13
Source File: CompilerOptionsParserTests.java    From vscode-as3mxml with Apache License 2.0 6 votes vote down vote up
@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.");
}
 
Example #14
Source File: CompilerOptionsParserTests.java    From vscode-as3mxml with Apache License 2.0 6 votes vote down vote up
@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.");
}
 
Example #15
Source File: CompilerOptionsParserTests.java    From vscode-as3mxml with Apache License 2.0 6 votes vote down vote up
@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.");
}
 
Example #16
Source File: AuthoringController.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
    * 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;
   }
 
Example #17
Source File: UpdateMessagePatchConverterTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #18
Source File: UpdateMessagePatchConverterTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #19
Source File: WithCustomerReferencesTest.java    From commercetools-sync-java with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #20
Source File: CartDiscountSyncUtilsTest.java    From commercetools-sync-java with Apache License 2.0 6 votes vote down vote up
@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")));
}
 
Example #21
Source File: TblMonitoringController.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
    * 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();
   }
 
Example #22
Source File: NotificationRequestConverterTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #23
Source File: ResourceCustomUpdateActionUtilsTest.java    From commercetools-sync-java with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #24
Source File: NotificationMessageArgumentResolverTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@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!");
}
 
Example #25
Source File: AIROptionsParserTests.java    From vscode-as3mxml with Apache License 2.0 5 votes vote down vote up
@Test
void testDefaultOptions()
{
	ObjectNode options = JsonNodeFactory.instance.objectNode();
	ArrayList<String> result = new ArrayList<>();
	parser.parse(AIRPlatform.AIR, false, "application.xml", "content.swf", options, result);
	Assertions.assertEquals(0, result.indexOf("-package"));
	Assertions.assertEquals(1, result.indexOf("-target"));
	Assertions.assertEquals(2, result.indexOf(AIRPlatform.AIR));
}
 
Example #26
Source File: UncachedMessageUtilImpl.java    From Javacord with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Void> delete(long channelId, long... messageIds) {
    // split by younger than two weeks / older than two weeks
    Instant twoWeeksAgo = Instant.now().minus(14, ChronoUnit.DAYS);
    Map<Boolean, List<Long>> messageIdsByAge = Arrays.stream(messageIds).distinct().boxed()
            .collect(Collectors.groupingBy(
                    messageId -> DiscordEntity.getCreationTimestamp(messageId).isAfter(twoWeeksAgo)));

    AtomicInteger batchCounter = new AtomicInteger();
    return CompletableFuture.allOf(Stream.concat(
            // for messages younger than 2 weeks
            messageIdsByAge.getOrDefault(true, Collections.emptyList()).stream()
                    // send batches of 100 messages
                    .collect(Collectors.groupingBy(messageId -> batchCounter.getAndIncrement() / 100))
                    .values().stream()
                    .map(messageIdBatch -> {
                        // do not use batch deletion for a single message
                        if (messageIdBatch.size() == 1) {
                            return Message.delete(api, channelId, messageIdBatch.get(0));
                        }

                        ObjectNode body = JsonNodeFactory.instance.objectNode();
                        ArrayNode messages = body.putArray("messages");
                        messageIdBatch.stream()
                                .map(Long::toUnsignedString)
                                .forEach(messages::add);

                        return new RestRequest<Void>(api, RestMethod.POST, RestEndpoint.MESSAGES_BULK_DELETE)
                                .setUrlParameters(Long.toUnsignedString(channelId))
                                .setBody(body)
                                .execute(result -> null);
                    }),
            // for messages older than 2 weeks use single message deletion
            messageIdsByAge.getOrDefault(false, Collections.emptyList()).stream()
                    .map(messageId -> Message.delete(api, channelId, messageId))
    ).toArray(CompletableFuture[]::new));
}
 
Example #27
Source File: JmapRequestParserImplTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void extractJmapRequestShouldNotThrowWhenJsonContainsUnknownProperty() throws Exception {
    ObjectNode parameters = new ObjectNode(new JsonNodeFactory(false));
    parameters.put("id", "myId");
    JsonNode[] nodes = new JsonNode[] { new ObjectNode(new JsonNodeFactory(false)).textNode("unknwonMethod"),
            parameters,
            new ObjectNode(new JsonNodeFactory(false)).textNode("#1")};

    testee.extractJmapRequest(InvocationRequest.deserialize(nodes), RequestClass.class);
}
 
Example #28
Source File: WorkflowManager.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void createWorkplace(WorkplaceDescription wpDesc) throws WorkflowException {
    log.info("createWorkplace: {}", wpDesc);

    JsonNode root;
    if (wpDesc.data().isPresent()) {
        root = wpDesc.data().get();
    } else {
        root = JsonNodeFactory.instance.objectNode();
    }
    DefaultWorkplace workplace =
            new DefaultWorkplace(wpDesc.name(), new JsonDataModelTree(root));
    workplaceStore.registerWorkplace(wpDesc.name(), workplace);
}
 
Example #29
Source File: EntityTest.java    From aws-xray-sdk-java with Apache License 2.0 5 votes vote down vote up
public ObjectNode expectedCompletedSegment(TraceID traceId, String segmentId, double startTime, double endTime) {
    ObjectNode expected = JsonNodeFactory.instance.objectNode();
    expected.put("name", "test");
    expected.put("start_time", startTime);
    expected.put("end_time", endTime);
    expected.put("trace_id", traceId.toString());
    expected.put("id", segmentId);
    return expected;
}
 
Example #30
Source File: MonitoringController.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * Gets users whose progress bars will be displayed in Learner tab in Monitor.
    */
   @RequestMapping("/getLearnerProgressPage")
   @ResponseBody
   public String getLearnerProgressPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID);
if (!securityService.isLessonMonitor(lessonId, getUserId(), "get learner progress page", false)) {
    response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson");
    return null;
}

String searchPhrase = request.getParameter("searchPhrase");
Integer pageNumber = WebUtil.readIntParam(request, "pageNumber", true);
if (pageNumber == null) {
    pageNumber = 1;
}
// are the learners sorted by the most completed first?
boolean isProgressSorted = WebUtil.readBooleanParam(request, "isProgressSorted", false);

// either sort by name or how much a learner progressed into the lesson
List<User> learners = isProgressSorted
	? monitoringService.getLearnersByMostProgress(lessonId, searchPhrase, 10, (pageNumber - 1) * 10)
	: lessonService.getLessonLearners(lessonId, searchPhrase, 10, (pageNumber - 1) * 10, true);
ObjectNode responseJSON = JsonNodeFactory.instance.objectNode();
for (User learner : learners) {
    responseJSON.withArray("learners").add(WebUtil.userToJSON(learner));
}

// get all possible learners matching the given phrase, if any; used for max page number
responseJSON.put("learnerPossibleNumber", lessonService.getCountLessonLearners(lessonId, searchPhrase));
response.setContentType("application/json;charset=utf-8");
return responseJSON.toString();
   }