示例#1
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  public void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");

    PrintWriter out = response.getWriter();
    try {
      SubjectDAO subdao = new SubjectDAO();
      DatastreamDAO dstreamDao = new DatastreamDAO();
      List<JsonSubject> jsubList = new ArrayList<JsonSubject>();
      List<Subject> subList = new ArrayList<Subject>();
      String loginID = "leoncool";
      if (request.getParameter(AllConstants.api_entryPoints.request_api_loginid) != null) {
        loginID = request.getParameter(AllConstants.api_entryPoints.request_api_loginid);
      }
      UserDAO userDao = new UserDAO();
      if (!userDao.existLogin(loginID)) {
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.Unauthorized_Access, null, null);
        return;
      }
      if (request.getParameter(AllConstants.api_entryPoints.request_api_onlyParentSubjects) != null
          && request
              .getParameter(AllConstants.api_entryPoints.request_api_onlyParentSubjects)
              .equalsIgnoreCase(AllConstants.api_entryPoints.request_api_true)) {
        subList = subdao.findOnlyParentSubjectsByLoginID(loginID);
      } else {
        subList = subdao.findSubjectsByLoginID(loginID);
      }
      DBtoJsonUtil dbtoJUtil = new DBtoJsonUtil();
      for (Subject sub : subList) {
        if (sub.getVisibleSet() != null
            && sub.getVisibleSet().equalsIgnoreCase(AllConstants.ProgramConts.visibleSet_PUBLIC)) {
          jsubList.add(dbtoJUtil.convert_a_Subject(sub));
        }
      }
      System.out.println(jsubList.size());
      Gson gson = new Gson();
      JsonElement je = gson.toJsonTree(jsubList);
      JsonObject jo = new JsonObject();
      jo.addProperty(AllConstants.ProgramConts.result, AllConstants.ProgramConts.succeed);
      jo.add("subject_list", je);
      JsonWriter jwriter = new JsonWriter(response.getWriter());
      //            if (request.getParameter("callback") != null) {
      //                System.out.println("using callback");
      //                out.print(request.getParameter("callback")+"("+ gson.toJson(jo) + ");");
      //            } else {
      //                gson.toJson(jo, jwriter);
      //                jwriter.close();
      //            }
      gson.toJson(jo, jwriter);
      jwriter.close();

    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      out.close();
    }
  }
  @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
  public void exportData(HttpServletResponse resp, Principal prin) throws IOException {

    resp.setContentType(MediaType.APPLICATION_JSON_VALUE);

    // this writer puts things out onto the wire
    JsonWriter writer = new JsonWriter(resp.getWriter());
    writer.setIndent("  ");

    try {

      writer.beginObject();

      writer.name("exported-at");
      writer.value(dateFormat.format(new Date()));

      writer.name("exported-from");
      writer.value(config.getIssuer());

      writer.name("exported-by");
      writer.value(prin.getName());

      // delegate to the service to do the actual export
      dataService_1_3.exportData(writer);

      writer.endObject(); // end root
      writer.close();

    } catch (IOException e) {
      logger.error("Unable to export data", e);
    }
  }
  private static void addRSPack(boolean refreash) {
    File rspack = new File(getConfigFolder(), "/resources");
    if (!rspack.exists()) return;

    if (!Arrays.asList(rspack.list()).contains("pack.mcmeta")) {
      try {
        JsonWriter writer = new JsonWriter(new FileWriter(new File(rspack, "pack.mcmeta")));
        writer.beginObject();
        writer.name("pack");
        writer.beginObject();
        writer.name("pack_format").value(1);
        writer.name("description").value("Draconic Evolution GUI Images");
        writer.endObject();
        writer.endObject();
        writer.close();
      } catch (IOException e) {
        LogHelper.error("Error creating pack.mcmeta");
        e.printStackTrace();
      }
    }

    Field f =
        ReflectionHelper.findField(Minecraft.class, "defaultResourcePacks", "field_110449_ao");
    f.setAccessible(true);
    try {
      List defaultResourcePacks = (List) f.get(Minecraft.getMinecraft());
      defaultResourcePacks.add(new FolderResourcePack(rspack));

      f.set(Minecraft.getMinecraft(), defaultResourcePacks);
      LogHelper.info("RS Added");
      if (refreash) Minecraft.getMinecraft().refreshResources();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    }
  }
