Ejemplo n.º 1
0
  public static void main(String[] args) {
    User user = new User();

    ObjectMapper mapper = new ObjectMapper();
    try {
      // compact mode
      System.out.println(mapper.writeValueAsString(user));

      // Pretty Print JSON Object
      // Older versions: defaultPrettyPrintingWriter
      System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(user));

      // Newer versions: writerWithDefaultPrettyPrinter
      System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user));

      // Pretty Print JSON String
      String test = "{\"age\":29,\"messages\":[\"msg 1\",\"msg 2\",\"msg 3\"],\"name\":\"mkyong\"}";
      System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(test));

      test = "{\"age\":29,\"messages\":[\"msg 1\",\"msg 2\",\"msg 3\"],\"name\":\"mkyong\"}";
      Object json = mapper.readValue(test, Object.class);
      System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));
    } catch (Exception e) {

    }
  }
Ejemplo n.º 2
0
 // both reads and writes - need to be synchronized for consistent data to be written
 public static void deleteWorkflowJob(String workflowJobId) throws IOException {
   String workflowJobPath =
       LoaderServerConfiguration.instance().getJobFSConfig().getWorkflowJobPath(workflowJobId);
   File file = new File(workflowJobPath);
   if (!file.exists())
     throw new RuntimeException("WorkflowJobId " + workflowJobId + " not found.");
   File statusFile =
       new File(
           LoaderServerConfiguration.instance()
               .getJobFSConfig()
               .getWorkflowJobStatusPath(workflowJobId));
   ScheduledWorkFlowJob workflow = objectMapper.readValue(statusFile, ScheduledWorkFlowJob.class);
   FileHelper.deleteRecursively(file);
   File workflowJobsFile =
       new File(
           LoaderServerConfiguration.instance()
               .getJobFSConfig()
               .getScheduledWorkflowJobsFile(workflow.getWorkflowName()));
   synchronized (ScheduledWorkFlowJob.class) {
     ArrayList<String> allWorkflowJobIds =
         objectMapper.readValue(workflowJobsFile, ArrayList.class);
     allWorkflowJobIds.remove(workflowJobId);
     objectMapper.writerWithDefaultPrettyPrinter().writeValue(workflowJobsFile, allWorkflowJobIds);
   }
 }
