Esempio n. 1
0
 public List<CIBuild> getBuilds(CIJob job) throws PhrescoException {
   if (debugEnabled) {
     S_LOGGER.debug("Entering Method CIManagerImpl.getCIBuilds(CIJob job)");
   }
   List<CIBuild> ciBuilds = null;
   try {
     if (debugEnabled) {
       S_LOGGER.debug("getCIBuilds()  JobName = " + job.getName());
     }
     JsonArray jsonArray = getBuildsArray(job);
     ciBuilds = new ArrayList<CIBuild>(jsonArray.size());
     Gson gson = new Gson();
     CIBuild ciBuild = null;
     for (int i = 0; i < jsonArray.size(); i++) {
       ciBuild = gson.fromJson(jsonArray.get(i), CIBuild.class);
       setBuildStatus(ciBuild, job);
       String buildUrl = ciBuild.getUrl();
       String jenkinUrl = job.getJenkinsUrl() + ":" + job.getJenkinsPort();
       buildUrl =
           buildUrl.replaceAll(
               "localhost:" + job.getJenkinsPort(),
               jenkinUrl); // when displaying url it should display setup machine ip
       ciBuild.setUrl(buildUrl);
       ciBuilds.add(ciBuild);
     }
   } catch (Exception e) {
     if (debugEnabled) {
       S_LOGGER.debug(
           "Entering Method CIManagerImpl.getCIBuilds(CIJob job) " + e.getLocalizedMessage());
     }
   }
   return ciBuilds;
 }
Esempio n. 2
0
  private void setSvnCredential(CIJob job) throws JDOMException, IOException {
    S_LOGGER.debug("Entering Method CIManagerImpl.setSvnCredential");
    try {
      String jenkinsTemplateDir = Utility.getJenkinsTemplateDir();
      String credentialFilePath = jenkinsTemplateDir + job.getRepoType() + HYPHEN + CREDENTIAL_XML;
      if (debugEnabled) {
        S_LOGGER.debug("credentialFilePath ... " + credentialFilePath);
      }
      File credentialFile = new File(credentialFilePath);

      SvnProcessor processor = new SvnProcessor(credentialFile);

      //			DataInputStream in = new DataInputStream(new FileInputStream(credentialFile));
      //			while (in.available() != 0) {
      //				System.out.println(in.readLine());
      //			}
      //			in.close();

      processor.changeNodeValue("credentials/entry//userName", job.getUserName());
      processor.changeNodeValue("credentials/entry//password", job.getPassword());
      processor.writeStream(new File(Utility.getJenkinsHome() + File.separator + job.getName()));

      // jenkins home location
      String jenkinsJobHome = System.getenv(JENKINS_HOME);
      StringBuilder builder = new StringBuilder(jenkinsJobHome);
      builder.append(File.separator);

      processor.writeStream(new File(builder.toString() + CI_CREDENTIAL_XML));
    } catch (Exception e) {
      S_LOGGER.error(
          "Entered into the catch block of CIManagerImpl.setSvnCredential "
              + e.getLocalizedMessage());
    }
  }
 /** @return {@link InputStream} from a {@link HttpResponse} */
 InputStream getStream(HttpResponse response) {
   try {
     return response.getEntity().getContent();
   } catch (Exception e) {
     log.error("Error reading response. " + e.getMessage());
     throw new CouchDbException(e);
   }
 }
Esempio n. 4
0
 private static void addFolder(FileSystem fs, Path p, JsonArray succeeded, JsonArray failed) {
   try {
     if (fs == null) return;
     for (FileStatus file : fs.listStatus(p)) {
       Path pfs = file.getPath();
       if (file.isDir()) {
         addFolder(fs, pfs, succeeded, failed);
       } else {
         Key k = Key.make(pfs.toString());
         long size = file.getLen();
         Value val = null;
         if (pfs.getName().endsWith(Extensions.JSON)) {
           JsonParser parser = new JsonParser();
           JsonObject json = parser.parse(new InputStreamReader(fs.open(pfs))).getAsJsonObject();
           JsonElement v = json.get(Constants.VERSION);
           if (v == null) throw new RuntimeException("Missing version");
           JsonElement type = json.get(Constants.TYPE);
           if (type == null) throw new RuntimeException("Missing type");
           Class c = Class.forName(type.getAsString());
           OldModel model = (OldModel) c.newInstance();
           model.fromJson(json);
         } else if (pfs.getName().endsWith(Extensions.HEX)) { // Hex file?
           FSDataInputStream s = fs.open(pfs);
           int sz = (int) Math.min(1L << 20, size); // Read up to the 1st meg
           byte[] mem = MemoryManager.malloc1(sz);
           s.readFully(mem);
           // Convert to a ValueArray (hope it fits in 1Meg!)
           ValueArray ary = new ValueArray(k, 0).read(new AutoBuffer(mem));
           val = new Value(k, ary, Value.HDFS);
         } else if (size >= 2 * ValueArray.CHUNK_SZ) {
           val =
               new Value(
                   k,
                   new ValueArray(k, size),
                   Value.HDFS); // ValueArray byte wrapper over a large file
         } else {
           val = new Value(k, (int) size, Value.HDFS); // Plain Value
           val.setdsk();
         }
         DKV.put(k, val);
         Log.info("PersistHdfs: DKV.put(" + k + ")");
         JsonObject o = new JsonObject();
         o.addProperty(Constants.KEY, k.toString());
         o.addProperty(Constants.FILE, pfs.toString());
         o.addProperty(Constants.VALUE_SIZE, file.getLen());
         succeeded.add(o);
       }
     }
   } catch (Exception e) {
     Log.err(e);
     JsonObject o = new JsonObject();
     o.addProperty(Constants.FILE, p.toString());
     o.addProperty(Constants.ERROR, e.getMessage());
     failed.add(o);
   }
 }
Esempio n. 5
0
 public Card(ResultSet resultSet) {
   try {
     cid = resultSet.getInt("cid");
     inverseid = resultSet.getInt("inverseid");
     deckid = resultSet.getInt("did");
     question = resultSet.getString("question");
     answer = resultSet.getString("answer");
     dir = resultSet.getString("dir");
   } catch (Exception e) {
     e.printStackTrace(System.err);
   }
 }