示例#4
0
  public File executeQuery(String command, String rootDirectory) throws SQLException, IOException {
    Statement stmt = null;
    if (this.conn != null) {
      final String fileName = UUID.randomUUID().toString();
      final File file = File.createTempFile(fileName, ".json");
      try {
        stmt = this.conn.createStatement();
        ResultSet results = stmt.executeQuery(command);
        ResultSetMetaData rsmd = results.getMetaData();

        // Borrowed from
        // http://stackoverflow.com/questions/18960446/how-to-convert-a-java-resultset-into-json
        JsonWriter writer = new JsonWriter(new PrintWriter(file));
        int count = 0;
        int numRows = 0;
        boolean hasRows = results.last();
        if (hasRows) {
          numRows = results.getRow();
        }
        results.beforeFirst();

        writer.beginObject();
        writer.name("elements");
        writer.beginArray();

        while (results.next()) {
          writer.beginObject();
          for (int idx = 1; idx <= rsmd.getColumnCount(); idx++) {
            writer.name(rsmd.getColumnLabel(idx));
            writer.value(results.getString(idx));
          }
          writer.endObject();
          count++;
        }
        if (count == 0) {
          writer.beginObject();
          writer.endObject();
        }
        writer.endArray();
        writer.endObject();

        writer.flush();
        writer.close();
        return file;

      } catch (SQLException e) {
        e.printStackTrace();
        return null;
      } finally {
        if (stmt != null) {
          stmt.close();
        }
      }
    }
    return null;
  }
示例#5
0
 /**
  * Serialize this fancy message, converting it into syntactically-valid JSON using a {@link
  * JsonWriter}. This JSON should be compatible with vanilla formatter commands such as {@code
  * /tellraw}.
  *
  * @return The JSON string representing this object.
  */
 public String toJSONString() {
   if (!dirty && jsonString != null) {
     return jsonString;
   }
   StringWriter string = new StringWriter();
   JsonWriter json = new JsonWriter(string);
   try {
     writeJson(json);
     json.close();
   } catch (Exception e) {
     throw new RuntimeException("invalid message");
   }
   jsonString = string.toString();
   dirty = false;
   return jsonString;
 }
 private void encodeAndSendMapMessage(
     @NonNull WebSocketMessage.UnencodedMapMessage paramUnencodedMapMessage)
     throws IOException, WebSocketException {
   ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
   JsonWriter localJsonWriter =
       new JsonWriter(new OutputStreamWriter(localByteArrayOutputStream, "UTF-8"));
   this.mGson.toJson(paramUnencodedMapMessage.mPayload, Map.class, localJsonWriter);
   localJsonWriter.flush();
   localJsonWriter.close();
   paramUnencodedMapMessage = localByteArrayOutputStream.toByteArray();
   localByteArrayOutputStream.close();
   if (paramUnencodedMapMessage.length > this.mWebSocketOptions.getMaxMessagePayloadSize()) {
     throw new WebSocketException("message payload exceeds payload limit");
   }
   sendFrame(1, true, paramUnencodedMapMessage);
 }
示例#7
0
  @Override
  public void write(final KadMessage msg, final OutputStream out) throws IOException {

    Writer utf8Writer = null;
    JsonWriter writer = null;

    try {

      utf8Writer = new OutputStreamWriter(out, "UTF-8");
      writer = new JsonWriter(utf8Writer);

      writer.beginArray();
      final Class<?> clazz = msg.getClass();
      this.gson.toJson(clazz.getSimpleName(), String.class, writer);
      // System.out.println("writing class: "+clazz);
      this.gson.toJson(msg, clazz, writer);
      writer.endArray();

    } finally {
      writer.close();
      utf8Writer.close();
      out.close();
    }
  }
