Example #1
0
  public static void writeFile(List<BasicDBObject> result, String type) throws IOException {
    File file = new File("C:\\data\\" + type + ".json");

    BufferedWriter writer = new BufferedWriter(new FileWriter(file));

    ObjectMapper mapper = new ObjectMapper();
    ObjectWriter writer2 = mapper.defaultPrettyPrintingWriter();

    for (BasicDBObject object : result) {
      writer.write(mapper.defaultPrettyPrintingWriter().writeValueAsString(object) + ",");
      System.out.println(object.toString());
    }
    writer.flush();
    writer.close();
  }
Example #2
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) {

    }
  }
Example #3
0
  private QueryWorkUnit getQueryWorkUnit(final PhysicalPlan plan) throws ExecutionSetupException {
    final PhysicalOperator rootOperator = plan.getSortedOperators(false).iterator().next();
    final Fragment rootFragment = rootOperator.accept(MakeFragmentsVisitor.INSTANCE, null);
    final SimpleParallelizer parallelizer = new SimpleParallelizer(queryContext);
    final QueryWorkUnit queryWorkUnit =
        parallelizer.getFragments(
            queryContext.getOptions().getOptionList(),
            queryContext.getCurrentEndpoint(),
            queryId,
            queryContext.getActiveEndpoints(),
            drillbitContext.getPlanReader(),
            rootFragment,
            initiatingClient.getSession(),
            queryContext.getQueryContextInfo());

    if (logger.isTraceEnabled()) {
      final StringBuilder sb = new StringBuilder();
      sb.append("PlanFragments for query ");
      sb.append(queryId);
      sb.append('\n');

      final List<PlanFragment> planFragments = queryWorkUnit.getFragments();
      final int fragmentCount = planFragments.size();
      int fragmentIndex = 0;
      for (final PlanFragment planFragment : planFragments) {
        final FragmentHandle fragmentHandle = planFragment.getHandle();
        sb.append("PlanFragment(");
        sb.append(++fragmentIndex);
        sb.append('/');
        sb.append(fragmentCount);
        sb.append(") major_fragment_id ");
        sb.append(fragmentHandle.getMajorFragmentId());
        sb.append(" minor_fragment_id ");
        sb.append(fragmentHandle.getMinorFragmentId());
        sb.append('\n');

        final DrillbitEndpoint endpointAssignment = planFragment.getAssignment();
        sb.append("  DrillbitEndpoint address ");
        sb.append(endpointAssignment.getAddress());
        sb.append('\n');

        String jsonString = "<<malformed JSON>>";
        sb.append("  fragment_json: ");
        final ObjectMapper objectMapper = new ObjectMapper();
        try {
          final Object json = objectMapper.readValue(planFragment.getFragmentJson(), Object.class);
          jsonString = objectMapper.defaultPrettyPrintingWriter().writeValueAsString(json);
        } catch (final Exception e) {
          // we've already set jsonString to a fallback value
        }
        sb.append(jsonString);

        logger.trace(sb.toString());
      }
    }

    return queryWorkUnit;
  }