Esempio n. 6
0
  private void setMailCredential(CIJob job) {
    if (debugEnabled) {
      S_LOGGER.debug("Entering Method CIManagerImpl.setMailCredential");
    }
    try {
      String jenkinsTemplateDir = Utility.getJenkinsTemplateDir();
      String mailFilePath = jenkinsTemplateDir + MAIL + HYPHEN + CREDENTIAL_XML;
      if (debugEnabled) {
        S_LOGGER.debug("configFilePath ... " + mailFilePath);
      }
      File mailFile = new File(mailFilePath);

      SvnProcessor processor = new SvnProcessor(mailFile);

      //			DataInputStream in = new DataInputStream(new FileInputStream(mailFile));
      //			while (in.available() != 0) {
      //				System.out.println(in.readLine());
      //			}
      //			in.close();

      // Mail have to go with jenkins running email address
      InetAddress ownIP = InetAddress.getLocalHost();
      processor.changeNodeValue(
          CI_HUDSONURL,
          HTTP_PROTOCOL
              + PROTOCOL_POSTFIX
              + ownIP.getHostAddress()
              + COLON
              + job.getJenkinsPort()
              + FORWARD_SLASH
              + CI
              + FORWARD_SLASH);
      processor.changeNodeValue("smtpAuthUsername", job.getSenderEmailId());
      processor.changeNodeValue("smtpAuthPassword", job.getSenderEmailPassword());
      processor.changeNodeValue("adminAddress", job.getSenderEmailId());

      // jenkins home location
      String jenkinsJobHome = System.getenv(JENKINS_HOME);
      StringBuilder builder = new StringBuilder(jenkinsJobHome);
      builder.append(File.separator);

      processor.writeStream(new File(builder.toString() + CI_MAILER_XML));
    } catch (Exception e) {
      S_LOGGER.error(
          "Entered into the catch block of CIManagerImpl.setMailCredential "
              + e.getLocalizedMessage());
    }
  }
Esempio n. 7
0
 public void closedSession() {
   try {
     if ((socket == null) || socket.isClosed()) {
       return;
     }
     sendMessage(
         new ObjectExchangeWrap(OUT_SESSION_CLOSE, null, transactionId).getObjectExchange());
     writer.close();
     reader.close();
     socket.close();
     this.interrupt();
     System.out.println("Showdown input and output");
   } catch (Exception e) {
     System.out.println("try shutdown error");
     System.out.println(e.getMessage());
   }
 }
Esempio n. 8
0
 public LinkedList parseFile(String fileName, Class theClass) {
   LinkedList object = null;
   String nextLine = "";
   String jsonFile;
   StringBuilder sb = new StringBuilder();
   try {
     BufferedReader reader = new BufferedReader(new FileReader(fileName));
     while ((nextLine = reader.readLine()) != null) {
       sb.append(nextLine);
     }
     jsonFile = sb.toString();
     if (jsonFile.indexOf("{") == 0) {
       jsonFile = jsonFile.substring(1, jsonFile.length() - 1);
     }
     object = (LinkedList) gson.fromJson(jsonFile, theClass);
   } catch (Exception e) {
     e.printStackTrace();
   }
   return object;
 }
Esempio n. 9
0
  private void deserializeProperties(
      String context, JsonObject jsonObject, String name, Object object)
      throws QueryException, BeanValidationException {
    Set<Map.Entry<String, JsonElement>> props = jsonObject.entrySet();
    for (Map.Entry<String, JsonElement> prop : props) {
      String property = prop.getKey();
      if (property.equals("name")) continue;

      PropertyDescriptor pd = null;
      try {
        pd = getPropertyDescriptor(object.getClass(), property);
      } catch (IntrospectionException e) {
        logger.error("Introspection error on " + object.getClass(), e);
      }

      if (pd == null) {
        String msg =
            "Property '"
                + property
                + "' was specified for object '"
                + name
                + "' but no matching setter was found on '"
                + object.getClass()
                + "'";

        throw new QueryException(msg);
      }

      Class propClass = pd.getPropertyType();

      Object propValue;
      try {
        propValue = m_gson.fromJson(prop.getValue(), propClass);
        validateObject(propValue, context + "." + property);
      } catch (ContextualJsonSyntaxException e) {
        throw new BeanValidationException(
            new SimpleConstraintViolation(e.getContext(), e.getMessage()), context);
      } catch (NumberFormatException e) {
        throw new BeanValidationException(
            new SimpleConstraintViolation(property, e.getMessage()), context);
      }

      Method method = pd.getWriteMethod();
      if (method == null) {
        String msg =
            "Property '"
                + property
                + "' was specified for object '"
                + name
                + "' but no matching setter was found on '"
                + object.getClass().getName()
                + "'";

        throw new QueryException(msg);
      }

      try {
        method.invoke(object, propValue);
      } catch (Exception e) {
        logger.error("Invocation error: ", e);
        String msg =
            "Call to "
                + object.getClass().getName()
                + ":"
                + method.getName()
                + " failed with message: "
                + e.getMessage();

        throw new QueryException(msg);
      }
    }
  }
Esempio n. 10
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void addObject(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    Connection c;
    PreparedStatement st;
    ResultSet set;

    String objName;
    int objTileSrc;
    int objXOff;
    int objYOff;
    int objWidth;
    int objHeight;
    String objDesc;
    int objId;
    int objAuth;
    Gson Gson;
    FormResponse resp;

    resp = null;

    c = null;
    st = null;
    set = null;

    Gson = new Gson();

    try {

      //	Verify we have authorization to do this! TODO: Set a special response code on authorization
      // failure.

      //	Perform a quick, cursory validation

      resp = validateAddForm(request);

      if (!resp.isAccepted()) {
        resp.setResult("FAIL");

      } else {

        //	Apply parameters

        objName = request.getParameter("title");
        objDesc = request.getParameter("desc");
        objTileSrc = Integer.parseInt(request.getParameter("tileset"));
        objXOff = Integer.parseInt(request.getParameter("objXOff"));
        objYOff = Integer.parseInt(request.getParameter("objYOff"));
        objWidth = Integer.parseInt(request.getParameter("objWidth"));
        objHeight = Integer.parseInt(request.getParameter("objHeight"));
        // objAuth 	= (Integer) request.getSession().getAttribute("userid");
        // TODO: Get the public flag

        System.out.println("Object name: '" + objName + "'");

        //	Generate the query

        c = DBResourceManager.getConnection();

        st = c.prepareStatement(OBJTYPE_INSERT, PreparedStatement.RETURN_GENERATED_KEYS);

        st.setString(1, objName);
        st.setInt(2, objTileSrc);
        st.setInt(3, objXOff);
        st.setInt(4, objYOff);
        st.setInt(5, objWidth);
        st.setInt(6, objHeight);
        st.setString(7, objDesc);

        st.execute();

        set = st.getGeneratedKeys();

        //	Grab the generated key

        if (set.next()) {
          objId = set.getInt(1);

          resp.setResult("OK");
          resp.addParamResult("objId", "VALUEUP:" + objId);

          //	Send the OK. Note that Dojo requires us to wrap the response
          //	in an html doc's text area for max. compatibility.

        } else {

          System.out.println("Failure to create object.");

          resp.setResult("FAIL");
        }
      }

      //	Send the resposne object no matter what

      response
          .getWriter()
          .println("<html><body><textarea>" + Gson.toJson(resp) + "</textarea></html></body>");

    } catch (Exception ex) {
      ex.printStackTrace();

      if (resp == null) {
        resp = new FormResponse();
        resp.setAcceptance(false);
      }

      resp.setResult("FAIL");
      resp.addMessage(ex.toString());

      response
          .getWriter()
          .println("<html><body><textarea>" + ex.toString() + "</textarea></html></body>");

    } finally {

      DataTools.safeCleanUp(c, st, set);
    }
  }