示例#8
0
  @Override
  protected void doPut(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    Movie movie;
    try {
      movie = gson.fromJson(req.getReader(), Movie.class);
    } catch (Exception ignore) {
      resp.setStatus(SC_BAD_REQUEST);
      return;
    }

    if (!isMovieValid(movie) || movie.getId() != null) {
      resp.setStatus(SC_BAD_REQUEST);
      return;
    }
    Long id = service.addMovie(movie);

    resp.setContentType("application/json");
    resp.setCharacterEncoding("UTF-8");

    JsonWriter jsonWriter = gson.newJsonWriter(resp.getWriter());
    jsonWriter.beginObject().name("id").value(id).endObject();
    jsonWriter.close();
  }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  public void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");

    //        PrintWriter out = response.getWriter();
    OutputStream outStream = null;
    try {

      long start = 0;
      long end = 0;
      String blockid = null;
      try {
        if (request.getParameter(AllConstants.api_entryPoints.request_api_start) != null) {
          start =
              Long.parseLong(request.getParameter(AllConstants.api_entryPoints.request_api_start));
        }
        if (request.getParameter(AllConstants.api_entryPoints.request_api_end) != null) {
          end = Long.parseLong(request.getParameter(AllConstants.api_entryPoints.request_api_end));
        }
        if (request.getParameter(AllConstants.api_entryPoints.request_api_blockid) != null) {
          blockid = request.getParameter(AllConstants.api_entryPoints.request_api_blockid);
          if (blockid.length() < 5) {}
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }

      String loginID = "leoncool";
      if (request.getParameter(AllConstants.api_entryPoints.request_api_loginid) != null) {
        loginID = request.getParameter(AllConstants.api_entryPoints.request_api_loginid);
      }
      UserDAO userDao = new UserDAO();
      if (!userDao.existLogin(loginID)) {
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.Unauthorized_Access, null, null);
        return;
      }
      SubjectDAO subjDao = new SubjectDAO();
      Subject subject = (Subject) subjDao.findHealthSubject(loginID); // Retreive
      if (subject == null) {
        ReturnParser.outputErrorException(
            response,
            AllConstants.ErrorDictionary.SYSTEM_ERROR_NO_DEFAULT_HEALTH_SUBJECT,
            null,
            null);
        return;
      }
      String streamID = ServerUtil.getHealthStreamID(ServletPath(request));

      DatastreamDAO dstreamDao = new DatastreamDAO();
      DBtoJsonUtil dbtoJUtil = new DBtoJsonUtil();
      Datastream datastream = dstreamDao.getDatastream(streamID, true, false);
      if (blockid != null && dstreamDao.getDatastreamBlock(blockid) == null) {
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.Invalid_Datablock_ID, null, blockid);
        return;
      }
      if (datastream == null) {
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.Unknown_StreamID, null, streamID);
        return;
      }
      HashMap<String, String> mapUnits = new HashMap<String, String>();
      HashMap<String, String> allUnits = new HashMap<String, String>();
      if (request.getParameter(AllConstants.api_entryPoints.request_api_unit_id) != null
          && request.getParameter(AllConstants.api_entryPoints.request_api_unit_id).length() > 0) {
        String[] unitids =
            request.getParameter(AllConstants.api_entryPoints.request_api_unit_id).split(",");
        System.out.println("unitids:size:" + unitids.length);
        allUnits = dbtoJUtil.ToDatastreamUnitsMap(datastream);
        System.out.println("units size:" + datastream.getDatastreamUnitsList().size());
        for (String id : unitids) {
          if (id.length() < 3) {
            // error
            return;
          } else {
            if (allUnits.get(id) == null) {
              // error
              System.out.println("cannot find id" + id + "");
              return;
            } else {
              mapUnits.put(id, id);
            }
          }
        }
      }
      System.out.println("mapUnits.size():" + mapUnits.size() + ", " + mapUnits);
      Gson gson = new Gson();
      int debug = 1;
      if (debug == 1) {
        System.out.println("debuging.....going to hbase");
        HBaseDatapointDAO diDao = new HBaseDatapointDAO();
        System.out.println("datastreamID:" + datastream.getStreamId());
        HBaseDataImport hbaseexport = null;
        try {
          hbaseexport = diDao.exportDatapoints(streamID, start, end, blockid, mapUnits, null, null);
        } catch (ErrorCodeException ex) {
          ex.printStackTrace();
          ReturnParser.outputErrorException(
              response, AllConstants.ErrorDictionary.Internal_Fault, null, null);
          return;
        } catch (Throwable ex) {
          ex.printStackTrace();
          ReturnParser.outputErrorException(
              response, AllConstants.ErrorDictionary.Internal_Fault, null, null);
          return;
        }
        if (hbaseexport != null) {
          hbaseexport.setUnits_list(
              dbtoJUtil.convertDatastream(datastream, mapUnits).getUnits_list());
        } else {
          hbaseexport = new HBaseDataImport();
          hbaseexport.setBlock_id(blockid);
          hbaseexport.setData_points(new ArrayList<JsonDataPoints>());

          hbaseexport.setDatastream_id(streamID);
          hbaseexport.setUnits_list(
              dbtoJUtil.convertDatastream(datastream, mapUnits).getUnits_list());
          //                    hbaseexport.setDeviceid(streamID);
        }
        outStream = null;
        boolean iftoZip = true;
        String encodings = request.getHeader("Accept-Encoding");
        if (encodings != null && encodings.indexOf("gzip") != -1 && iftoZip == true) {
          // Go with GZIP
          response.setHeader("Content-Encoding", "gzip");
          outStream = new GZIPOutputStream(response.getOutputStream());
        } else {
          outStream = response.getOutputStream();
        }
        response.setHeader("Vary", "Accept-Encoding");
        Date timerStart = new Date();
        JsonElement je = gson.toJsonTree(hbaseexport);
        JsonObject jo = new JsonObject();
        jo.addProperty(AllConstants.ProgramConts.result, AllConstants.ProgramConts.succeed);
        jo.add("datapoints_list", je);
        OutputStreamWriter osWriter = new OutputStreamWriter(outStream);
        JsonWriter jwriter = new JsonWriter(osWriter);
        String callbackStr = null;
        if (request.getParameter(AllConstants.api_entryPoints.requset_api_callback) != null) {
          callbackStr = request.getParameter(AllConstants.api_entryPoints.requset_api_callback);
          osWriter.append(callbackStr + "(");
        }
        gson.toJson(jo, jwriter);
        if (callbackStr != null) {
          osWriter.append(");");
        }
        jwriter.close();
        Date timerEnd = new Date();
        System.out.println(
            "Json Time takes:"
                + (timerEnd.getTime() - timerStart.getTime()) / (1000.00)
                + "seconds");
        osWriter.close();
        outStream.close();
      } else {
        String encodings = request.getHeader("Accept-Encoding");
        boolean iftoZip = true;
        if (encodings != null && encodings.indexOf("gzip") != -1 && iftoZip == true) {
          // Go with GZIP
          response.setHeader("Content-Encoding", "gzip");
          outStream = new GZIPOutputStream(response.getOutputStream());
        } else {
          outStream = response.getOutputStream();
        }
        response.setHeader("Vary", "Accept-Encoding");
        File inputFile = new File("E:/IC_Dropbox/Dropbox/java/healthbook/sample_data/download.txt");
        //                File inputFile = new
        // File("F:/Dropbox/Dropbox/java/healthbook/sample_data/download.txt");
        BufferedReader reader = new BufferedReader(new FileReader(inputFile));
        String inputLine;
        while ((inputLine = reader.readLine()) != null) {
          outStream.write(inputLine.getBytes());
          //  out.print(inputLine);
        }
        outStream.close();
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      ReturnParser.outputErrorException(
          response, AllConstants.ErrorDictionary.Internal_Fault, null, null);
      return;
    } finally {
      System.out.println("running finally");
      //            out.close();
      if (outStream != null) {
        outStream.close();
      }
    }
  }