Ejemplo n.º 3
0
 public static String toJson(Object object) {
   try {
     return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
Ejemplo n.º 4
0
  @Test
  public void testGetLegacyPodcasts()
      throws JsonGenerationException, JsonMappingException, IOException {

    ClientConfig clientConfig = new ClientConfig();
    clientConfig.register(JacksonFeature.class);

    Client client = ClientBuilder.newClient(clientConfig);

    WebTarget webTarget =
        client.target("http://localhost:8888/demo-rest-jersey-spring/legacy/podcasts/");

    Builder request = webTarget.request();
    request.header("Content-type", MediaType.APPLICATION_JSON);

    Response response = request.get();
    Assert.assertTrue(response.getStatus() == 200);

    List<Podcast> podcasts = response.readEntity(new GenericType<List<Podcast>>() {});

    ObjectMapper mapper = new ObjectMapper();
    System.out.print(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(podcasts));

    Assert.assertTrue("At least one podcast is present in the LEGACY", podcasts.size() > 0);
  }
Ejemplo n.º 5
0
  @Get
  @Produces("application/json")
  public String represent() {

    String userID = (String) getRequestAttributes().get("id");

    User u = userService.findByID(Integer.valueOf(userID), User.class);
    System.out.println(u);

    ObjectMapper om = new ObjectMapper();

    String value = "";
    try {
      // -- ����writeWithDefaultPrettyPrinter()����������Ϊ�˸�ӵĸ�ʽ��
      value = om.writerWithDefaultPrettyPrinter().writeValueAsString(u);

    } catch (JsonGenerationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (JsonMappingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return value;
  }
Ejemplo n.º 6
0
 public void persistWorkFlowJob() throws IOException {
   File workFlowStatusFile =
       new File(configuration.getJobFSConfig().getWorkflowJobStatusPath(this.workFlowId));
   if (!workFlowStatusFile.exists())
     FileHelper.createFilePath(workFlowStatusFile.getAbsolutePath());
   objectMapper
       .writerWithDefaultPrettyPrinter()
       .writeValue(new FileOutputStream(workFlowStatusFile), this);
 }
Ejemplo n.º 7
0
 /**
  * Creates a HTTP servlet response serializing the exception in it as JSON.
  *
  * @param response the servlet response
  * @param status the error code to set in the response
  * @param ex the exception to serialize in the response
  * @throws IOException thrown if there was an error while creating the response
  */
 public static void createServletExceptionResponse(
     HttpServletResponse response, int status, Throwable ex) throws IOException {
   response.setStatus(status);
   response.setContentType(APPLICATION_JSON_MIME);
   Map<String, Object> json = new LinkedHashMap<String, Object>();
   json.put(ERROR_MESSAGE_JSON, getOneLineMessage(ex));
   json.put(ERROR_EXCEPTION_JSON, ex.getClass().getSimpleName());
   json.put(ERROR_CLASSNAME_JSON, ex.getClass().getName());
   Map<String, Object> jsonResponse = new LinkedHashMap<String, Object>();
   jsonResponse.put(ERROR_JSON, json);
   ObjectMapper jsonMapper = new ObjectMapper();
   Writer writer = response.getWriter();
   jsonMapper.writerWithDefaultPrettyPrinter().writeValue(writer, jsonResponse);
   writer.flush();
 }
Ejemplo n.º 8
0
  @Test
  public void testGetPodcast() throws JsonGenerationException, JsonMappingException, IOException {

    ClientConfig clientConfig = new ClientConfig();
    clientConfig.register(JacksonFeature.class);

    Client client = ClientBuilder.newClient(clientConfig);

    WebTarget webTarget = client.target("http://localhost:8888/demo-rest-jersey-spring/podcasts/2");

    Builder request = webTarget.request(MediaType.APPLICATION_JSON);

    Response response = request.get();
    Assert.assertTrue(response.getStatus() == 200);

    Podcast podcast = response.readEntity(Podcast.class);

    ObjectMapper mapper = new ObjectMapper();
    System.out.print(
        "Received podcast from database *************************** "
            + mapper.writerWithDefaultPrettyPrinter().writeValueAsString(podcast));
  }
Ejemplo n.º 9
0
  @Override
  protected void buildDemoApplicationImpl(AdminClient client) throws Exception {

    logger.info("Loading 'City lights controller application' data...");

    loginTenantAdmin(client);

    ApplicationDto cityLightsDemoApplication = new ApplicationDto();
    cityLightsDemoApplication.setName("City lights controller demo");
    cityLightsDemoApplication = client.editApplication(cityLightsDemoApplication);
    sdkPropertiesDto.setApplicationId(cityLightsDemoApplication.getId());
    sdkPropertiesDto.setProfileSchemaVersion(1);
    sdkPropertiesDto.setNotificationSchemaVersion(1);
    sdkPropertiesDto.setLogSchemaVersion(1);

    loginTenantDeveloper(client);

    logger.info("Creating configuration schema...");
    ConfigurationSchemaDto configurationSchema = new ConfigurationSchemaDto();
    configurationSchema.setApplicationId(cityLightsDemoApplication.getId());
    configurationSchema.setName("City lights controller schema");
    configurationSchema.setDescription(
        "Default configuration schema for the city lights controller application");
    configurationSchema =
        client.createConfigurationSchema(
            configurationSchema, getResourcePath("config_schema.avsc"));
    logger.info("Configuration schema version: {}", configurationSchema.getMajorVersion());
    sdkPropertiesDto.setConfigurationSchemaVersion(configurationSchema.getMajorVersion());
    logger.info("Configuration schema was created.");

    EndpointGroupDto baseEndpointGroup = null;
    List<EndpointGroupDto> endpointGroups =
        client.getEndpointGroups(cityLightsDemoApplication.getId());
    if (endpointGroups.size() == 1 && endpointGroups.get(0).getWeight() == 0) {
      baseEndpointGroup = endpointGroups.get(0);
    }

    if (baseEndpointGroup == null) {
      throw new RuntimeException(
          "Can't get default endpoint group for the city lights controller application!");
    }

    ConfigurationDto baseConfiguration = new ConfigurationDto();
    baseConfiguration.setApplicationId(cityLightsDemoApplication.getId());
    baseConfiguration.setEndpointGroupId(baseEndpointGroup.getId());
    baseConfiguration.setSchemaId(configurationSchema.getId());
    baseConfiguration.setMajorVersion(configurationSchema.getMajorVersion());
    baseConfiguration.setMinorVersion(configurationSchema.getMinorVersion());
    baseConfiguration.setDescription("Base city lights controller configuration");
    String body = FileUtils.readResource(getResourcePath("config_data.json"));
    logger.info("Configuration body: [{}]", body);

    ObjectMapper objectMapper = new ObjectMapper();
    Map<String, Object> configBody = objectMapper.readValue(body, Map.class);
    logger.info("Getting config body: [{}]", configBody);
    Map<String, Object> kaaClientConfig = (Map<String, Object>) configBody.get(KAA_CLIENT_CONFIG);
    logger.info("Getting kaaClientConfig: [{}]", kaaClientConfig);
    logger.info("Getting traffic lights and traffic lights app tokens...");
    List<ApplicationDto> applications = client.getApplications();
    logger.info("All available applications: [{}]", applications);
    ApplicationDto trafficLightsApplication =
        getApplicationWithName(applications, TRAFFIC_LIGHTS_APPLICATION_NAME);
    if (trafficLightsApplication == null) {
      logger.error(formErrorLogMessage(TRAFFIC_LIGHTS_APPLICATION_NAME));
      throw new RuntimeException(
          "Can't get '" + TRAFFIC_LIGHTS_APPLICATION_NAME + "' application!");
    }
    logger.info(
        TRAFFIC_LIGHTS_APPLICATION_NAME + " application was found: {}", trafficLightsApplication);
    ApplicationDto streetLightApplication =
        getApplicationWithName(applications, STREET_LIGHT_APPLICATION_NAME);
    if (streetLightApplication == null) {
      logger.error(formErrorLogMessage(STREET_LIGHT_APPLICATION_NAME));
      throw new RuntimeException("Can't get '" + STREET_LIGHT_APPLICATION_NAME + "' application!");
    }
    logger.info(
        STREET_LIGHT_APPLICATION_NAME + " application was found: {}", streetLightApplication);
    kaaClientConfig.put(
        TRAFFIC_LIGHTS_APP_TOKEN_PROPERTY, trafficLightsApplication.getApplicationToken());
    kaaClientConfig.put(
        STREET_LIGHT_APP_TOKEN_PROPERTY, streetLightApplication.getApplicationToken());
    body = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(configBody);
    logger.info("Configuration body after altering: [{}]", body);
    baseConfiguration.setBody(body);
    baseConfiguration.setStatus(UpdateStatus.INACTIVE);
    logger.info("Editing the configuration...");
    baseConfiguration = client.editConfiguration(baseConfiguration);
    logger.info("Configuration was successfully edited");
    logger.info("Activating the configuration");
    client.activateConfiguration(baseConfiguration.getId());
    logger.info("Configuration was activated");

    logger.info("Finished loading 'City lights controller application' data...");
  }