protected static String generateMappingJson(List<String> columns, List<Table> tableList) {

    Map<String, MappingObj> srcMappingObjs = new LinkedHashMap<>();
    columns.forEach(
        col -> {
          MappingObj mappingObj = new MappingObj();
          mappingObj.setFieldName(col);
          mappingObj.setDataType("String");
          srcMappingObjs.put(col, mappingObj);
        });

    Map<String, MappingObj> standardMappingObjs = new LinkedHashMap<>();
    tableList.forEach(
        table -> {
          String fieldNameInClass =
              DomainGenerator.toCamelCase(table.getLongName().replace(" ", ""));
          String dataType = DomainGenerator.getDataType(table.getDataType());

          MappingObj mappingObj = new MappingObj();
          mappingObj.setFieldName(fieldNameInClass);
          mappingObj.setDataType(dataType);

          standardMappingObjs.put(table.getLongName().replace(" ", ""), mappingObj);
        });

    List<MappingItem> mappingItemList = new ArrayList<>();

    srcMappingObjs.forEach(
        (key, srcMappingObj) -> {
          MappingObj standardMappingObj =
              standardMappingObjs.get(srcMappingObj.getFieldName().replace("_", ""));

          String standardFieldName = null, standardDataType = null;
          if (standardMappingObj != null) {
            standardFieldName = standardMappingObj.getFieldName();
            standardDataType = standardMappingObj.getDataType();
          }

          MappingItem mappingItem = new MappingItem();
          mappingItem.setSrcFieldName(srcMappingObj.getFieldName());
          mappingItem.setSrcDataType(srcMappingObj.getDataType());
          mappingItem.setStandardFieldName(standardFieldName);
          mappingItem.setStandardDataType(standardDataType);

          mappingItemList.add(mappingItem);
        });

    Mapping mapping = new Mapping();
    mapping.setMapping(mappingItemList);

    ObjectMapper objectMapper = new ObjectMapper();

    String jsonResult;
    try {
      jsonResult = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(mapping);
    } catch (JsonProcessingException e) {
      throw new RuntimeException(e);
    }

    return jsonResult;
  }
 public static void createDoctorListByAdmin() throws JsonProcessingException {
   // speciality.setId(2);
   // doctor.setSpeciality(speciality);
   ObjectMapper mapper = new ObjectMapper();
   RestTemplate restTemplate = new RestTemplate();
   HttpHeaders headers = new HttpHeaders();
   headers.set("auth-token", StaticStrings.ADMIN_AUTH_TOKEN);
   List<Integer> ids = new ArrayList<>();
   ids.add(17);
   ids.add(18);
   doctor.setInstitutionIds(ids);
   doctor2.setInstitutionIds(ids);
   List<Doctor> list = new ArrayList<>();
   list.add(doctor);
   list.add(doctor2);
   HttpEntity entity = new HttpEntity(list, headers);
   // System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(entity.getBody()));
   HttpEntity<Response> response =
       restTemplate.exchange(
           StaticStrings.CREATE_DOCTOR_LIST_URI, HttpMethod.POST, entity, Response.class);
   mapper = new ObjectMapper();
   System.out.println(
       mapper.writerWithDefaultPrettyPrinter().writeValueAsString(entity.getBody()));
   System.out.println(
       mapper.writerWithDefaultPrettyPrinter().writeValueAsString(response.getBody()));
 }
  @Override
  public void notify(DelegateExecution execution) throws Exception {

    HistoryService historyService = execution.getProcessEngineServices().getHistoryService();

    HistoricDecisionInstance historicDecisionInstance =
        historyService
            .createHistoricDecisionInstanceQuery()
            .includeInputs()
            .includeOutputs()
            .decisionDefinitionKey((String) execution.getVariableLocal("tableName"))
            .processInstanceId(execution.getProcessInstanceId())
            .singleResult();

    // Fill a new object with stuff...
    FraudScoreTableObject fraudData = new FraudScoreTableObject();

    fraudData.setFraudInstanceID(historicDecisionInstance.getId());

    List<HistoricDecisionInputInstance> inputs = historicDecisionInstance.getInputs();
    for (HistoricDecisionInputInstance historicDecisionInputInstance : inputs) {
      String inputName = historicDecisionInputInstance.getTypeName();
      if (inputName.equals("paymentRejected")) {
        fraudData.setPaymentRejected((Boolean) historicDecisionInputInstance.getValue());
      } else if (inputName.equals("numberOfPayouts")) {
        fraudData.setNumberOfPayouts((Integer) historicDecisionInputInstance.getValue());
      } else if (inputName.equals("historyOfFraud")) {
        fraudData.setHistoryOfFraud((Boolean) historicDecisionInputInstance.getValue());
      } else if (inputName.equals("claimAmount")) {
        fraudData.setCalimAmount((Long) historicDecisionInputInstance.getValue());
      }
    }
    List<HistoricDecisionOutputInstance> outputs = historicDecisionInstance.getOutputs();
    for (HistoricDecisionOutputInstance historicDecisionOutputInstance : outputs) {

      String inputName = historicDecisionOutputInstance.getTypeName();
      if (inputName.equals("frausScore")) {
        fraudData.setFraudScore((Integer) historicDecisionOutputInstance.getValue());
      }
    }

    ObjectMapper mapper = new ObjectMapper();

    String serializedHistoricDecisionInstance =
        mapper.writerWithDefaultPrettyPrinter().writeValueAsString(fraudData);

    Client client =
        TransportClient.builder()
            .build()
            .addTransportAddress(
                new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));

    IndexResponse response =
        client
            .prepareIndex("camunda", "fraudData", historicDecisionInstance.getId())
            .setSource(serializedHistoricDecisionInstance)
            .get();

    LOGGER.info(response.getId());
  }
  @Test
  public void serializeHandlesException() throws IOException {
    // given
    thrown.expect(RuntimeException.class);
    thrown.expectMessage(
        "Exception while serializing verification to JSON with value {"
            + System.getProperty("line.separator")
            + "  \"httpRequest\" : { },"
            + System.getProperty("line.separator")
            + "  \"times\" : {"
            + System.getProperty("line.separator")
            + "    \"count\" : 1,"
            + System.getProperty("line.separator")
            + "    \"exact\" : false"
            + System.getProperty("line.separator")
            + "  }"
            + System.getProperty("line.separator")
            + "}");
    // and
    when(objectMapper.writerWithDefaultPrettyPrinter()).thenReturn(objectWriter);
    when(objectWriter.writeValueAsString(any(VerificationDTO.class)))
        .thenThrow(new RuntimeException("TEST EXCEPTION"));

    // when
    verificationSerializer.serialize(new Verification());
  }
 public String parseData(JsonNode node, String f)
     throws JsonProcessingException, IOException, JSONException {
   System.out.println("---");
   ObjectNode json = factory.objectNode();
   type.push(f);
   Iterator<String> fieldNames = node.fieldNames();
   String uri = type.toString().replaceAll(", ", ".").replaceAll("[\\[\\]]", "");
   json.put("type_uri", uri);
   ObjectNode object = factory.objectNode();
   while (fieldNames.hasNext()) {
     String fieldName = fieldNames.next();
     JsonNode fieldValue = node.get(fieldName);
     // if (node.findParent("description").get("description") != null)
     // json.set("value", node.findParent("description").get("description"));
     if (fieldValue.isObject()) {
       ObjectNode assoc = factory.objectNode();
       assoc.set(uri + "." + parseData(fieldValue, fieldName).replaceAll("\n", ""), fieldValue);
       json.set("composite", assoc);
     } else {
       json.set(fieldName, fieldValue);
     }
   }
   // json.append("}");
   System.out.println("xxx");
   System.out.println(m.writerWithDefaultPrettyPrinter().writeValueAsString(json));
   TopicModel t = new TopicModel(new JSONObject(json.toString()));
   System.err.println(t.getUri());
   System.err.println(t.getChildTopicsModel());
   return type.pop();
 }
  public static String jsonPrettyPrinter(String json) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    Object obj = mapper.readValue(json, Object.class);
    String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);

    return indented;
  }