Example #4
0
  @RequestMapping(
      value = "/bsar/ar/arPayment",
      method = RequestMethod.POST,
      consumes = {"application/json"})
  public String arPaymentOpen(
      Model model,
      @RequestBody OtimeVO otimeVO,
      @RequestParam(required = false) String callBackFunc) {

    logger.debug("pymDiv:::::::::::" + otimeVO.toString());
    logger.debug("pymDiv:::::::::::" + callBackFunc);

    ObjectMapper om = new ObjectMapper();
    String temp = null;
    try {
      temp = om.defaultPrettyPrintingWriter().writeValueAsString(otimeVO);
    } catch (Exception e) {
      // e.printStackTrace();
    }

    model.addAttribute("recpData", temp);
    model.addAttribute("callBackFunc", callBackFunc);
    model.addAttribute("rcpmnyDt", CmnDateUtils.addDate(0));

    // cycle bill and hotbill(payment for real time) and ownership-change hotbill(before) and
    // terminate(hotbill)
    if (otimeVO.getCsEvntCd().substring(0, 2).equals("30")
        || otimeVO.getCsEvntCd().equals("206000")
        || otimeVO.getCsEvntCd().equals("203010")
        || otimeVO.getCsEvntCd().equals("207000")) {

      List<CoAuthCodeInfo> authList =
          securityService.getCurrentMember().getSpCoAuthCodeInfoAuthList();

      for (CoAuthCodeInfo coAuthCodeInfo : authList) {
        if (coAuthCodeInfo
            .getAuthName()
            .equals("PaymentBankTransfer")) { // auth_name :: 'PaymentBankTransfer'
          model.addAttribute("bnkTransferViewalbe", true); // lnkgPymLclsCd == 30 and 권한 유저
          return "dialog.bsar.ar.arPayment";
        }
      }

      model.addAttribute("bnkTransferViewalbe", false); // lnkgPymLclsCd == 30 and 비권한 유저
      return "dialog.bsar.ar.arPayment";

    } else {
      model.addAttribute("bnkTransferViewalbe", false); // lnkgPymLclsCd != 30 and 비권한 유저
      return "dialog.bsar.ar.arPayment";
    }
  }
