@Test public void testKillTaskSerde() throws Exception { final KillTask task = new KillTask(null, "foo", new Interval("2010-01-01/P1D"), null); final String json = jsonMapper.writeValueAsString(task); Thread.sleep(100); // Just want to run the clock a bit to make sure the task id doesn't change final KillTask task2 = (KillTask) jsonMapper.readValue(json, Task.class); Assert.assertEquals("foo", task.getDataSource()); Assert.assertEquals(new Interval("2010-01-01/P1D"), task.getInterval()); Assert.assertEquals(task.getId(), task2.getId()); Assert.assertEquals(task.getGroupId(), task2.getGroupId()); Assert.assertEquals(task.getDataSource(), task2.getDataSource()); Assert.assertEquals(task.getInterval(), task2.getInterval()); final KillTask task3 = (KillTask) jsonMapper.readValue( jsonMapper.writeValueAsString( new ClientKillQuery("foo", new Interval("2010-01-01/P1D"))), Task.class); Assert.assertEquals("foo", task3.getDataSource()); Assert.assertEquals(new Interval("2010-01-01/P1D"), task3.getInterval()); }
private HadoopDruidIndexerConfig testRunUpdateSegmentListIfDatasourcePathSpecIsUsed( PathSpec datasourcePathSpec, Interval jobInterval) throws Exception { HadoopIngestionSpec spec = new HadoopIngestionSpec( new DataSchema( "foo", null, new AggregatorFactory[0], new UniformGranularitySpec( Granularity.DAY, null, ImmutableList.of(new Interval("2010-01-01/P1D"))), jsonMapper), new HadoopIOConfig(jsonMapper.convertValue(datasourcePathSpec, Map.class), null, null), null); spec = jsonMapper.readValue(jsonMapper.writeValueAsString(spec), HadoopIngestionSpec.class); UsedSegmentLister segmentLister = EasyMock.createMock(UsedSegmentLister.class); EasyMock.expect( segmentLister.getUsedSegmentsForIntervals( testDatasource, Lists.newArrayList(jobInterval))) .andReturn(ImmutableList.of(SEGMENT)); EasyMock.replay(segmentLister); spec = HadoopIngestionSpec.updateSegmentListIfDatasourcePathSpecIsUsed( spec, jsonMapper, segmentLister); return HadoopDruidIndexerConfig.fromString(jsonMapper.writeValueAsString(spec)); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; try { Authentication authentication = authenticationService.getAuthentication(httpRequest); SecurityContextHolder.getContext().setAuthentication(authentication); filterChain.doFilter(httpRequest, httpResponse); } catch (SignatureException exception) { httpResponse.setCharacterEncoding("UTF-8"); httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE); httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); ObjectMapper mapper = new ObjectMapper(); FailureResponse error = new FailureResponse( httpRequest.getMethod(), httpRequest.getRequestURI(), "unauthorized JWT (invalid signature or expired token). Please use auth api to take another valid token."); httpResponse.getWriter().println(mapper.writeValueAsString(error)); SecurityContextHolder.clearContext(); } catch (MalformedJwtException exception) { httpResponse.setCharacterEncoding("UTF-8"); httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE); httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); ObjectMapper mapper = new ObjectMapper(); FailureResponse error = new FailureResponse( httpRequest.getMethod(), httpRequest.getRequestURI(), "malformed token. Please use auth api to take another valid token."); httpResponse.getWriter().println(mapper.writeValueAsString(error)); SecurityContextHolder.clearContext(); } catch (Exception exception) { httpResponse.setCharacterEncoding("UTF-8"); httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE); httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); ObjectMapper mapper = new ObjectMapper(); FailureResponse error = new FailureResponse( httpRequest.getMethod(), httpRequest.getRequestURI(), "Internal server error, please contact the backend team."); httpResponse.getWriter().println(mapper.writeValueAsString(error)); LOGGER.error(exception.getMessage(), exception); SecurityContextHolder.clearContext(); } }
@Around("execution(@com.marcolenzo.gameboard.annotations.ActionLoggable * *(..))") public Object around(ProceedingJoinPoint point) throws Throwable { long start = System.currentTimeMillis(); Object result = point.proceed(); User currentUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Action action = new Action(); action.setName(MethodSignature.class.cast(point.getSignature()).getMethod().getName()); // Parse args List<String> jsonStrings = Lists.newArrayList(); for (Object obj : point.getArgs()) { jsonStrings.add(mapper.writeValueAsString(obj)); } action.setArgs(jsonStrings); action.setResult(mapper.writeValueAsString(result)); action.setUserId(currentUser.getId()); action.setDatetime(LocalDateTime.now()); repository.save(action); LOGGER.info( "#{}({}): in {} ms by {}", MethodSignature.class.cast(point.getSignature()).getMethod().getName(), point.getArgs(), System.currentTimeMillis() - start, currentUser.getId() + " " + currentUser.getEmail()); return result; }
protected ContentResponse putRule(HttpCriteria criteria, Collection<HttpEntry> responseEntries) throws JsonProcessingException, InterruptedException, TimeoutException, ExecutionException { return newRequest() .path(PUT_FULL_RULE_PATH) .method(HttpMethod.PUT) .param("criteria", MAPPER.writeValueAsString(criteria)) .param("response", MAPPER.writeValueAsString(responseEntries)) .send(); }
@Override public AsyncFuture<Void> run(final ShellIO io, final TaskParameters base) throws Exception { final Parameters params = (Parameters) base; final String queryString = params.query.stream().collect(Collectors.joining(" ")); final ObjectMapper indent = mapper.copy(); indent.configure(SerializationFeature.INDENT_OUTPUT, true); final QueryOptions.Builder optionsBuilder = QueryOptions.builder().tracing(params.tracing); params.dataLimit.ifPresent(optionsBuilder::dataLimit); params.groupLimit.ifPresent(optionsBuilder::groupLimit); params.seriesLimit.ifPresent(optionsBuilder::seriesLimit); final QueryOptions options = optionsBuilder.build(); final Optional<QueryDateRange> range = Optional.of(new QueryDateRange.Relative(TimeUnit.DAYS, 1)); return query .useGroup(params.group) .query( query .newQueryFromString(queryString) .options(Optional.of(options)) .rangeIfAbsent(range) .build()) .directTransform( result -> { for (final RequestError e : result.getErrors()) { io.out().println(String.format("ERR: %s", e.toString())); } io.out().println(String.format("LIMITS: %s", result.getLimits().getLimits())); for (final ShardedResultGroup resultGroup : result.getGroups()) { final MetricCollection group = resultGroup.getMetrics(); io.out() .println( String.format( "%s: %s %s", group.getType(), resultGroup.getShard(), indent.writeValueAsString(resultGroup.getSeries()))); io.out().println(indent.writeValueAsString(group.getData())); io.out().flush(); } io.out().println("TRACE:"); result.getTrace().formatTrace(io.out()); io.out().flush(); return null; }); }
@Test public void testV1Serialization() throws Exception { final Interval interval = new Interval("2011-10-01/2011-10-02"); final ImmutableMap<String, Object> loadSpec = ImmutableMap.<String, Object>of("something", "or_other"); DataSegment segment = new DataSegment( "something", interval, "1", loadSpec, Arrays.asList("dim1", "dim2"), Arrays.asList("met1", "met2"), NoneShardSpec.instance(), IndexIO.CURRENT_VERSION_ID, 1); final Map<String, Object> objectMap = mapper.readValue( mapper.writeValueAsString(segment), new TypeReference<Map<String, Object>>() {}); Assert.assertEquals(10, objectMap.size()); Assert.assertEquals("something", objectMap.get("dataSource")); Assert.assertEquals(interval.toString(), objectMap.get("interval")); Assert.assertEquals("1", objectMap.get("version")); Assert.assertEquals(loadSpec, objectMap.get("loadSpec")); Assert.assertEquals("dim1,dim2", objectMap.get("dimensions")); Assert.assertEquals("met1,met2", objectMap.get("metrics")); Assert.assertEquals(ImmutableMap.of("type", "none"), objectMap.get("shardSpec")); Assert.assertEquals(IndexIO.CURRENT_VERSION_ID, objectMap.get("binaryVersion")); Assert.assertEquals(1, objectMap.get("size")); DataSegment deserializedSegment = mapper.readValue(mapper.writeValueAsString(segment), DataSegment.class); Assert.assertEquals(segment.getDataSource(), deserializedSegment.getDataSource()); Assert.assertEquals(segment.getInterval(), deserializedSegment.getInterval()); Assert.assertEquals(segment.getVersion(), deserializedSegment.getVersion()); Assert.assertEquals(segment.getLoadSpec(), deserializedSegment.getLoadSpec()); Assert.assertEquals(segment.getDimensions(), deserializedSegment.getDimensions()); Assert.assertEquals(segment.getMetrics(), deserializedSegment.getMetrics()); Assert.assertEquals(segment.getShardSpec(), deserializedSegment.getShardSpec()); Assert.assertEquals(segment.getSize(), deserializedSegment.getSize()); Assert.assertEquals(segment.getIdentifier(), deserializedSegment.getIdentifier()); deserializedSegment = mapper.readValue(mapper.writeValueAsString(segment), DataSegment.class); Assert.assertEquals(0, segment.compareTo(deserializedSegment)); deserializedSegment = mapper.readValue(mapper.writeValueAsString(segment), DataSegment.class); Assert.assertEquals(0, deserializedSegment.compareTo(segment)); deserializedSegment = mapper.readValue(mapper.writeValueAsString(segment), DataSegment.class); Assert.assertEquals(segment.hashCode(), deserializedSegment.hashCode()); }
// [JACKSON-684] public void testAsIndex() throws Exception { // By default, serialize using name ObjectMapper m = new ObjectMapper(); assertFalse(m.isEnabled(SerializationFeature.WRITE_ENUMS_USING_INDEX)); assertEquals(quote("B"), m.writeValueAsString(TestEnum.B)); // but we can change (dynamically, too!) it to be number-based m.enable(SerializationFeature.WRITE_ENUMS_USING_INDEX); assertEquals("1", m.writeValueAsString(TestEnum.B)); }
@Test public void testVoteSuccess() { Vote correctVote = new Vote(); correctVote.setRestaurantId(Long.MIN_VALUE); Restaurant restaurant = new Restaurant(); restaurant.setRestaurantId(Long.MIN_VALUE); when(restaurantRepository.findOne(Long.MIN_VALUE)).thenReturn(restaurant); when(votingRepository.findByUser("admin")).thenReturn(null); try { MvcResult successVoteRes = mockMvc .perform( post("/vote") .contentType(MediaType.APPLICATION_JSON) .content(mapper.writeValueAsString(correctVote))) .andExpect(status().isOk()) .andReturn(); String outdatedVoteResString = successVoteRes.getResponse().getContentAsString(); assertTrue(outdatedVoteResString.contains(Status.SUCCESS.getStatusValue())); } catch (Exception e) { fail(); } LocalTime currentTime = LocalTime.now(); if (currentTime.isBefore(RestaurantController.DEADLINE)) { Restaurant votingRestaurant = new Restaurant(); votingRestaurant.setRestaurantId(Long.MAX_VALUE); Voting identicalVoting = new Voting(); identicalVoting.setRestaurant(votingRestaurant); when(votingRepository.findByUser("admin")).thenReturn(identicalVoting); try { MvcResult actualVoteRes = mockMvc .perform( post("/vote") .contentType(MediaType.APPLICATION_JSON) .content(mapper.writeValueAsString(correctVote))) .andExpect(status().isOk()) .andReturn(); String outdatedVoteResString = actualVoteRes.getResponse().getContentAsString(); assertTrue(outdatedVoteResString.contains(Status.SUCCESS.getStatusValue())); } catch (Exception e) { fail(); } } }
@Test public void updateTask() throws Exception { // update existing task Task t = new Task(); Long id = PermanentUserData.tasks.get(0).getId(); t.setName("updated"); t.setRole(new Role(PermanentUserData.tasks.get(0).getRole().getId())); given() .contentType("application/json") .filter(sessionFilter) .body(om.writeValueAsString(t)) .put("/web/" + id.toString()) .then() .statusCode(204); // delete it given() .header(PermanentUserData.tokenHeader) .delete("/m/" + PermanentUserData.tasks.get(0).getId()) .then() .statusCode(204); // test if is recreated with correct values t.setNote("note"); LocalTime moment = LocalTime.now(); int minutes = moment.getMinute(); int hours = moment.getHour(); t.setTime(moment); given() .contentType("application/json") .header(PermanentUserData.tokenHeader) .body(om.writeValueAsString(t)) .put("/m/" + id.toString()) .then() .statusCode(204); try (Connection conn = ds.getConnection(); PreparedStatement ps = conn.prepareStatement("select * from task where name = ?"); ) { ps.setString(1, "updated"); try (ResultSet rs = ps.executeQuery(); ) { rs.next(); assertThat(rs.getString("name"), equalTo("updated")); assertThat(rs.getString("note"), equalTo("note")); assertThat(rs.getTime("time").getMinutes(), equalTo(minutes)); assertThat(rs.getTime("time").getHours(), equalTo(hours)); // rest was set to default assertThat(rs.getBoolean("finished"), equalTo(false)); assertThat(rs.getBoolean("important"), equalTo(false)); assertThat(rs.getBoolean("finished"), equalTo(false)); assertThat(rs.getDate("date"), equalTo(null)); assertThat(rs.getDate("firstDate"), equalTo(null)); } } }
@Test public void serializesToXML() throws IOException { final Airlines airlines = new Airlines(); airlines.getAirlines().add("All Nippon Airways"); airlines.getAirlines().add("Cebu Pacific"); final String expected = MAPPER.writeValueAsString( MAPPER.readValue(FixtureHelpers.fixture("fixtures/airlines.xml"), Airlines.class)); Assert.assertEquals(MAPPER.writeValueAsString(airlines), expected); }
private Map<String, String> details(Check check, List<Alert> alerts) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false); mapper.setPropertyNamingStrategy(new PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy()); return ImmutableMap.<String, String>builder() .put("CHECK", mapper.writeValueAsString(check)) .put("STATE", check.getState().name()) .put("ALERTS", mapper.writeValueAsString(alerts)) .put("SEYREN_URL", seyrenConfig.getBaseUrl()) .build(); }
public static void main(String[] args) throws Exception { keycloak = new KeycloakInstalled(); br = new BufferedReader(new InputStreamReader(System.in)); printHelp(); printDivider(); System.out.print("$ "); for (String s = br.readLine(); s != null; s = br.readLine()) { printDivider(); try { if (s.equals("login")) { keycloak.login(System.out, br); System.out.println("Logged in: " + keycloak.getToken().getSubject()); } else if (s.equals("logout")) { keycloak.logout(); System.out.println("Logged out"); } else if (s.equals("login-desktop")) { keycloak.loginDesktop(); System.out.println("Logged in: " + keycloak.getToken().getSubject()); } else if (s.equals("login-manual")) { keycloak.loginManual(System.out, br); System.out.println("Logged in: " + keycloak.getToken().getSubject()); } else if (s.equals("profile")) { profile(); } else if (s.equals("customers")) { customers(); } else if (s.equals("token")) { System.out.println(mapper.writeValueAsString(keycloak.getToken())); } else if (s.equals("id-token")) { System.out.println(mapper.writeValueAsString(keycloak.getIdToken())); } else if (s.equals("refresh")) { keycloak.refreshToken(); System.out.println( "Token refreshed: expires at " + Time.toDate(keycloak.getToken().getExpiration())); } else if (s.equals("exit")) { System.exit(0); } else { printHelp(); } } catch (ServerRequest.HttpFailure t) { System.out.println(t.getError()); } catch (Throwable t) { System.out.println(t.getMessage() != null ? t.getMessage() : t.getClass().toString()); } printDivider(); System.out.print("$ "); } }
/** * Performs roundtrip test for the specified class. * * @param <TClass> Item class * @param item Item to be checked * @param asclass Class to be used during conversions * @return Deserialized object after the roundtrip * @throws IOException JSON Conversion error * @throws AssertionError Validation error */ public static <TClass> TClass testRoundTrip(TClass item, Class<TClass> asclass) throws IOException, AssertionError { ObjectMapper mapper = new ObjectMapper(); String serialized1 = mapper.writeValueAsString(item); JsonNode json1 = mapper.readTree(serialized1); TClass deserialized1 = mapper.readValue(serialized1, asclass); String serialized2 = mapper.writeValueAsString(deserialized1); JsonNode json2 = mapper.readTree(serialized2); TClass deserialized2 = mapper.readValue(serialized2, asclass); assertEquals(json2, json1, "JSONs must be equal after the second roundtrip"); return deserialized2; }
@Test public void should_serialize_to_JSON() throws Exception { // given final Restaurant representation = new Restaurant("MacDo"); final String expected = MAPPER.writeValueAsString( MAPPER.readValue(fixture("fixtures/valid_restaurant.json"), Restaurant.class)); // when String serializedRepresentation = MAPPER.writeValueAsString(representation); // then assertThat(serializedRepresentation).isEqualTo(expected); }
@Test public void testVoteError() { try { Vote wrongVote = new Vote(); wrongVote.setRestaurantId(Long.MAX_VALUE); when(restaurantRepository.findOne(Long.MAX_VALUE)).thenReturn(null); MvcResult wrongIdVoteRes = mockMvc .perform( post("/vote") .contentType(MediaType.APPLICATION_JSON) .content(mapper.writeValueAsString(wrongVote))) .andExpect(status().isOk()) .andReturn(); String wrongIdVoteResponseString = wrongIdVoteRes.getResponse().getContentAsString(); assertTrue(wrongIdVoteResponseString.contains(Status.FAILED.getStatusValue())); assertTrue(wrongIdVoteResponseString.contains(RestaurantController.WRONG_RESTAURANT_MSG)); LocalTime currentTime = LocalTime.now(); if (currentTime.isAfter(RestaurantController.DEADLINE)) { Vote correctVote = new Vote(); correctVote.setRestaurantId(Long.MIN_VALUE); Restaurant restaurant = new Restaurant(); restaurant.setRestaurantId(Long.MIN_VALUE); when(restaurantRepository.findOne(Long.MIN_VALUE)).thenReturn(restaurant); Restaurant votingRestaurant = new Restaurant(); votingRestaurant.setRestaurantId(Long.MAX_VALUE); Voting outdatedVoting = new Voting(); outdatedVoting.setRestaurant(votingRestaurant); when(votingRepository.findByUser("admin")).thenReturn(outdatedVoting); MvcResult outdatedVoteRes = mockMvc .perform( post("/vote") .contentType(MediaType.APPLICATION_JSON) .content(mapper.writeValueAsString(correctVote))) .andExpect(status().isOk()) .andReturn(); String outdatedVoteResString = outdatedVoteRes.getResponse().getContentAsString(); assertTrue(outdatedVoteResString.contains(Status.FAILED.getStatusValue())); } } catch (Exception e) { fail(); } }
private void print(Collection<TopologyUsage> usages) { try { ObjectMapper om = new ObjectMapper(); LOG.info(">>>" + om.writeValueAsString(usages)); } catch (Exception e) { } }
private static String toJSON(ObjectMapper mapper, Object object) { try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalArgumentException("Cannot marshal to JSON: " + object, e); } }
/** * <br> * <b>功能:</b>输出JSON<br> * <b>作者:</b>肖财高<br> * <b>日期:</b> 2013-4-24 <br> * * @param response * @param type 0=成功 其他=失败 * @param msg */ public void toJsonMsg(HttpServletResponse response, int type, String msg) { Map<String, Object> map = new HashMap<String, Object>(); ObjectMapper mapper = new ObjectMapper(); map.put("state", type); if (type == 0) { map.put("success", true); if (msg == null) { map.put("msg", "成功"); } else { map.put("msg", msg); } } else { map.put("success", false); if (msg == null) { map.put("msg", "失败"); } else { map.put("msg", msg); } } try { this.toJsonPrint(response, mapper.writeValueAsString(map)); } catch (JsonProcessingException e) { e.printStackTrace(); } }
/** * Creates CkanDataset on the server * * @param dataset data set with a given parameters * @return the newly created dataset * @throws JackanException */ public synchronized CkanDataset createDataset(CkanDataset dataset) { logger.warning("TODO 0.4 CREATION OF FULL DATASETS IS EXPERIMENTAL!"); checkNotNull(dataset); if (ckanToken == null) { throw new JackanException( "Tried to create dataset" + dataset.getName() + ", but ckan token was not set!"); } ObjectMapper objectMapper = CkanClient.getObjectMapper(); String json = null; try { json = objectMapper.writeValueAsString(dataset); } catch (IOException e) { throw new JackanException("Couldn't serialize the provided CkanDatasetMinimized!", this, e); } DatasetResponse datasetresponse = postHttp( DatasetResponse.class, "/api/3/action/package_create", json, ContentType.APPLICATION_JSON); return datasetresponse.result; }
@Transactional @Rollback(true) @Test public void testUpdateWidgetInstance() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException, IOException { ObjectMapper objectMapper = new ObjectMapper(); DefaultWidgetInstance defaultWidgetInstance = prepareData(objectMapper); Map<String, String> responsMap = uIService.createOrUpdateWidgetInstance(defaultWidgetInstance); Assert.isTrue( responsMap.get("widgetInstanceAction").equals("update"), "The response action should have been 'updated'"); Canvas retrievedPerishableCanvas = uIService.getCanvasByName("Perishable Goods Canvas"); List<DefaultWidgetInstance> retrievedDefaultWidgetInstances = retrievedPerishableCanvas.getWidgetInstanceList(); DefaultWidgetInstance retrievedRefaultWidgetInstance = retrievedDefaultWidgetInstances.get(0); Assert.isTrue( objectMapper .writeValueAsString(actualViewConfig) .equals(retrievedRefaultWidgetInstance.getActualViewConfig())); }
private void writeToPubsub( Time batchTime, int partitionId, Iterator<AggregateResult> aggregateResultIterator) throws IOException { String timestamp = ISODateTimeFormat.dateTime().print(batchTime.milliseconds()); String batchId = getFormatterPrefix().print(batchTime.milliseconds()) + batchTime.milliseconds() + "-" + partitionId; TreeMap<String, Object> batchMap = new TreeMap<>(); batchMap.put("batch_id", batchId); List<Map<String, Object>> batches = new LinkedList<>(); while (aggregateResultIterator.hasNext()) { AggregateResult aggrResult = aggregateResultIterator.next(); TreeMap<String, Object> map = new TreeMap<>(); map.putAll(aggrResult.getDimensions()); map.putAll(aggrResult.getMetrics()); map.put(WINDOW_TIMESTAMP_KEY, timestamp); batches.add(map); } if (batches.isEmpty()) return; batchMap.put("aggregated_result", batches); pubsubManager.writeAggregatedOutput(topic, objectMapper.writeValueAsString(batchMap)); }
protected <T, I> T handleCreate(I resource, Class<T> outputType) throws ExecutionException, InterruptedException, KubernetesClientException, IOException { RequestBody body = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(resource)); Request.Builder requestBuilder = new Request.Builder().post(body).url(getNamespacedUrl(checkNamespace(resource))); return handleResponse(requestBuilder, 201, outputType); }
@Test public void testMoveTaskSerde() throws Exception { final MoveTask task = new MoveTask( null, "foo", new Interval("2010-01-01/P1D"), ImmutableMap.<String, Object>of("bucket", "hey", "baseKey", "what"), null, null); final String json = jsonMapper.writeValueAsString(task); Thread.sleep(100); // Just want to run the clock a bit to make sure the task id doesn't change final MoveTask task2 = (MoveTask) jsonMapper.readValue(json, Task.class); Assert.assertEquals("foo", task.getDataSource()); Assert.assertEquals(new Interval("2010-01-01/P1D"), task.getInterval()); Assert.assertEquals( ImmutableMap.<String, Object>of("bucket", "hey", "baseKey", "what"), task.getTargetLoadSpec()); Assert.assertEquals(task.getId(), task2.getId()); Assert.assertEquals(task.getGroupId(), task2.getGroupId()); Assert.assertEquals(task.getDataSource(), task2.getDataSource()); Assert.assertEquals(task.getInterval(), task2.getInterval()); Assert.assertEquals(task.getTargetLoadSpec(), task2.getTargetLoadSpec()); }
public static String escapeJsonString(String original) { try { return objectMapper.writeValueAsString(original); } catch (JsonProcessingException e) { return original; } }
@Test public void testVersionConverterSubTaskSerde() throws Exception { final ConvertSegmentTask.SubTask task = new ConvertSegmentTask.SubTask( "myGroupId", DataSegment.builder() .dataSource("foo") .interval(new Interval("2010-01-01/P1D")) .version("1234") .build(), indexSpec, false, true, null); final String json = jsonMapper.writeValueAsString(task); Thread.sleep(100); // Just want to run the clock a bit to make sure the task id doesn't change final ConvertSegmentTask.SubTask task2 = (ConvertSegmentTask.SubTask) jsonMapper.readValue(json, Task.class); Assert.assertEquals("foo", task.getDataSource()); Assert.assertEquals("myGroupId", task.getGroupId()); Assert.assertEquals(task.getId(), task2.getId()); Assert.assertEquals(task.getGroupId(), task2.getGroupId()); Assert.assertEquals(task.getDataSource(), task2.getDataSource()); Assert.assertEquals(task.getSegment(), task2.getSegment()); }
@Test public void testVoteNone() { Vote correctVote = new Vote(); correctVote.setRestaurantId(Long.MIN_VALUE); Restaurant restaurant = new Restaurant(); restaurant.setRestaurantId(Long.MIN_VALUE); when(restaurantRepository.findOne(Long.MIN_VALUE)).thenReturn(restaurant); Restaurant votingRestaurant = new Restaurant(); votingRestaurant.setRestaurantId(Long.MIN_VALUE); Voting identicalVoting = new Voting(); identicalVoting.setRestaurant(votingRestaurant); when(votingRepository.findByUser("admin")).thenReturn(identicalVoting); try { MvcResult outdatedVoteRes = mockMvc .perform( post("/vote") .contentType(MediaType.APPLICATION_JSON) .content(mapper.writeValueAsString(correctVote))) .andExpect(status().isOk()) .andReturn(); String outdatedVoteResString = outdatedVoteRes.getResponse().getContentAsString(); assertTrue(outdatedVoteResString.contains(Status.IGNORED.getStatusValue())); } catch (Exception e) { fail(); } }
@RequestMapping(value = "/contacts/email/{email}", method = GET) public String getContactByEmail(@PathVariable String email) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); mapper.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true); ContactDto contact = contactService.getByEmail(email); return mapper.writeValueAsString(contact); }
/** Add CRS (assumed to be EPSG:4326) to a GeoJSON string if it doesn't already exist */ public static String addCrsToGeoJSON(String geoJson) throws BaleenException { if (Strings.isNullOrEmpty(geoJson)) { return geoJson; } try { Map<String, Object> geoJsonObj = MAPPER.readValue(geoJson, MAP_LIKE_TYPE); if (geoJsonObj.get("crs") == null) { Map<String, Object> crs = new HashMap<>(); crs.put("type", "name"); Map<String, Object> srid = new HashMap<>(); srid.put("name", "EPSG:4326"); crs.put("properties", srid); geoJsonObj.put("crs", crs); return MAPPER.writeValueAsString(geoJsonObj); } else { return geoJson; } } catch (Exception e) { throw new BaleenException("Unable to parse GeoJSON", e); } }
/** * Sends a message envelope on this socket * * @param envelope The message envelope * @return This socket instance * @throws IOException Thrown if the message cannot be sent */ public Socket push(final Envelope envelope) throws IOException { LOG.log(Level.FINE, "Pushing envelope: {0}", envelope); final ObjectNode node = objectMapper.createObjectNode(); node.put("topic", envelope.getTopic()); node.put("event", envelope.getEvent()); node.put("ref", envelope.getRef()); node.set( "payload", envelope.getPayload() == null ? objectMapper.createObjectNode() : envelope.getPayload()); final String json = objectMapper.writeValueAsString(node); LOG.log(Level.FINE, "Sending JSON: {0}", json); RequestBody body = RequestBody.create(WebSocket.TEXT, json); if (this.isConnected()) { try { webSocket.sendMessage(body); } catch (IllegalStateException e) { LOG.log(Level.SEVERE, "Attempted to send push when socket is not open", e); } } else { this.sendBuffer.add(body); } return this; }