Beispiel #7
0
public enum Jackson {
  ;
  private static final ObjectMapper objectMapper = new ObjectMapper();

  static {
    objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  };

  private static final ObjectWriter writer = objectMapper.writer();
  private static final ObjectWriter prettyWriter = objectMapper.writerWithDefaultPrettyPrinter();

  public static String toJsonPrettyString(Object value) {
    try {
      return prettyWriter.writeValueAsString(value);
    } catch (Exception e) {
      throw new IllegalStateException(e);
    }
  }

  public static String toJsonString(Object value) {
    try {
      return writer.writeValueAsString(value);
    } catch (Exception e) {
      throw new IllegalStateException(e);
    }
  }

  public static <T> T fromJsonString(String json, Class<T> clazz) {
    try {
      return objectMapper.readValue(json, clazz);
    } catch (Exception e) {
      throw new IllegalArgumentException(e);
    }
  }

  public static <T> T loadFrom(File file, Class<T> clazz) throws IOException {
    try {
      return objectMapper.readValue(file, clazz);
    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      throw new IllegalStateException(e);
    }
  }

  public static ObjectMapper getObjectMapper() {
    return objectMapper;
  }

  public static ObjectWriter getWriter() {
    return writer;
  }

  public static ObjectWriter getPrettywriter() {
    return prettyWriter;
  }
}
  public void jsonWrite() throws Exception {

    Album album = Album.getSimpleAlbum();

    File file = FileAccessor.getFile("jackson_album.json");
    ObjectMapper jsonMapper = new ObjectMapper();
    jsonMapper.writerWithDefaultPrettyPrinter().writeValue(file, album);

    System.out.printf("Serialization to %s done.\n", file.getPath());
  }