Esempio n. 11
0
  /**
   * When browsing objects, we'd like to make it possible to interface the object type list with a
   * Dojo Data Source. To do so, we stream the objects out as a JSON object.
   *
   * @param request
   * @param response
   * @throws ServletException
   * @throws IOException
   */
  private void doObjTypeRequestJSON(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    int fromIndex, maxResult;
    Connection c;
    PreparedStatement st;
    ResultSet set;
    JsonWriter jOut;
    int recCount;

    //	Set the content up

    response.setContentType("application/json");

    //	Setup our database information

    c = null;
    st = null;
    set = null;

    //	Setup the rest of our environment

    recCount = 0;

    jOut = new JsonWriter(response.getWriter());

    try {

      //	Parse request parameters

      fromIndex = Integer.parseInt(request.getParameter("start"));
      maxResult = Integer.parseInt(request.getParameter("count"));

      //	Create connection to the database and prep the query

      c = DBResourceManager.getConnection();

      st = c.prepareStatement(OBJTYPE_LIST_JSON);
      st.setInt(1, fromIndex);
      st.setInt(2, maxResult);

      //	Execute the query

      set = st.executeQuery();

      //	Now, stream the results out as if they were an object

      jOut.beginObject();
      jOut.name("items").beginArray();

      while (set.next()) {
        //	Write each element out as an object

        jOut.beginObject();

        jOut.name("objid").value(set.getInt("id"));
        jOut.name("objname").value(set.getString("name"));
        jOut.name("objtilesrc").value(set.getString("tilesrc"));
        jOut.name("description").value(set.getString("description"));

        jOut.endObject();

        //	Increment the record count

        recCount++;
      }

      //	Terminate the array

      jOut.endArray();

      //	Note the number of rows

      jOut.name("numRows").value(recCount);

      //	End the overall object

      jOut.endObject();

      //	Flush the output

      jOut.flush();

    } catch (Exception ex) {
      ex.printStackTrace();

    } finally {

      DataTools.safeCleanUp(c, st, set);
    }
  }