Example #5
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  @RequestMapping(value = "/bsar/ar/arReceipt", method = RequestMethod.POST)
  // public String receiptOpen(Model model, @RequestParam(required=false)
  // String callBackFunc,@RequestParam(required=false) String language,
  // @RequestBody OtimeVO otimeVO){
  public String receiptOpen(Model model, ReceiptCmd receiptCmd, @RequestBody OtimeVO otimeVO) {

    ObjectMapper om = new ObjectMapper();

    String temp = null;

    try {

      temp = om.defaultPrettyPrintingWriter().writeValueAsString(otimeVO);

      model.addAttribute("recpData", temp);
      model.addAttribute("receipt", receiptService.getReceipt(receiptCmd));
      model.addAttribute(
          "rshtLabel",
          new ObjectMapper()
              .defaultPrettyPrintingWriter()
              .writeValueAsString(receiptService.getRshtLabel(receiptCmd)));

      model.addAttribute("arPymDialogName", receiptCmd.getArPymDialogName());
      // model.addAttribute("callBackFunc",callBackFunc);
      model.addAttribute("callBackFunc", receiptCmd.getCallBackFunc());

    } catch (AcubeCommonException me) {

      logger.error("[receiptOpen] " + me.toString(), me);
      model.addAttribute("RESULT", "FAIL");
      model.addAttribute("MESSAGE", me.toString());
    } catch (Exception e) {

      logger.error("[receiptOpen] " + e.toString(), e);
      model.addAttribute("RESULT", "FAIL");
      model.addAttribute("MESSAGE", "err.500");
    } finally {
      if (logger.isDebugEnabled()) {
        logger.debug("[receiptOpen] END");
      }
    }

    // return new ModelAndView("bsar/ar/arReceipt","data",data);
    return "bsar/ar/arReceipt";
  }
  public static void main(String[] args) throws JsonGenerationException {
    SchloettQueryExtraction extraction = new SchloettQueryExtraction();
    File folder = new File("/home/hziak/Datasets/EExcess/schloett-datacollection-785deb288e36/");
    File[] listOfFiles = folder.listFiles();
    List<File> files = getQueryFile(listOfFiles);

    List<SchloettQueryFormat> querys = new ArrayList<SchloettQueryFormat>();
    try {
      querys.addAll(parseQueryiesFile(files, extraction));
    } catch (JsonSyntaxException | IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    EvaluationQueryList evalQueries = new EvaluationQueryList();
    for (SchloettQueryFormat schloettQueryFormat : querys) {
      if (schloettQueryFormat.getQuerieMap() == null) System.out.println("is null");
      else
        for (Entry<String, LinkedHashMap<String, String>> schloettQueryFormat1 :
            schloettQueryFormat.getQuerieMap().entrySet()) {

          if (schloettQueryFormat1.getValue().get("task_name").endsWith(".en")) {
            System.out.println("query: " + schloettQueryFormat1.getValue().get("query"));
            evalQueries
                .getQueries()
                .add(
                    new EvaluationQuery(
                        schloettQueryFormat1.getValue().get("query"), "TODO: decription", null));
          }
        }
    }

    ObjectMapper mapper = new ObjectMapper();

    try {
      File file = new File(folder.getCanonicalFile() + "/queriesEn.json");
      mapper.defaultPrettyPrintingWriter().writeValue(file, evalQueries);
      System.out.println("Writing to file:" + file.getAbsolutePath());
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Example #7
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  @RequestMapping(value = "/bsar/ar/subsPayment", method = RequestMethod.POST)
  public String getSubsReceipt(
      Model model,
      @RequestBody OtimeVO otimeVO,
      @RequestParam(required = false) String callBackFunc) {

    System.out.println("subsPymDiv:::::::::::" + otimeVO.toString());
    System.out.println("subsPymDiv:::::::::::" + callBackFunc);

    ObjectMapper om = new ObjectMapper();
    String temp = null;
    try {
      temp = om.defaultPrettyPrintingWriter().writeValueAsString(otimeVO);
    } catch (Exception e) {
      // e.printStackTrace();
    }

    model.addAttribute("subsRecpData", temp);
    model.addAttribute("callBackFunc", callBackFunc);
    model.addAttribute("rcpmnyDt", CmnDateUtils.addDate(0));

    return "dialog.bsar.ar.subsPayment";
  }
Example #8
0
 private static <T> void serializeObject(Writer writer, final T artifact) throws IOException {
   OBJECT_MAPPER.defaultPrettyPrintingWriter().writeValue(writer, artifact);
 }
Example #9
0
public class Utils {
  private static boolean DEBUG = false;
  private static final int LOG_DATA_SIZE = 75;
  private static final String LOG_TAG = "tivo_commander";
  private static final int MAX_LOG_LEN = 4096;
  private static final LinkedList<String> mLogData = new LinkedList<String>();
  private static final SimpleDateFormat mLogDateFormatter =
      new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS ");
  private static final ObjectMapper mMapper = new ObjectMapper();
  private static final ObjectWriter mMapperPretty = mMapper.defaultPrettyPrintingWriter();

  public static final void debugLog(String message) {
    if (DEBUG) {
      log(message);
    } else {
      saveLog(message);
    }
  }

  public static final String findImageUrl(JsonNode node) {
    String url = null;
    int biggestSize = 0;
    int size = 0;
    for (JsonNode image : node.path("image")) {
      size = image.path("width").getIntValue() * image.path("height").getIntValue();
      if (size > biggestSize) {
        biggestSize = size;
        url = image.path("imageUrl").getTextValue();
      }
    }
    return url;
  }

  public static final String getLog() {
    @SuppressWarnings("unchecked")
    List<String> logData = (List<String>) mLogData.clone();
    Collections.reverse(logData);
    return join("\n", logData);
  }

  public static final String getVersion(Context context) {
    String version = " v";
    try {
      PackageManager pm = context.getPackageManager();
      version += pm.getPackageInfo(context.getPackageName(), 0).versionName;
    } catch (NameNotFoundException e) {
      version = "";
    }
    return version;
  }

  public static final String join(String glue, List<String> strings) {
    Iterator<String> it = strings.iterator();
    StringBuilder out = new StringBuilder();
    String s;
    while (it.hasNext()) {
      s = it.next();
      if (s == null || s == "") {
        continue;
      }
      out.append(s);
      if (it.hasNext()) {
        out.append(glue);
      }
    }

    return out.toString();
  }

  public static final String join(String glue, String... strings) {
    return join(glue, Arrays.asList(strings));
  }

  public static final void log(String message) {
    saveLog(message);
    Log.i(LOG_TAG, message);
  }

  public static final void logError(String message) {
    saveLog(message);
    Log.e(LOG_TAG, message);
  }

  public static final void logError(String message, Throwable e) {
    StringWriter sw = new StringWriter();
    e.printStackTrace(new PrintWriter(sw));
    String stackTrace = sw.toString();

    saveLog(message + "\n" + stackTrace);
    Log.e(LOG_TAG, message, e);
  }

  public static final void logRpc(Object obj) {
    if (DEBUG) {
      Log.d(LOG_TAG, Utils.stringifyToPrettyJson(obj));
    }
    saveLog(Utils.stringifyToJson(obj));
  }

  public static final void mailLog(String log, Context context, String title) {
    Intent i = new Intent(Intent.ACTION_SEND);
    i.setType("message/rfc822");
    i.putExtra(Intent.EXTRA_EMAIL, new String[] {"*****@*****.**"});
    i.putExtra(Intent.EXTRA_SUBJECT, "TiVo Commander " + title);
    i.putExtra(
        Intent.EXTRA_TEXT,
        "Please describe you were doing when "
            + "something went wrong:\n\n\n\nThen leave these details for me:\n"
            + "Version: "
            + getVersion(context)
            + "\n"
            + log);
    try {
      context.startActivity(Intent.createChooser(i, "Send mail..."));
    } catch (android.content.ActivityNotFoundException ex) {
      Toast.makeText(context, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
    }
  }

  public static final Date parseDateStr(String dateStr) {
    SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd");
    return parseDateTimeStr(dateParser, dateStr);
  }

  public static final Date parseDateTimeStr(String dateStr) {
    SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    return parseDateTimeStr(dateParser, dateStr);
  }

  public static final JsonNode parseJson(String json) {
    try {
      return mMapper.readValue(json, JsonNode.class);
    } catch (JsonMappingException e) {
      Log.e(LOG_TAG, "parseJson failure", e);
    } catch (JsonParseException e) {
      Log.e(LOG_TAG, "parseJson failure", e);
    } catch (IOException e) {
      Log.e(LOG_TAG, "parseJson failure", e);
    }
    logError("When parsing:\n" + json);
    return null;
  }

  public static final String stringifyToJson(Object obj) {
    return stringifyToJson(obj, false);
  }

  public static final String stringifyToPrettyJson(Object obj) {
    return stringifyToJson(obj, true);
  }

  public static final String ucFirst(String s) {
    if (s == null) {
      return null;
    }
    return s.substring(0, 1).toUpperCase() + s.substring(1);
  }

  private static final Date parseDateTimeStr(SimpleDateFormat dateParser, String dateStr) {
    TimeZone tz = TimeZone.getTimeZone("UTC");
    dateParser.setTimeZone(tz);
    ParsePosition pp = new ParsePosition(0);
    return dateParser.parse(dateStr, pp);
  }

  private static final void saveLog(String message) {
    if (message.length() > MAX_LOG_LEN) {
      message = String.format("(%d) %s...", message.length(), message.substring(0, MAX_LOG_LEN));
    }
    mLogData.add(mLogDateFormatter.format(new Date()) + message);
    while (mLogData.size() > LOG_DATA_SIZE) {
      mLogData.remove();
    }
  }

  private static final String stringifyToJson(Object obj, boolean pretty) {
    try {
      if (pretty) {
        return mMapperPretty.writeValueAsString(obj);
      } else {
        return mMapper.writeValueAsString(obj);
      }
    } catch (JsonGenerationException e) {
      Log.e(LOG_TAG, "stringifyToJson failure", e);
    } catch (JsonMappingException e) {
      Log.e(LOG_TAG, "stringifyToJson failure", e);
    } catch (IOException e) {
      Log.e(LOG_TAG, "stringifyToJson failure", e);
    }
    return null;
  }
}