Beispiel #9
0
 public void onCompleteResponse(FullHttpRequest request, FullHttpResponse response) {
   try {
     ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
     Session targetSession =
         Session.newSession(
             MessageFactory.createRequest(request), MessageFactory.createResponse(response));
     writer.writeValue(this.file, prepareTargetSessions(targetSession));
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
 public String toString() {
   ObjectMapper mapper = new ObjectMapper();
   mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
   String jsonInString;
   try {
     jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(this);
     return jsonInString;
   } catch (JsonProcessingException e) {
     // TODO Auto-generated catch block
     return null;
   }
 }
  @Test
  public void serialize() throws IOException {
    // given
    when(objectMapper.writerWithDefaultPrettyPrinter()).thenReturn(objectWriter);

    // when
    verificationSerializer.serialize(fullVerification);

    // then
    verify(objectMapper).writerWithDefaultPrettyPrinter();
    verify(objectWriter).writeValueAsString(fullVerificationDTO);
  }
 public void testAtomicRefViaDefaultTyping() throws Exception {
   ObjectMapper mapper = new ObjectMapper();
   mapper.enableDefaultTyping(DefaultTyping.NON_FINAL);
   AtomicStringWrapper data = new AtomicStringWrapper("foo");
   String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(data);
   AtomicStringWrapper result = mapper.readValue(json, AtomicStringWrapper.class);
   assertNotNull(result);
   assertNotNull(result.wrapper);
   assertEquals(AtomicReference.class, result.wrapper.getClass());
   StringWrapper w = result.wrapper.get();
   assertEquals("foo", w.str);
 }
 public static void printJsonFromFile(final String fileName) {
   System.out.println("-----------------");
   final ObjectMapper mapper = new ObjectMapper();
   try {
     final Object json =
         mapper.readValue(readFile(fileName, StandardCharsets.UTF_8), Object.class);
     System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));
   } catch (final IOException e) {
     e.printStackTrace();
   }
   System.out.println("-----------------");
 }