Esempio n. 12
0
  public synchronized Object __rpccall__(String endpoint, Object funcobj, boolean usecache) {
    try {
      // normal case is passing a functioncall, batch case is passing a List<FunctionCall>
      FunctionCall func = (FunctionCall) funcobj;
      if (usecache && has(endpoint, func)) return get(endpoint, func);
      if (!can_connect)
        if (has(endpoint, func)) {
          return get(endpoint, func);
        } else {
          return null;
        }
      func.params = __marshall_args__(func.params);
      funcobj = func;
    } catch (ClassCastException ex) {
      try {
        BatchClient b = (BatchClient) funcobj;
        List<FunctionCall> newcalls = new Vector<FunctionCall>();
        for (int i = 0; i < b.batch.size(); i++) {
          b.batch.get(i).params = __marshall_args__(b.batch.get(i).params);
        }
        for (FunctionCall f : b.batch) {
          if (!b.called.contains(f)) {
            newcalls.add(f);
          }
        }
        funcobj = newcalls;
      } catch (ClassCastException ex2) {

      }
    }
    HttpPost post = new HttpPost(endpoint);
    StringEntity req = null;
    req = new StringEntity(gson.toJson(funcobj), "UTF-8");
    post.setEntity(req);
    post.setHeader(HTTP.CONTENT_TYPE, "application/json");
    HttpResponse resp = null;
    HttpClient client = Http.client();
    try {
      resp = client.execute(post, Http.context());
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return null;
    }
    Object ret = null;
    HttpEntity rep = resp.getEntity();
    InputStreamReader is = null;
    try {
      is = new InputStreamReader(rep.getContent());
      BufferedReader rd = new BufferedReader(is);
      String out = "";
      String line = null;
      while ((line = rd.readLine()) != null) {
        out += line;
      }
      resp.getEntity().consumeContent();
      ret = __parse_response__(out);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      throw new RuntimeException();
    } finally {
      if (is != null)
        try {
          is.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
    }
    FunctionCall func = (FunctionCall) funcobj;
    if (usecache) set(endpoint, func, ret);
    return ret;
  }
Esempio n. 13
0
  // New -- returns data in HashMap
  private static Map viewSignups(
      HttpServletRequest req, PrintWriter out, Connection con, boolean json_mode) {

    int wait_list_id = 0;
    int wait_list_signup_id = 0;
    int sum_players = 0;
    int date = 0;
    int pos = 1;
    int time = SystemUtils.getTime(con);
    int today_date = (int) SystemUtils.getDate(con);
    int start_time = 0;
    int end_time = 0;
    int count = 0;
    int index = 0;
    int player_index = 0;
    Map waitlist_map = new HashMap();
    waitlist_map.put("options", new HashMap());
    waitlist_map.put("signups", new LinkedHashMap());

    String sindex =
        req.getParameter(
            "index"); //  index value of day (needed by Proshop_waitlist_slot when returning)
    String id = req.getParameter("waitListId"); //  uid of the wait list we are working with
    String course = (req.getParameter("course") == null) ? "" : req.getParameter("course");
    String returnCourse =
        (req.getParameter("returnCourse") == null) ? "" : req.getParameter("returnCourse");
    String sdate = (req.getParameter("sdate") == null) ? "" : req.getParameter("sdate");
    String name = (req.getParameter("name") == null) ? "" : req.getParameter("name");
    String day_name = (req.getParameter("day_name") == null) ? "" : req.getParameter("day_name");
    String sstart_time =
        (req.getParameter("start_time") == null) ? "" : req.getParameter("start_time");
    String send_time = (req.getParameter("end_time") == null) ? "" : req.getParameter("end_time");
    // String count = (req.getParameter("count") == null) ? "" : req.getParameter("count");
    String jump = req.getParameter("jump");

    String fullName = "";
    String cw = "";
    String notes = "";
    String nineHole = "";

    PreparedStatement pstmt = null;
    PreparedStatement pstmt2 = null;

    boolean tmp_found = false;
    boolean tmp_found2 = false;
    boolean master =
        (req.getParameter("view") != null && req.getParameter("view").equals("master"));
    boolean show_notes =
        (req.getParameter("show_notes") != null && req.getParameter("show_notes").equals("yes"));
    boolean alt_row = false;
    boolean tmp_converted = false;

    try {

      date = Integer.parseInt(sdate);
      index = Integer.parseInt(sindex);
      wait_list_id = Integer.parseInt(id);
      start_time = Integer.parseInt(sstart_time);
      end_time = Integer.parseInt(send_time);
    } catch (NumberFormatException e) {
    }

    try {

      count = getWaitList.getListCount(wait_list_id, date, index, time, !master, con);

    } catch (Exception exp) {
      out.println(exp.getMessage());
    }

    //
    //  isolate yy, mm, dd
    //
    int yy = date / 10000;
    int temp = yy * 10000;
    int mm = date - temp;
    temp = mm / 100;
    temp = temp * 100;
    int dd = mm - temp;
    mm = mm / 100;

    String report_date = SystemUtils.getLongDateTime(today_date, time, " at ", con);

    if (!json_mode) {
      out.println("<br>");
      out.println(
          "<h3 align=center>"
              + ((master) ? "Master Wait List Sign-up Sheet" : "Current Wait List Sign-ups")
              + "</h3>");

      out.println("<p align=center><font size=3><b><i>\"" + name + "\"</i></b></font></p>");

      out.println("<table border=0 align=center>");

      out.println("<tr><td><font size=\"2\">");
      out.println(
          "Date:&nbsp;&nbsp;<b>"
              + day_name
              + "&nbsp;&nbsp;"
              + mm
              + "/"
              + dd
              + "/"
              + yy
              + "</b></td>");
      out.println("<td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</td><td>");
      if (!course.equals("")) {
        out.println("<font size=\"2\">Course:&nbsp;&nbsp;<b>" + course + "</b></font>");
      }
      out.println("</td></tr>");

      out.println(
          "<tr><td><font size=\"2\">Time:&nbsp;&nbsp;<b>"
              + SystemUtils.getSimpleTime(start_time)
              + " to "
              + SystemUtils.getSimpleTime(end_time)
              + "</b></font></td>");

      out.println("<td></td>");

      out.println("<td><font size=\"2\">Signups:&nbsp;&nbsp;<b>" + count + "</b></font></td>");

      out.println("</table>");

      out.println(
          "<p align=center><font size=2><b><i>List Generated on "
              + report_date
              + "</i></b></font></p>");

      out.println("<table align=center border=1 bgcolor=\"#F5F5DC\">");

      if (master) {

        out.println(
            "<tr bgcolor=\"#8B8970\" align=center style=\"color: black; font-weight: bold\">"
                + "<td height=35>&nbsp;Pos&nbsp;</td>"
                + "<td>Sign-up Time</td>"
                + "<td>Members</td>"
                + "<td>Desired Time</td>"
                + "<td>&nbsp;Players&nbsp;</td>"
                + "<td>&nbsp;On Sheet&nbsp;</td>"
                + "<td>Converted At</td>"
                + "<td>&nbsp;Converted By&nbsp;</td>"
                + ((show_notes) ? "<td>&nbsp;Notes&nbsp;</td>" : "")
                + "</tr>");
      } else {

        out.println(
            "<tr bgcolor=\"#8B8970\" align=center style=\"color: black; font-weight: bold\">"
                + "<td height=35>&nbsp;Pos&nbsp;</td>"
                + "<td>Members</td>"
                + "<td>Desired Time</td>"
                + "<td>&nbsp;Players&nbsp;</td>"
                + ((show_notes) ? "<td>&nbsp;Notes&nbsp;</td>" : "")
                + "</tr>"); // +
        // "<td>&nbsp;On Sheet&nbsp;</td>" +
        // "</tr>");
        // ((multi == 0) ? "" : "<td>Course</td>") +
      }
      out.println(
          "<!-- wait_list_id=" + wait_list_id + ", date=" + date + ", time=" + time + " -->");
    }

    try {

      pstmt =
          con.prepareStatement(
              ""
                  + "SELECT *, "
                  + "DATE_FORMAT(created_datetime, '%c/%e/%y %r') AS created_time, "
                  + "DATE_FORMAT(converted_at, '%c/%e/%y %r') AS converted_time "
                  + // %l:%i %p
                  "FROM wait_list_signups "
                  + "WHERE wait_list_id = ? AND date = ? "
                  + ((master) ? "" : "AND converted = 0 ")
                  + ((!master && sindex.equals("0")) ? "AND ok_etime > ? " : "")
                  + "ORDER BY created_datetime");

      pstmt.clearParameters();
      pstmt.setInt(1, wait_list_id);
      pstmt.setInt(2, date);
      if (!master && sindex.equals("0")) {
        pstmt.setInt(3, time);
      }

      ResultSet rs = pstmt.executeQuery();

      while (rs.next()) {

        wait_list_signup_id = rs.getInt("wait_list_signup_id");

        if (json_mode) {
          ((Map) waitlist_map.get("signups"))
              .put("signup_id_" + wait_list_signup_id, new LinkedHashMap());
          ((Map) ((Map) waitlist_map.get("signups")).get("signup_id_" + wait_list_signup_id))
              .put("players", new LinkedHashMap());
          ((Map) ((Map) waitlist_map.get("signups")).get("signup_id_" + wait_list_signup_id))
              .put("options", new HashMap());
        } else {
          out.print(
              "<tr align=center"
                  + ((alt_row) ? " style=\"background-color:white\"" : "")
                  + "><td>"
                  + pos
                  + "</td>");
          if (master) {
            out.println("<td>&nbsp;" + rs.getString("created_time") + "&nbsp;</td>");
          }
          out.print("<td align=left>");
        }
        // if (multi == 1) out.println("<td>" + rs.getString("course") + "</td>");

        //
        //  Display players in this signup
        //
        pstmt2 =
            con.prepareStatement(
                ""
                    + "SELECT * "
                    + "FROM wait_list_signups_players "
                    + "WHERE wait_list_signup_id = ? "
                    + "ORDER BY pos");

        pstmt2.clearParameters();
        pstmt2.setInt(1, wait_list_signup_id);

        ResultSet rs2 = pstmt2.executeQuery();

        tmp_found2 = false;
        player_index = 0;

        while (rs2.next()) {

          if (json_mode) {
            player_index++;
            ((Map)
                    ((Map)
                            ((Map) waitlist_map.get("signups"))
                                .get("signup_id_" + wait_list_signup_id))
                        .get("players"))
                .put("player_" + player_index, new HashMap());
            ((Map)
                    ((Map)
                            ((Map)
                                    ((Map) waitlist_map.get("signups"))
                                        .get("signup_id_" + wait_list_signup_id))
                                .get("players"))
                        .get("player_" + player_index))
                .put("player_name", rs2.getString("player_name"));
            ((Map)
                    ((Map)
                            ((Map)
                                    ((Map) waitlist_map.get("signups"))
                                        .get("signup_id_" + wait_list_signup_id))
                                .get("players"))
                        .get("player_" + player_index))
                .put("player_name", rs2.getString("player_name"));
            ((Map)
                    ((Map)
                            ((Map)
                                    ((Map) waitlist_map.get("signups"))
                                        .get("signup_id_" + wait_list_signup_id))
                                .get("players"))
                        .get("player_" + player_index))
                .put("cw", rs2.getString("cw"));
            ((Map)
                    ((Map)
                            ((Map)
                                    ((Map) waitlist_map.get("signups"))
                                        .get("signup_id_" + wait_list_signup_id))
                                .get("players"))
                        .get("player_" + player_index))
                .put("9hole", rs2.getInt("9hole"));
          } else {
            fullName = rs2.getString("player_name");
            cw = rs2.getString("cw");
            if (rs2.getInt("9hole") == 1) {
              cw = cw + "9";
            }
            if (tmp_found2) {
              out.print(",&nbsp; ");
            } else {
              out.print("&nbsp;");
            }
            out.print(fullName + " <font style=\"font-size:9px\">(" + cw + ")</font>");
            tmp_found2 = true;
          }
          sum_players++;
          nineHole = ""; // reset
        }

        pstmt2.close();

        if (json_mode) {

          ((Map)
                  ((Map)
                          ((Map) waitlist_map.get("signups"))
                              .get("signup_id_" + wait_list_signup_id))
                      .get("options"))
              .put("notes", notes);
          ((Map)
                  ((Map)
                          ((Map) waitlist_map.get("signups"))
                              .get("signup_id_" + wait_list_signup_id))
                      .get("options"))
              .put("created_time", rs.getInt("created_time"));
          ((Map)
                  ((Map)
                          ((Map) waitlist_map.get("signups"))
                              .get("signup_id_" + wait_list_signup_id))
                      .get("options"))
              .put("converted", rs.getInt("converted"));
          ((Map)
                  ((Map)
                          ((Map) waitlist_map.get("signups"))
                              .get("signup_id_" + wait_list_signup_id))
                      .get("options"))
              .put("converted_time", rs.getString("converted_time"));
          ((Map)
                  ((Map)
                          ((Map) waitlist_map.get("signups"))
                              .get("signup_id_" + wait_list_signup_id))
                      .get("options"))
              .put("converted_by", rs.getString("converted_by"));
          ((Map)
                  ((Map)
                          ((Map) waitlist_map.get("signups"))
                              .get("signup_id_" + wait_list_signup_id))
                      .get("options"))
              .put("start_time", SystemUtils.getSimpleTime(rs.getInt("ok_stime")));
          ((Map)
                  ((Map)
                          ((Map) waitlist_map.get("signups"))
                              .get("signup_id_" + wait_list_signup_id))
                      .get("options"))
              .put("end_time", SystemUtils.getSimpleTime(rs.getInt("ok_etime")));
          ((Map)
                  ((Map)
                          ((Map) waitlist_map.get("signups"))
                              .get("signup_id_" + wait_list_signup_id))
                      .get("options"))
              .put("wait_list_signup_id", wait_list_signup_id);
          ((Map)
                  ((Map)
                          ((Map) waitlist_map.get("signups"))
                              .get("signup_id_" + wait_list_signup_id))
                      .get("options"))
              .put("player_count", sum_players);
        } else {
          out.print("</td>");
          out.println(
              "<td>&nbsp;"
                  + SystemUtils.getSimpleTime(rs.getInt("ok_stime"))
                  + " - "
                  + SystemUtils.getSimpleTime(rs.getInt("ok_etime"))
                  + "&nbsp;</td>");
          out.println("<td>" + sum_players + "</td>");

          if (master) {

            tmp_converted = rs.getInt("converted") == 1;
            out.println("<td>" + ((tmp_converted) ? "Yes" : "No") + "</td>");
            out.println(
                "<td>" + ((tmp_converted) ? rs.getString("converted_time") : "&nbsp;") + "</td>");
            out.println(
                "<td>" + ((tmp_converted) ? rs.getString("converted_by") : "&nbsp;") + "</td>");
          }

          if (show_notes) {

            notes = rs.getString("notes").trim();
            if (notes.equals("")) {
              notes = "&nbsp;";
            }
            out.println("<td>" + notes + "</td>");
          }

          out.print("</tr>");
        }

        pos++;
        sum_players = 0;
        alt_row = alt_row == false;
      }

      pstmt.close();

    } catch (Exception exc) {

      SystemUtils.buildDatabaseErrMsg(
          "Error loading wait list signups.", exc.toString(), out, false);
    }

    if (json_mode) {

      ((Map) waitlist_map.get("options")).put("index", sindex);
      ((Map) waitlist_map.get("options")).put("wait_list_id", wait_list_id);
      ((Map) waitlist_map.get("options")).put("date", "" + mm + "/" + dd + "/" + yy);
      ((Map) waitlist_map.get("options")).put("name", name);
      ((Map) waitlist_map.get("options")).put("time", time);
      ((Map) waitlist_map.get("options")).put("jump", jump);
      ((Map) waitlist_map.get("options")).put("returnCourse", returnCourse);
      ((Map) waitlist_map.get("options")).put("course", course);
      ((Map) waitlist_map.get("options")).put("master", master);
      ((Map) waitlist_map.get("options")).put("report_date", report_date);
      ((Map) waitlist_map.get("options")).put("show_notes", show_notes);

    } else {

      out.println("</table><br>");

      out.println("<table align=center><tr>");

      out.println("<form action=\"Member_jump\" method=\"POST\" target=\"_top\">");
      out.println("<input type=\"hidden\" name=\"jump\" value=\"0\">");
      out.println("<input type=\"hidden\" name=\"index\" value=" + sindex + ">");
      out.println(
          "<input type=\"hidden\" name=\"course\" value=\""
              + ((!returnCourse.equals("")) ? returnCourse : course)
              + "\">");

      out.println("<td><input type=\"submit\" value=\"Tee Sheet\"></td></form>");

      out.println("<td>&nbsp;&nbsp;</td>");

      out.println("<form action=\"Member_waitlist\" method=\"POST\">");
      out.println("<input type=\"hidden\" name=\"waitListId\" value=\"" + wait_list_id + "\">");
      out.println("<input type=\"hidden\" name=\"date\" value=\"" + date + "\">");
      out.println("<input type=\"hidden\" name=\"day\" value=\"" + day_name + "\">");
      out.println("<input type=\"hidden\" name=\"index\" value=\"" + sindex + "\">");
      out.println("<input type=\"hidden\" name=\"course\" value=\"" + course + "\">");
      out.println("<input type=\"hidden\" name=\"returnCourse\" value=\"" + returnCourse + "\">");
      out.println("<input type=\"hidden\" name=\"jump\" value=\"" + jump + "\">");

      out.println("<td><input type=\"submit\" value=\"Return\"></td></form>");

      out.println("</tr></table></form>");

      out.println("<br>");
    }

    return waitlist_map;
  } // end viewSignups
Esempio n. 14
0
  // *****************************************************
  // Process the request from Member_sheet
  // *****************************************************
  //
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();

    PreparedStatement pstmt3 = null;
    Statement stmt = null;
    ResultSet rs = null;

    HttpSession session = SystemUtils.verifyMem(req, out); // check for intruder

    if (session == null) {

      return;
    }

    Connection con = SystemUtils.getCon(session); // get DB connection

    if (con == null) {

      out.println(SystemUtils.HeadTitle("DB Connection Error"));
      out.println(
          "<BODY bgcolor=\"#ccccaa\"><CENTER><img src=\"/" + rev + "/images/foretees.gif\"><BR>");
      out.println("<hr width=\"40%\">");
      out.println("<BR><BR><H3>Database Connection Error</H3>");
      out.println("<BR><BR>Unable to connect to the Database.");
      out.println("<BR>Please try again later.");
      out.println("<BR><BR>If problem persists, please contact customer support.");
      out.println("<BR><BR>");
      out.println("<font size=\"2\">");
      out.println("<form method=\"get\" action=\"javascript:history.back(1)\">");
      out.println("<input type=\"submit\" value=\"Return\" style=\"text-decoration:underline;\">");
      out.println("</form></font>");
      out.println("</CENTER></BODY></HTML>");
      out.close();
      return;
    }

    // Create Json response for later use
    Gson gson_obj = new Gson();
    // HashMap for later use by gson
    Map<String, Object> hashMap = new HashMap<String, Object>();
    // Check if we will only be return json data
    boolean json_mode = (req.getParameter("jsonMode")) != null;

    //
    // See if we are here to VIEW a wait list
    //
    if (req.getParameter("view") != null && req.getParameter("waitListId") != null) {

      if (json_mode) {
        out.print(gson_obj.toJson(viewSignups(req, out, con, true)));
      } else {
        viewSignups(req, out, con);
      }
      return;
    }

    String jump = "0"; // jump index - default to zero (for _sheet)

    if (req.getParameter("jump") != null) { // if jump index provided

      jump = req.getParameter("jump");
    }

    //
    //  Get this session's username
    //
    String club = (String) session.getAttribute("club");
    String user = (String) session.getAttribute("user");
    String name = (String) session.getAttribute("name"); // get users full name

    String sindex =
        req.getParameter("index"); //  index value of day (needed by Member_sheet when returning)
    String course = req.getParameter("course"); //  Name of Course
    String id = req.getParameter("waitListId"); //  uid of the wait list we are working with

    String returnCourse = "";

    if (req.getParameter("returnCourse") != null) { // if returnCourse provided

      returnCourse = req.getParameter("returnCourse");
    }

    String sdate = req.getParameter("date"); //  date of the request (yyyymmdd)
    String day_name = req.getParameter("day"); //  name of the day
    String p5 = req.getParameter("p5"); //  5-somes supported

    int index = 0;
    int wait_list_id = 0;
    int count = 0;

    int mm = 0;
    int dd = 0;
    int yy = 0;
    int date = 0;

    int time = SystemUtils.getTime(con);

    //
    //  Convert the values from string to int
    //
    try {

      wait_list_id = Integer.parseInt(id);
      index = Integer.parseInt(sindex);
      date = Integer.parseInt(sdate);
    } catch (NumberFormatException e) {
    }

    // get our date parts
    yy = date / 10000;
    mm = date - (yy * 10000);
    dd = mm - (mm / 100) * 100;
    mm = mm / 100;

    //
    //  parm block to hold the wait list parameters
    //
    parmWaitList parmWL = new parmWaitList(); // allocate a parm block

    parmWL.wait_list_id = wait_list_id;

    try {

      getWaitList.getParms(con, parmWL); // get the wait list config

      // if members can see the wait list then get the count
      if (parmWL.member_view == 1) {
        count = getWaitList.getListCount(wait_list_id, date, index, time, true, con);
      }

    } catch (Exception exp) {
      out.println(exp.getMessage());
    }

    int onlist = 0;

    try {

      onlist = getWaitList.onList(user, wait_list_id, date, con);

    } catch (Exception exp) {

      out.println(exp.toString());
    }

    String waitlist_notice = "";

    if (onlist == 0) {

      // not on the list

      try {

        // out.println("<pre>");
        waitlist_notice = getWaitList.getNotice(wait_list_id, con);
        // out.println("</pre>");

      } catch (Exception exp) {
      }
    }

    if (json_mode) {

      // If in json mode, add data to hashmap
      // New skin uses Member_waitlist in json mode exclusively.

      // Group the data we want to send to javascript in a hash map
      hashMap.put("wait_list_id", wait_list_id);
      hashMap.put("waitlist_notice", waitlist_notice);
      hashMap.put("date", "" + mm + "/" + dd + "/" + yy);
      hashMap.put("start_time", SystemUtils.getSimpleTime(parmWL.start_time));
      hashMap.put("end_time", SystemUtils.getSimpleTime(parmWL.end_time));
      hashMap.put("member_access", parmWL.member_access);
      hashMap.put("member_view", parmWL.member_view);
      hashMap.put("onlist", onlist);
      hashMap.put("index", index);
      hashMap.put("course", course);
      hashMap.put("count", count);
      hashMap.put("name", parmWL.name);

      out.print(gson_obj.toJson(hashMap));

      return;

    } else {
      // If not in json mode, output data directly to user

      out.println(
          "<!-- wait_list_id=" + wait_list_id + ", date=" + date + ", count=" + count + " -->");

      //
      // ********************************************************************
      //   Build a page to display Wait List details to member
      // ********************************************************************
      //
      out.println("<html>");
      out.println("<head>");
      out.println(
          "<link rel=\"stylesheet\" href=\"/"
              + rev
              + "/web utilities/foretees2.css\" type=\"text/css\">");
      out.println("<title>Member Wait List Registration Page</title>");
      out.println("</head>");

      out.println(
          "<body bgcolor=\"#ccccaa\" text=\"#000000\" link=\"#FFFFFF\" vlink=\"#FFFFFF\" alink=\"#FF0000\" topmargin=\"0\">");
      out.println("<font face=\"Arial, Helvetica, Sans-serif\"><center>");

      out.println(
          "<table border=\"0\" width=\"100%\" align=\"center\" valign=\"top\">"); // large table for
                                                                                  // whole page
      out.println("<tr><td valign=\"top\" align=\"center\">");

      out.println(
          "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" bgcolor=\"#336633\" align=\"center\" valign=\"top\">");
      out.println("<tr><td align=\"left\" width=\"300\">&nbsp;");
      out.println("<img src=\"/" + rev + "/images/foretees.gif\" border=0>");
      out.println("</td>");

      out.println("<td align=\"center\">");
      out.println("<font color=\"ffffff\" size=\"5\">Member Wait List Registration</font>");
      out.println("</font></td>");

      out.println("<td align=\"center\" width=\"300\">");
      out.println("<font size=\"1\" color=\"#ffffff\">Copyright&nbsp;</font>");
      out.println("<font size=\"2\" color=\"#ffffff\">&#169;&nbsp;</font>");
      out.println(
          "<font size=\"1\" color=\"#ffffff\">ForeTees, LLC <br> 2009 All rights reserved.");
      out.println("</font><font size=\"3\">");
      out.println(
          "<br><br><a href=\"/" + rev + "/member_help.htm\" target=\"_blank\"><b>Help</b></a>");
      out.println("</font></td>");
      out.println("</tr></table>");

      out.println("<br>");

      out.println("<table border=\"1\" cols=\"1\" bgcolor=\"#f5f5dc\" cellpadding=\"3\">");
      out.println("<tr>");
      out.println("<td width=\"620\" align=\"center\">");
      out.println("<font size=\"3\">");
      out.println("<b>Wait List Registration</b><br></font>");
      out.println("<font size=\"2\">");

      out.println(
          "The golf shop is running a wait list "
              + ((index == 0) ? "today" : "on this day")
              + ". ");
      out.println(
          "The wait list you've selected is running from <nobr>"
              + SystemUtils.getSimpleTime(parmWL.start_time)
              + "</nobr> till <nobr>"
              + SystemUtils.getSimpleTime(parmWL.end_time)
              + ".</nobr> ");

      out.println("Review the information below and click on 'Continue With Request' to continue.");
      out.println(
          "<br>OR click on 'Cancel Request' to delete the request. To return without changes click on 'Go Back'.");

      // out.println("<br><br><b>NOTE:</b> Only the person that originates the request will be
      // allowed to cancel it or change these values.");

      out.println("</font></td></tr>");
      out.println("</table>");

      out.println("<br><br>");

      out.println("<table border=0>");

      out.println("<tr><td><font size=\"2\">");
      out.println(
          "Date:&nbsp;&nbsp;<b>"
              + day_name
              + "&nbsp;&nbsp;"
              + mm
              + "/"
              + dd
              + "/"
              + yy
              + "</b></td>");
      out.println("<td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</td><td>");
      if (!course.equals("")) {
        out.println("<font size=\"2\">Course:&nbsp;&nbsp;<b>" + course + "</b></font>");
      }
      out.println("</td></tr>");

      out.println(
          "<tr><td><font size=\"2\">Wait List:&nbsp;&nbsp;<b>"
              + SystemUtils.getSimpleTime(parmWL.start_time)
              + " to "
              + SystemUtils.getSimpleTime(parmWL.end_time)
              + "</b></font></td>");

      out.println("<td></td>");

      out.println("<td><font size=\"2\">Signups:<b>");
      out.print(((parmWL.member_view == 1) ? count : "N/A"));
      out.println("</b></font></td>");

      out.println("</table>");

      out.println("<br>");

      out.println("<table border=\"0\" align=\"center\">"); // table to contain 2 tables below

      out.println("<tr>");

      out.println("<td align=\"center\" valign=\"top\">");

      out.println(
          "<table border=\"1\" bgcolor=\"#f5f5dc\" align=\"center\" width=\"500\" cellpadding=\"5\" cellspacing=\"5\">"); // table for request details
      out.println("<tr bgcolor=\"#336633\"><td align=\"center\">");
      out.println("<font color=\"ffffff\" size=\"3\">");
      out.println(
          "<b>" + ((!parmWL.name.equals("")) ? parmWL.name : "Wait List Information") + "</b>");
      out.println("</font></td></tr>");

      out.println("<tr>");

      out.println("<form action=\"Member_waitlist_slot\" method=\"post\">");
      out.println("<input type=\"hidden\" name=\"waitListId\" value=\"" + wait_list_id + "\">");
      out.println("<input type=\"hidden\" name=\"sdate\" value=\"" + date + "\">");
      out.println("<input type=\"hidden\" name=\"day\" value=\"" + day_name + "\">");
      out.println("<input type=\"hidden\" name=\"index\" value=\"" + sindex + "\">");
      out.println("<input type=\"hidden\" name=\"course\" value=\"" + course + "\">");
      out.println("<input type=\"hidden\" name=\"returnCourse\" value=\"" + returnCourse + "\">");
      out.println("<input type=\"hidden\" name=\"jump\" value=\"" + jump + "\">");

      out.println("<td><font size=\"2\"><br>");

      // see if they are already on the wait list
      out.println("<input type=\"hidden\" name=\"signupId\" value=\"" + onlist + "\">");

      if (onlist == 0) {

        // not on the list

        // out.println("The golf shop is running a wait list " + ((index == 0) ? "today": "on this
        // day") + ". ");
        // out.println("The wait list you've selected is running from " +
        // SystemUtils.getSimpleTime(parmWL.start_time) + " till " +
        // SystemUtils.getSimpleTime(parmWL.end_time) + ". ");

        // try {

        // out.println("<pre>");
        // out.print(getWaitList.getNotice(wait_list_id, con));
        // out.println("</pre>");
        out.print(waitlist_notice);

        // } catch (Exception exp) { }

        if (parmWL.member_access == 1) {
          out.println(
              "<br><p align=center><input type=submit value=\"Continue With Sign-up\" name=\"continue\"></p>");
        } else {
          out.println("<p align=center><b>Contact the golf shop to get on the wait list.</b></p>");
        }

      } else {

        // already on this list

        out.println(
            "<p align=center><b><i>You are already signed up for this wait list.</b></i></p>");

        if (parmWL.member_access == 1) {
          out.println(
              "<br><p align=center><input type=submit value=\"Modify Your Sign-up\" name=\"continue\"></p>");
        } else {
          out.println(
              "<p align=center><b>Contact the golf shop to make changes or cancel your entry.</b></p>");
        }
      }

      if (parmWL.member_view == 1 && count > 0) {

        out.println(
            "<p align=center><input type=button value=\"View Wait List\" name=\"view\" onclick=\"document.forms['frmView'].submit();\"></p>");
      }

      out.println("<br></font></td>");

      out.println("</table>");
      out.println("</form>");

      out.println("<br>");

      if (index == 999) {

        // out.println("<form action=\"Member_teelist\" method=\"GET\">");
        out.println("<form action=\"/" + rev + "/member_teemain.htm\" method=\"GET\">");

      } else if (index == 995) {

        // out.println("<form action=\"Member_teelist_list\" method=\"GET\">");
        out.println("<form action=\"/" + rev + "/member_teemain2.htm\" method=\"GET\">");

      } else {

        out.println("<form action=\"Member_jump\" method=\"POST\">");
        out.println("<input type=\"hidden\" name=\"jump\" value=" + jump + ">");
        out.println("<input type=\"hidden\" name=\"index\" value=" + index + ">");
        out.println(
            "<input type=\"hidden\" name=\"course\" value=\""
                + ((!returnCourse.equals("")) ? returnCourse : course)
                + "\">");
      }
      out.println("<font size=2>Return w/o Changes:</font><br>");
      out.println("<input type=\"submit\" value=\"Go Back\" name=\"cancel\"></form>");

      out.println("<form action=\"Member_waitlist\" method=\"GET\" name=frmView>");
      out.println("<input type=\"hidden\" name=\"view\" value=\"current\">");
      out.println("<input type=\"hidden\" name=\"waitListId\" value=\"" + wait_list_id + "\">");
      out.println("<input type=\"hidden\" name=\"sdate\" value=\"" + date + "\">");
      out.println("<input type=\"hidden\" name=\"name\" value=\"" + parmWL.name + "\">");
      // out.println("<input type=\"hidden\" name=\"day\" value=\"" + day_name + "\">");
      out.println("<input type=\"hidden\" name=\"index\" value=\"" + sindex + "\">");
      out.println("<input type=\"hidden\" name=\"course\" value=\"" + parmWL.course + "\">");
      out.println("<input type=\"hidden\" name=\"returnCourse\" value=\"" + returnCourse + "\">");
      out.println("<input type=\"hidden\" name=\"jump\" value=\"" + jump + "\">");
      ;
      out.println(
          "<input type=\"hidden\" name=\"start_time\" value=\"" + parmWL.start_time + "\">");
      out.println("<input type=\"hidden\" name=\"end_time\" value=\"" + parmWL.end_time + "\">");
      out.println("<input type=\"hidden\" name=\"day_name\" value=\"" + day_name + "\">");
      // out.println("<input type=submit value=\"View Sign-ups\" name=\"view\">");
      out.println("</form>");
    } // end json check
  } // end doPost
  @Override
  public void handle(ChannelHandlerContext ctx, HttpRequest request) {

    Tracker.getInstance().track(request);

    final String tenantId = request.getHeader("tenantId");

    if (!(request instanceof HTTPRequestWithDecodedQueryParams)) {
      sendResponse(
          ctx, request, "Missing query params: from, to, points", HttpResponseStatus.BAD_REQUEST);
      return;
    }

    final String body = request.getContent().toString(Constants.DEFAULT_CHARSET);

    if (body == null || body.isEmpty()) {
      sendResponse(
          ctx,
          request,
          "Invalid body. Expected JSON array of metrics.",
          HttpResponseStatus.BAD_REQUEST);
      return;
    }

    List<String> locators = new ArrayList<String>();
    try {
      locators.addAll(getLocatorsFromJSONBody(tenantId, body));
    } catch (Exception ex) {
      log.debug(ex.getMessage(), ex);
      sendResponse(ctx, request, ex.getMessage(), HttpResponseStatus.BAD_REQUEST);
      return;
    }

    if (locators.size() > maxMetricsPerRequest) {
      sendResponse(
          ctx,
          request,
          "Too many metrics fetch in a single call. Max limit is " + maxMetricsPerRequest + ".",
          HttpResponseStatus.BAD_REQUEST);
      return;
    }

    HTTPRequestWithDecodedQueryParams requestWithParams =
        (HTTPRequestWithDecodedQueryParams) request;
    final Timer.Context httpBatchMetricsFetchTimerContext = httpBatchMetricsFetchTimer.time();
    try {
      RollupsQueryParams params = PlotRequestParser.parseParams(requestWithParams.getQueryParams());
      Map<Locator, MetricData> results =
          getRollupByGranularity(
              tenantId,
              locators,
              params.getRange().getStart(),
              params.getRange().getStop(),
              params.getGranularity(tenantId));
      JSONObject metrics = serializer.transformRollupData(results, params.getStats());
      final JsonElement element = parser.parse(metrics.toString());
      final String jsonStringRep = gson.toJson(element);
      sendResponse(ctx, request, jsonStringRep, HttpResponseStatus.OK);
    } catch (InvalidRequestException e) {
      log.debug(e.getMessage());
      sendResponse(ctx, request, e.getMessage(), HttpResponseStatus.BAD_REQUEST);
    } catch (SerializationException e) {
      log.debug(e.getMessage(), e);
      sendResponse(ctx, request, e.getMessage(), HttpResponseStatus.INTERNAL_SERVER_ERROR);
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      sendResponse(ctx, request, e.getMessage(), HttpResponseStatus.INTERNAL_SERVER_ERROR);
    } finally {
      httpBatchMetricsFetchTimerContext.stop();
    }
  }
Esempio n. 16
0
  /** @return {@link DefaultHttpClient} instance. */
  private HttpClient createHttpClient(CouchDbProperties props) {
    DefaultHttpClient httpclient = null;
    try {
      SchemeSocketFactory ssf = null;
      if (props.getProtocol().equals("https")) {
        TrustManager trustManager =
            new X509TrustManager() {
              public void checkClientTrusted(X509Certificate[] chain, String authType)
                  throws CertificateException {}

              public void checkServerTrusted(X509Certificate[] chain, String authType)
                  throws CertificateException {}

              public X509Certificate[] getAcceptedIssuers() {
                return null;
              }
            };
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, new TrustManager[] {trustManager}, null);
        ssf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SSLSocket socket = (SSLSocket) ssf.createSocket(null);
        socket.setEnabledCipherSuites(new String[] {"SSL_RSA_WITH_RC4_128_MD5"});
      } else {
        ssf = PlainSocketFactory.getSocketFactory();
      }
      SchemeRegistry schemeRegistry = new SchemeRegistry();
      schemeRegistry.register(new Scheme(props.getProtocol(), props.getPort(), ssf));
      PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schemeRegistry);
      httpclient = new DefaultHttpClient(ccm);
      host = new HttpHost(props.getHost(), props.getPort(), props.getProtocol());
      context = new BasicHttpContext();
      // Http params
      httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
      httpclient
          .getParams()
          .setParameter(CoreConnectionPNames.SO_TIMEOUT, props.getSocketTimeout());
      httpclient
          .getParams()
          .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, props.getConnectionTimeout());
      int maxConnections = props.getMaxConnections();
      if (maxConnections != 0) {
        ccm.setMaxTotal(maxConnections);
        ccm.setDefaultMaxPerRoute(maxConnections);
      }
      if (props.getProxyHost() != null) {
        HttpHost proxy = new HttpHost(props.getProxyHost(), props.getProxyPort());
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
      }
      // basic authentication
      if (props.getUsername() != null && props.getPassword() != null) {
        httpclient
            .getCredentialsProvider()
            .setCredentials(
                new AuthScope(props.getHost(), props.getPort()),
                new UsernamePasswordCredentials(props.getUsername(), props.getPassword()));
        props.clearPassword();
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(host, basicAuth);
        context.setAttribute(ClientContext.AUTH_CACHE, authCache);
      }
      // request interceptor
      httpclient.addRequestInterceptor(
          new HttpRequestInterceptor() {
            public void process(final HttpRequest request, final HttpContext context)
                throws IOException {
              if (log.isInfoEnabled()) {
                RequestLine requestLine = request.getRequestLine();
                try {
                  log.info(
                      ">> "
                          + (new StringBuilder())
                              .append(">> ")
                              .append(requestLine.getMethod())
                              .append(" ")
                              .append(urlCodec.decode(requestLine.getUri()))
                              .toString());
                } catch (DecoderException e) {
                  log.error(e, e);
                }
              }
            }
          });
      // response interceptor
      httpclient.addResponseInterceptor(
          new HttpResponseInterceptor() {
            public void process(final HttpResponse response, final HttpContext context)
                throws IOException {
              validate(response);
              if (log.isInfoEnabled())
                log.info("<< Status: " + response.getStatusLine().getStatusCode());
            }
          });
    } catch (Exception e) {
      log.error("Error Creating HTTP client. " + e.getMessage());
      throw new IllegalStateException(e);
    }
    return httpclient;
  }