Beispiel #14
0
 protected String json(Object x) {
   try {
     if (this.prettyPrint) {
       return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(x);
     } else {
       return objectMapper.writeValueAsString(x);
     }
   } catch (JsonProcessingException e) {
     LOG.error("Error while generating JSON", e);
     throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
   }
 }
 public static void deleteDoctorByAdmin(int id) throws JsonProcessingException {
   RestTemplate restTemplate = new RestTemplate();
   HttpHeaders headers = new HttpHeaders();
   headers.set("auth-token", StaticStrings.ADMIN_AUTH_TOKEN);
   HttpEntity entity = new HttpEntity(headers);
   Map<String, String> params = new HashMap<>();
   params.put("id", String.valueOf(id));
   HttpEntity<Response> response =
       restTemplate.exchange(
           StaticStrings.DELETE_DOCTOR_URI, HttpMethod.DELETE, entity, Response.class, params);
   ObjectMapper mapper = new ObjectMapper();
   System.out.println(
       mapper.writerWithDefaultPrettyPrinter().writeValueAsString(response.getBody()));
 }
  // For [databind#689]
  public void testCustomDefaultPrettyPrinter() throws Exception {
    final ObjectMapper m = new ObjectMapper();
    final int[] input = new int[] {1, 2};

    // without anything else, compact:
    assertEquals("[1,2]", m.writeValueAsString(input));

    // or with default, get... defaults:
    m.enable(SerializationFeature.INDENT_OUTPUT);
    assertEquals("[ 1, 2 ]", m.writeValueAsString(input));
    assertEquals("[ 1, 2 ]", m.writerWithDefaultPrettyPrinter().writeValueAsString(input));
    assertEquals("[ 1, 2 ]", m.writer().withDefaultPrettyPrinter().writeValueAsString(input));

    // but then with our custom thingy...
    m.setDefaultPrettyPrinter(new FooPrettyPrinter());
    assertEquals("[1 , 2]", m.writeValueAsString(input));
    assertEquals("[1 , 2]", m.writerWithDefaultPrettyPrinter().writeValueAsString(input));
    assertEquals("[1 , 2]", m.writer().withDefaultPrettyPrinter().writeValueAsString(input));

    // and yet, can disable too
    assertEquals(
        "[1,2]", m.writer().without(SerializationFeature.INDENT_OUTPUT).writeValueAsString(input));
  }
 public static void getAllStatisticsByAdmin(String byField, boolean ascending)
     throws JsonProcessingException {
   RestTemplate restTemplate = new RestTemplate();
   HttpHeaders headers = new HttpHeaders();
   headers.set("auth-token", StaticStrings.ADMIN_AUTH_TOKEN);
   HttpEntity entity = new HttpEntity(headers);
   Map<String, String> params = new HashMap<>();
   params.put("byField", String.valueOf(byField));
   params.put("ascending", String.valueOf(ascending));
   HttpEntity<Response> response =
       restTemplate.exchange(
           StaticStrings.GET_ALL_STATISTICS_URI, HttpMethod.GET, entity, Response.class, params);
   ObjectMapper mapper = new ObjectMapper();
   System.out.println(
       mapper.writerWithDefaultPrettyPrinter().writeValueAsString(response.getBody()));
 }
 public static void updateDoctorByAdmin(int id) throws JsonProcessingException {
   doctor.setId(id);
   doctor.setName("Valera");
   speciality.setId(1);
   doctor.setSpeciality(speciality);
   RestTemplate restTemplate = new RestTemplate();
   HttpHeaders headers = new HttpHeaders();
   headers.set("auth-token", StaticStrings.ADMIN_AUTH_TOKEN);
   HttpEntity entity = new HttpEntity(doctor, headers);
   HttpEntity<Response> response =
       restTemplate.exchange(
           StaticStrings.UPDATE_DOCTOR_URI, HttpMethod.POST, entity, Response.class);
   ObjectMapper mapper = new ObjectMapper();
   System.out.println(
       mapper.writerWithDefaultPrettyPrinter().writeValueAsString(response.getBody()));
 }
 public static void getAllInstitutionsToDoctor(Integer doctorID) throws JsonProcessingException {
   RestTemplate restTemplate = new RestTemplate();
   HttpHeaders headers = new HttpHeaders();
   headers.set("auth-token", StaticStrings.ADMIN_AUTH_TOKEN);
   HttpEntity entity = new HttpEntity(headers);
   Map<String, String> params = new HashMap<>();
   params.put("doctorID", String.valueOf(doctorID));
   HttpEntity<Response> response =
       restTemplate.exchange(
           StaticStrings.GET_ALL_DOCTOR_INSTITUTIONS_URI,
           HttpMethod.GET,
           entity,
           Response.class,
           params);
   ObjectMapper mapper = new ObjectMapper();
   System.out.println(
       mapper.writerWithDefaultPrettyPrinter().writeValueAsString(response.getBody()));
 }
 public static void getAllDoctorsBySpecialityByAdmin(Integer specialityID)
     throws JsonProcessingException {
   RestTemplate restTemplate = new RestTemplate();
   HttpHeaders headers = new HttpHeaders();
   headers.set("auth-token", StaticStrings.ADMIN_AUTH_TOKEN);
   HttpEntity entity = new HttpEntity(headers);
   Map<String, String> params = new HashMap<>();
   params.put("specialityID", String.valueOf(specialityID));
   HttpEntity<Response> response =
       restTemplate.exchange(
           StaticStrings.GET_DOCTORS_BY_SPECIALITY_URI,
           HttpMethod.GET,
           entity,
           Response.class,
           params);
   ObjectMapper mapper = new ObjectMapper();
   System.out.println(
       mapper.writerWithDefaultPrettyPrinter().writeValueAsString(response.getBody()));
 }
  // For [#15]
  @Test
  public void testGetCustomerJson() throws Exception {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistenceUnit");

    try {
      EntityManager em = emf.createEntityManager();

      // false -> no forcing of lazy loading
      ObjectMapper mapper = mapperWithModule(false);

      Customer customer = em.find(Customer.class, 103);
      assertFalse(Hibernate.isInitialized(customer.getPayments()));
      String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(customer);
      // should not force loading...
      Set<Payment> payments = customer.getPayments();
      /*
      System.out.println("--- JSON ---");
      System.out.println(json);
      System.out.println("--- /JSON ---");
      */

      assertFalse(Hibernate.isInitialized(payments));
      // TODO: verify
      assertNotNull(json);

      Map<?, ?> stuff = mapper.readValue(json, Map.class);

      // "payments" is marked as lazily loaded AND "Include.NON_EMPTY"; should not be serialized
      if (stuff.containsKey("payments")) {
        fail(
            "Should not find serialized property 'payments'; got: "
                + stuff.get("payments")
                + " from JSON: "
                + json);
      }
      // orders, on the other hand, not:
      assertTrue(stuff.containsKey("orders"));
      assertNull(stuff.get("orderes"));

    } finally {
      emf.close();
    }
  }
Beispiel #22
0
  private void writeJsonConfig(File jsonTempFile, List<Module> modules) throws IOException {
    List<SerializablePrebuiltJarRule> libraries =
        Lists.newArrayListWithCapacity(libraryJars.size());
    for (PrebuiltJarRule libraryJar : libraryJars) {
      libraries.add(new SerializablePrebuiltJarRule(libraryJar));
    }

    Map<String, Object> config =
        ImmutableMap.<String, Object>of(
            "modules", modules,
            "libraries", libraries);

    // Write out the JSON config to be consumed by the Python.
    Writer writer = new FileWriter(jsonTempFile);
    JsonFactory jsonFactory = new JsonFactory();
    ObjectMapper objectMapper = new ObjectMapper(jsonFactory);
    if (executionContext.getVerbosity().shouldPrintOutput()) {
      ObjectWriter objectWriter = objectMapper.writerWithDefaultPrettyPrinter();
      objectWriter.writeValue(writer, config);
    } else {
      objectMapper.writeValue(writer, config);
    }
  }
Beispiel #23
0
  @POST
  @Produces({MediaType.APPLICATION_JSON, SmileMediaTypes.APPLICATION_JACKSON_SMILE})
  @Consumes({
    MediaType.APPLICATION_JSON,
    SmileMediaTypes.APPLICATION_JACKSON_SMILE,
    APPLICATION_SMILE
  })
  public Response doPost(
      InputStream in,
      @QueryParam("pretty") String pretty,
      @Context
          final HttpServletRequest req // used only to get request content-type and remote address
      ) throws IOException {
    final long start = System.currentTimeMillis();
    Query query = null;
    String queryId = null;

    final String reqContentType = req.getContentType();
    final boolean isSmile =
        SmileMediaTypes.APPLICATION_JACKSON_SMILE.equals(reqContentType)
            || APPLICATION_SMILE.equals(reqContentType);
    final String contentType =
        isSmile ? SmileMediaTypes.APPLICATION_JACKSON_SMILE : MediaType.APPLICATION_JSON;

    ObjectMapper objectMapper = isSmile ? smileMapper : jsonMapper;
    final ObjectWriter jsonWriter =
        pretty != null ? objectMapper.writerWithDefaultPrettyPrinter() : objectMapper.writer();

    final String currThreadName = Thread.currentThread().getName();
    try {
      query = objectMapper.readValue(in, Query.class);
      queryId = query.getId();
      if (queryId == null) {
        queryId = UUID.randomUUID().toString();
        query = query.withId(queryId);
      }
      if (query.getContextValue(QueryContextKeys.TIMEOUT) == null) {
        query =
            query.withOverriddenContext(
                ImmutableMap.of(
                    QueryContextKeys.TIMEOUT,
                    config.getMaxIdleTime().toStandardDuration().getMillis()));
      }

      Thread.currentThread()
          .setName(
              String.format(
                  "%s[%s_%s_%s]", currThreadName, query.getType(), query.getDataSource(), queryId));
      if (log.isDebugEnabled()) {
        log.debug("Got query [%s]", query);
      }

      final Map<String, Object> responseContext = new MapMaker().makeMap();
      final Sequence res = query.run(texasRanger, responseContext);
      final Sequence results;
      if (res == null) {
        results = Sequences.empty();
      } else {
        results = res;
      }

      final Yielder yielder =
          results.toYielder(
              null,
              new YieldingAccumulator() {
                @Override
                public Object accumulate(Object accumulated, Object in) {
                  yield();
                  return in;
                }
              });

      try {
        final Query theQuery = query;
        Response.ResponseBuilder builder =
            Response.ok(
                    new StreamingOutput() {
                      @Override
                      public void write(OutputStream outputStream)
                          throws IOException, WebApplicationException {
                        // json serializer will always close the yielder
                        CountingOutputStream os = new CountingOutputStream(outputStream);
                        jsonWriter.writeValue(os, yielder);

                        os
                            .flush(); // Some types of OutputStream suppress flush errors in the
                                      // .close() method.
                        os.close();

                        final long queryTime = System.currentTimeMillis() - start;
                        emitter.emit(
                            DruidMetrics.makeQueryTimeMetric(
                                    jsonMapper, theQuery, req.getRemoteAddr())
                                .setDimension("success", "true")
                                .build("query/time", queryTime));
                        emitter.emit(
                            DruidMetrics.makeQueryTimeMetric(
                                    jsonMapper, theQuery, req.getRemoteAddr())
                                .build("query/bytes", os.getCount()));

                        requestLogger.log(
                            new RequestLogLine(
                                new DateTime(start),
                                req.getRemoteAddr(),
                                theQuery,
                                new QueryStats(
                                    ImmutableMap.<String, Object>of(
                                        "query/time",
                                        queryTime,
                                        "query/bytes",
                                        os.getCount(),
                                        "success",
                                        true))));
                      }
                    },
                    contentType)
                .header("X-Druid-Query-Id", queryId);

        // Limit the response-context header, see https://github.com/druid-io/druid/issues/2331
        // Note that Response.ResponseBuilder.header(String key,Object value).build() calls
        // value.toString()
        // and encodes the string using ASCII, so 1 char is = 1 byte
        String responseCtxString = jsonMapper.writeValueAsString(responseContext);
        if (responseCtxString.length() > RESPONSE_CTX_HEADER_LEN_LIMIT) {
          log.warn(
              "Response Context truncated for id [%s] . Full context is [%s].",
              queryId, responseCtxString);
          responseCtxString = responseCtxString.substring(0, RESPONSE_CTX_HEADER_LEN_LIMIT);
        }

        return builder.header("X-Druid-Response-Context", responseCtxString).build();
      } catch (Exception e) {
        // make sure to close yielder if anything happened before starting to serialize the
        // response.
        yielder.close();
        throw Throwables.propagate(e);
      } finally {
        // do not close yielder here, since we do not want to close the yielder prior to
        // StreamingOutput having iterated over all the results
      }
    } catch (QueryInterruptedException e) {
      try {
        log.info("%s [%s]", e.getMessage(), queryId);
        final long queryTime = System.currentTimeMillis() - start;
        emitter.emit(
            DruidMetrics.makeQueryTimeMetric(jsonMapper, query, req.getRemoteAddr())
                .setDimension("success", "false")
                .build("query/time", queryTime));
        requestLogger.log(
            new RequestLogLine(
                new DateTime(start),
                req.getRemoteAddr(),
                query,
                new QueryStats(
                    ImmutableMap.<String, Object>of(
                        "query/time",
                        queryTime,
                        "success",
                        false,
                        "interrupted",
                        true,
                        "reason",
                        e.toString()))));
      } catch (Exception e2) {
        log.error(e2, "Unable to log query [%s]!", query);
      }
      return Response.serverError()
          .type(contentType)
          .entity(
              jsonWriter.writeValueAsBytes(
                  ImmutableMap.of(
                      "error", e.getMessage() == null ? "null exception" : e.getMessage())))
          .build();
    } catch (Exception e) {
      // Input stream has already been consumed by the json object mapper if query == null
      final String queryString = query == null ? "unparsable query" : query.toString();

      log.warn(e, "Exception occurred on request [%s]", queryString);

      try {
        final long queryTime = System.currentTimeMillis() - start;
        emitter.emit(
            DruidMetrics.makeQueryTimeMetric(jsonMapper, query, req.getRemoteAddr())
                .setDimension("success", "false")
                .build("query/time", queryTime));
        requestLogger.log(
            new RequestLogLine(
                new DateTime(start),
                req.getRemoteAddr(),
                query,
                new QueryStats(
                    ImmutableMap.<String, Object>of(
                        "query/time", queryTime, "success", false, "exception", e.toString()))));
      } catch (Exception e2) {
        log.error(e2, "Unable to log query [%s]!", queryString);
      }

      log.makeAlert(e, "Exception handling request")
          .addData("exception", e.toString())
          .addData("query", queryString)
          .addData("peer", req.getRemoteAddr())
          .emit();

      return Response.serverError()
          .type(contentType)
          .entity(
              jsonWriter.writeValueAsBytes(
                  ImmutableMap.of(
                      "error", e.getMessage() == null ? "null exception" : e.getMessage())))
          .build();
    } finally {
      Thread.currentThread().setName(currThreadName);
    }
  }
  // public String parseSchema(TreeNode node, String key) throws IOException {
  // if (node.isObject()) {
  // type.push(key);
  // Iterator<String> fields = node.fieldNames();
  // List<String> s = new ArrayList<String>();
  // while (fields.hasNext()) {
  // String field = fields.next();
  // if (node.at("/type").toString().contains("object")) {
  // // System.out.println("true");
  // key = parseSchema(node.get(field), field);
  //
  // } else {
  // // System.out.println("false");
  // // System.out.println(type.toString()+":"+field);
  // // s.add(node.a);
  // key = parseSchema(node.get(field), field);
  // }
  // }
  // types.put(type.toString(), s);
  // type.pop();
  // }
  //
  // return key;
  // }
  public String printAll(JsonNode node, String f)
      throws JsonProcessingException, IOException, JSONException {
    System.out.println("---");
    ObjectNode json = factory.objectNode();

    if (!f.equals("properties")) {
      type.push(f);
    }

    Iterator<String> fieldNames = node.fieldNames();

    Enumeration<String> e = type.elements();
    while (e.hasMoreElements()) {
      e.nextElement();
    }

    String uri =
        type.toString()
            .replaceAll(", ", ".")
            .replaceFirst(".schema.", ".community.")
            .replaceAll("[\\[\\]]", "");
    json.put("uri", uri);
    ArrayNode index_mode = factory.arrayNode();
    index_mode.add("dm4.core.fulltext");
    index_mode.add("dm4.core.fulltext_key");
    json.set("index_mode_uris", index_mode);
    json.put("data_type_uri", "dm.core.text");
    ArrayNode array = factory.arrayNode();
    while (fieldNames.hasNext()) {
      String fieldName = fieldNames.next();
      JsonNode fieldValue = node.get(fieldName);
      if (node.findParent("description").get("description") != null) {
        json.set("value", node.findParent("description").get("description"));
      }
      if (fieldValue.isObject()) {
        ObjectNode assoc = factory.objectNode();
        assoc.put(
            "child_type_uri", uri + "." + printAll(fieldValue, fieldName).replaceAll("\n", ""));
        assoc.put("child_cardinality_uri", "dm4.core.one");
        assoc.put("parent_cardinality_uri", "dm4.core.one");
        assoc.put("assoc_type_uri", "dm4.core.composition_def");
        // json.append(("composite: "+uri+"."+printAll(fieldValue, fieldName)).replaceAll("\n",
        // "")+"\n");
        array.add(assoc);
        json.put("data_type_uri", "dm4.core.composite");
        json.set("assoc_defs", array);
      } else {
        // String value = fieldValue.toString();
        if (fieldName.equals("description")) {
          json.set("value", fieldValue);
          // json.append("\"value\"" + " : " + value+",\n");
        }
        if (fieldName.equals("enum")) {
          // json.append("\"options\"" + " : " + value+",\n");
          json.set("enum", fieldValue);
        }
      }
    }
    // json.append("}");
    System.out.println("xxx");
    System.out.println(m.writerWithDefaultPrettyPrinter().writeValueAsString(json));
    TopicTypeModel t = new TopicTypeModel(new JSONObject(json.toString()));
    System.err.println(t.getUri());
    System.err.println(t.getAssocDefs());
    if (!f.equals("properties")) {
      return type.pop();
    } else {
      return "";
    }
  }