Ejemplo n.º 1
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    System.out.println("[Servlet3.doPost]");

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

    out.println("FILTER-REQUEST:" + request.getSession().getAttribute("FILTER-REQUEST"));
    out.println("FILTER-FORWARD:" + request.getSession().getAttribute("FILTER-FORWARD"));
    out.println("FILTER-INCLUDE:" + request.getSession().getAttribute("FILTER"));
  }
Ejemplo n.º 2
0
  // callRestfulApi - Calls restful API and returns results as a string
  public String callRestfulApi(
      String addr, HttpServletRequest request, HttpServletResponse response) {
    if (localCookie) CookieHandler.setDefault(cm);

    try {
      ByteArrayOutputStream output = new ByteArrayOutputStream();
      URL url = new URL(API_ROOT + addr);
      URLConnection urlConnection = url.openConnection();
      String cookieVal = getBrowserInfiniteCookie(request);
      if (cookieVal != null) {
        urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
      }
      IOUtils.copy(urlConnection.getInputStream(), output);
      String newCookie = getConnectionInfiniteCookie(urlConnection);
      if (newCookie != null && response != null) {
        setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
      }
      return output.toString();
    } catch (IOException e) {
      System.out.println(e.getMessage());
      return null;
    }
  } // TESTED
Ejemplo n.º 3
0
  // postToRestfulApi -
  // Note: params in the addr field need to be URLEncoded
  private String postToRestfulApi(
      String addr, String data, HttpServletRequest request, HttpServletResponse response) {
    if (localCookie) CookieHandler.setDefault(cm);
    String result = "";
    try {
      URLConnection connection = new URL(API_ROOT + addr).openConnection();
      String cookieVal = getBrowserInfiniteCookie(request);
      if (cookieVal != null) {
        connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
        connection.setDoInput(true);
      }
      connection.setDoOutput(true);
      connection.setRequestProperty("Accept-Charset", "UTF-8");

      // Post JSON string to URL
      OutputStream os = connection.getOutputStream();
      byte[] b = data.getBytes("UTF-8");
      os.write(b);

      // Receive results back from API
      InputStream is = connection.getInputStream();
      result = IOUtils.toString(is, "UTF-8");

      String newCookie = getConnectionInfiniteCookie(connection);
      if (newCookie != null && response != null) {
        setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
      }
    } catch (Exception e) {
      // System.out.println("Exception: " + e.getMessage());
    }
    return result;
  } // TESTED
Ejemplo n.º 4
0
 private void getPermissions(HttpServletRequest request, Role item) {
   String[] per = request.getParameterValues("permissions");
   item.clearPermissions();
   for (int i = 0; i < per.length; i++) {
     item.addPermission(Long.parseLong(per[i]));
   }
 }
Ejemplo n.º 5
0
 private void getPositions(HttpServletRequest request, Role item) {
   String[] pos = request.getParameterValues("positions");
   item.clearPositions();
   for (int i = 0; i < pos.length; i++) {
     item.addPosition(Long.parseLong(pos[i]));
   }
 }
Ejemplo n.º 6
0
  /**
   * This calls the itemselection.jsp and list all items available for a WorkOrder and a WorkOrder's
   * item list
   *
   * @param workorderid - the WO_ID of the parent WorkOrder
   * @param request - servlet request
   * @param response - servlet response
   */
  private void listProducts(
      long workorderId,
      WorkOrderDetailRemote workorderdetEJBean,
      HttpSession session,
      HttpServletRequest req,
      HttpServletResponse resp) {

    try {
      // If any product object is left over in session remove it
      session.removeValue("itemObj");

      // Create db connection for EJB
      workorderdetEJBean.connect();

      // Get the 2D Array which has the List of Items for the WorkOrder
      // grouped by the Billing System.
      Object[][] productList = workorderdetEJBean.getWorkOrderItems(workorderId);

      // Get the WorkOrder Object
      WorkOrder workorderObj = workorderdetEJBean.getWorkOrderInfo(workorderId);

      // Get the List of all Product Names for the WorkOrder
      String[] productNameList = workorderdetEJBean.getProdList(workorderId);

      for (int w = 0; w < productNameList.length; w++)
        USFEnv.getLog()
            .writeDebug("VALUES INSIDE productNameList is" + productNameList[w], this, null);

      // Set the attributes to the itemselection JSP
      req.setAttribute("productNameList", productNameList);
      req.setAttribute("productList", productList);
      req.setAttribute("workorderObj", workorderObj);

      // Release db connection for EJB
      workorderdetEJBean.release();

      // Include the JSP
      includeJSP(req, resp, ITEM_JSP_PATH, "itemselection");
      return;
    } catch (Exception e) {
      String errorMsg = "Fail to list products for a WORKORDER " + workorderId;
      USFEnv.getLog().writeCrit(errorMsg, this, e);
      errorJSP(req, resp, errorMsg);
    }
  }
Ejemplo n.º 7
0
 // getBrowserInfiniteCookie
 public static String getBrowserInfiniteCookie(HttpServletRequest request) {
   Cookie[] cookieJar = request.getCookies();
   if (cookieJar != null) {
     for (Cookie cookie : cookieJar) {
       if (cookie.getName().equals("infinitecookie")) {
         return cookie.getValue() + ";";
       }
     }
   }
   return null;
 } // TESTED
 private void endHereCommon() throws BeanException {
   // save EJB object handle in property
   if (ejb != null) {
     try {
       hPubAccessHandle = ejb.getHandle();
     } catch (Exception e) {
       String errMsg =
           (new Date(System.currentTimeMillis())).toString()
               + " HPS5955 "
               + this.getClass().getName()
               + ": ejb.getHandle(), ejb="
               + ejb
               + ": "
               + e.getClass().getName()
               + ": "
               + e.getMessage();
       System.err.println(errMsg);
       if (tracing == true) {
         traceArgs[0] = this;
         traceArgs[1] = errMsg;
         try {
           traceMethod.invoke(o, traceArgs);
         } catch (Exception x) {
         }
       }
       throw new BeanException(errMsg);
     }
   }
   // save ejb accessHandle and hpubLinkKey in HttpSession
   if ((oHttpServletRequest != null) && (outputProps != null)) {
     // a new HPubEjb2HttpSessionBindingListener object containing the ejb access
     // handle and hPubLinkKey for the connection is bound to the session using
     // a prefix and the ending connection state of the IO just processed.
     // This hPubLinkKey uniquely identifies the connection associated with the
     // IO chain for that HP Runtime JVM.
     // The ejb access handle is contained within the HPubEjb2HttpSessionBindingListener
     // object so that an ejb remove can be issued in the case where a session
     // timeout or session invalidation occurs for an incomplete IO chain.
     HttpSession theWebsession = oHttpServletRequest.getSession(true);
     if (theWebsession != null) {
       synchronized (theWebsession) {
         try {
           String theKey = KEY_WEBCONN + outputProps.getHPubEndChainName();
           hPubLinkKey = outputProps.getHPubLinkKey();
           theWebsession.setAttribute(
               theKey, new HPubEJB2HttpSessionBindingListener(hPubAccessHandle, hPubLinkKey));
           if (tracing == true) {
             traceArgs[0] = this;
             traceArgs[1] =
                 "theWebsession.setAttribute("
                     + theKey
                     + ",new HPubEJB2HttpSessionBindingListener("
                     + hPubAccessHandle
                     + ", "
                     + hPubLinkKey
                     + "))";
             try {
               traceMethod.invoke(o, traceArgs);
             } catch (Exception x) {
             }
           }
           if (auditing == true) {
             auditArgs[0] =
                 "\n---\nIN:"
                     + this.getClass().getName()
                     + " "
                     + theKey
                     + " "
                     + hPubAccessHandle
                     + " "
                     + hPubLinkKey
                     + " "
                     + theWebsession.getId();
             auditArgs[1] = theWebsession;
             try {
               auditMethod.invoke(o, auditArgs);
             } catch (Exception x) {
             }
           }
         } catch (Exception e) {
           hPubLinkKey = null; // set to null to force following error logic
         }
       }
     }
     // if an error occurred throw an exception to cause ejb remove to be issued.
     if ((theWebsession == null) || (hPubLinkKey == null)) {
       String errMsg =
           (new Date(System.currentTimeMillis())).toString()
               + " HPS5956 "
               + this.getClass().getName()
               + ": HttpServletRequest.getSession(true), hPubLinkKey="
               + hPubLinkKey;
       System.err.println(errMsg);
       if (tracing == true) {
         traceArgs[0] = this;
         traceArgs[1] = errMsg;
         try {
           traceMethod.invoke(o, traceArgs);
         } catch (Exception x) {
         }
       }
       throw new BeanException(errMsg);
     }
   }
   // send Event to User indicating that the Query request is complete
   RequestCompleteEvent hPubEvent = new RequestCompleteEvent(this);
   fireHPubReqCompleteEvent(hPubEvent);
   return;
 }
Ejemplo n.º 9
0
  // Process the request
  private String processRequest(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession();
    String userIDs = (String) session.getAttribute("user.id");
    userIDs = (userIDs != null && userIDs.compareTo(" ") > 0) ? userIDs : "0";
    long userID = Long.parseLong(userIDs);
    String command = request.getParameter("command");
    String template = request.getParameter("template");
    String pageHash = request.getParameter("pagehash");
    String pageTitle = request.getParameter("pagetitle");
    String pageDescription = request.getParameter("pagedescription");

    String outLine = "";
    String nextScript = request.getParameter("nextscript");
    OutputStream toClient;
    boolean success = false;

    // System.out.println("userid=" + userID + ", id=" + id + ", command=" + command);

    command = (command != null && command.compareTo(" ") > 0) ? command : "form";
    nextScript = (nextScript != null && nextScript.compareTo(" ") > 0) ? nextScript : "simple1.jsp";

    //    inputstring = (inputstring != null && inputstring.compareTo(" ") > 0) ? inputstring : "";

    DbConn myConn = null;
    try {

      Context initCtx = new InitialContext();
      // String csiSchema = (String) initCtx.lookup("java:comp/env/csi-schema-path");
      // String acronym = (String) initCtx.lookup("java:comp/env/SystemAcronym");
      myConn = new DbConn();
      String csiSchema = myConn.getSchemaPath();
      if (userID != 0) {
        if (command.equals("add")) {
          outLine = "";
        } else if (command.equals("update")) {
          outLine = "";
        } else if (command.equals("updatepage")) {
          UHash uPage = new UHash(pageHash, myConn);
          // System.out.println("Got Here 1");
          if (template.equals("simple1")) {
            TextItem title = new TextItem(uPage.get("title"), myConn);
            title.setText(pageTitle);
            title.save(myConn);
            TextItem description = new TextItem(uPage.get("description"), myConn);
            description.setText(pageDescription);
            description.save(myConn);
          } else if (template.equals("simple2")) {
          }

        } else if (command.equals("test")) {
          outLine = "test";
        }
        success = true;
      }

    } catch (IllegalArgumentException e) {
      outLine = outLine + "IllegalArgumentException caught: " + e.getMessage();
      ALog.logActivity(userID, "csi", 0, pageHash + " error: '" + outLine + "'");
      // log(outLine);
    } catch (NullPointerException e) {
      outLine = outLine + "NullPointerException caught: " + e.getMessage();
      ALog.logActivity(userID, "csi", 0, pageHash + " error: '" + outLine + "'");
      // log(outLine);
    }

    // catch (IOException e) {
    //    outLine = outLine + "IOException caught: " + e.getMessage();
    //    ALog.logActivity(userID, "csi", 0, pageHash + " error: '" + outLine + "'");
    //    //log(outLine);
    // }

    catch (Exception e) {
      outLine = outLine + "Exception caught: " + e.getMessage();
      ALog.logActivity(userID, "csi", 0, pageHash + " error: '" + outLine + "'");
      // log(outLine);
    } finally {
      try {
        generateResponse(outLine, command, nextScript, success, response);
      } catch (Exception i) {
      }

      myConn.release();
      // log("Test log message\n");
    }

    return outLine;
  }
  /** all processing methods end up here */
  private void startHereCommon() throws BeanException {
    // try to get the linkKey if already set in input properties
    try {
      hPubLinkKey = inputProps.getHPubLinkKey();
    } catch (Exception e) {
    }

    // if running in Web environment and either the ejb access handle or
    // the linkKey are null, try to get them from the HttpSession
    if (oHttpServletRequest != null) {
      HttpSession theWebsession = oHttpServletRequest.getSession(false);
      if (theWebsession != null) {
        synchronized (theWebsession) {
          try {
            if (tracing == true) {
              traceArgs[0] = this;
              traceArgs[1] = "HttpSession.getId()=" + theWebsession.getId();
              try {
                traceMethod.invoke(o, traceArgs);
              } catch (Exception x) {
              }
            }
            String theKey = KEY_WEBCONN + inputProps.getHPubStartChainName();
            // if linkKey or access handle is null try to get it from Websession
            HPubEJB2HttpSessionBindingListener sbl =
                (HPubEJB2HttpSessionBindingListener) theWebsession.getAttribute(theKey);
            if ((hPubLinkKey == null) && (sbl != null)) {
              hPubLinkKey = sbl.getLinkKey();
              if (tracing == true) {
                traceArgs[0] = this;
                traceArgs[1] = "HttpSession.getAttribute(hPubLinkKey)=" + hPubLinkKey;
                try {
                  traceMethod.invoke(o, traceArgs);
                } catch (Exception x) {
                }
              }
              inputProps.setHPubLinkKey(hPubLinkKey);
            }
            if ((hPubAccessHandle == null) && (sbl != null)) {
              hPubAccessHandle = sbl.getEjbHandle();
              if (tracing == true) {
                traceArgs[0] = this;
                traceArgs[1] = "HttpSession.getAttribute(hPubAccessHandle)=" + hPubAccessHandle;
                try {
                  traceMethod.invoke(o, traceArgs);
                } catch (Exception x) {
                }
              }
            }
            // set the ejb handle to null before removing the Session Binding
            // Listener object
            if (auditing == true) {
              if (sbl != null)
                auditArgs[0] =
                    "\n---\nOUT:"
                        + this.getClass().getName()
                        + " "
                        + theKey
                        + " "
                        + hPubAccessHandle
                        + " "
                        + hPubLinkKey
                        + " "
                        + theWebsession.getId();
              else // error - object not found in HttpSession
              auditArgs[0] =
                    "\n---\nERR:"
                        + this.getClass().getName()
                        + " "
                        + theKey
                        + " "
                        + theWebsession.getId();

              auditArgs[1] = theWebsession;
              try {
                auditMethod.invoke(o, auditArgs);
              } catch (Exception x) {
              }
            }
            if (sbl != null) sbl.setEjbHandle(null);
            theWebsession.removeAttribute(theKey);
          } catch (IllegalStateException e) {
          }
        }
      }
    }
    // if either of required properties are still null then the ejb cannot
    // be accessed - throw an exception.
    if ((hPubAccessHandle == null) || (hPubLinkKey == null)) {
      String errMsg =
          (new Date(System.currentTimeMillis())).toString()
              + " HPS5951 "
              + this.getClass().getName()
              + ": hPubAccessHandle==null || hPubLinkKey==null";
      System.err.println(errMsg);
      if (tracing == true) {
        traceArgs[0] = this;
        traceArgs[1] = errMsg;
        try {
          traceMethod.invoke(o, traceArgs);
        } catch (Exception x) {
        }
      }
      throw new BeanException(errMsg);
    } else {
      if (tracing == true) {
        traceArgs[0] = this;
        traceArgs[1] = "hPubAccessHandle=" + hPubAccessHandle + ",hPubLinkKey=" + hPubLinkKey;
        try {
          traceMethod.invoke(o, traceArgs);
        } catch (Exception x) {
        }
      }
    }

    // get the EJB object from the handle
    try {
      ejb =
          (com.ibm.HostPublisher.EJB.HPubEJB2)
              javax.rmi.PortableRemoteObject.narrow(
                  hPubAccessHandle.getEJBObject(), com.ibm.HostPublisher.EJB.HPubEJB2.class);
    } catch (Exception e) {
      String errMsg =
          (new Date(System.currentTimeMillis())).toString()
              + " HPS5952 "
              + this.getClass().getName()
              + ": getEJBObject(): "
              + e.getClass().getName()
              + ": "
              + e.getMessage();
      System.err.println(errMsg);
      if (tracing == true) {
        traceArgs[0] = this;
        traceArgs[1] = errMsg;
        try {
          traceMethod.invoke(o, traceArgs);
        } catch (Exception x) {
        }
      }
      throw new BeanException(errMsg);
    }
    // if ejb handle, go invoke the HPubEJB's main business method.
    if (ejb != null) {
      try {
        outputProps = (CrownCounselIndexGetList_Properties) ejb.processIO(inputProps);
        inputProps = outputProps;
        inputProps.setInitialCall(false);
      } catch (Exception e) {
        String errMsg =
            (new Date(System.currentTimeMillis())).toString()
                + " HPS5953 "
                + this.getClass().getName()
                + ": processIO("
                + inputProps.getClass().getName()
                + "): "
                + e.getClass().getName()
                + ": "
                + e.getMessage();
        System.err.println(errMsg);
        if (tracing == true) {
          traceArgs[0] = this;
          traceArgs[1] = errMsg;
          try {
            traceMethod.invoke(o, traceArgs);
          } catch (Exception x) {
          }
        }
        throw new BeanException(errMsg);
      }
    }
    endHereCommon();
    return;
  }
Ejemplo n.º 11
0
  // Process the request
  private String processRequest(HttpServletRequest request, HttpServletResponse response) {
    String command = request.getParameter("command");
    String id = request.getParameter("id");
    String description = request.getParameter("description");
    String status = request.getParameter("rstatus");
    status = (status != null && status.compareTo(" ") > 0) ? status : null;
    String outLine = "";
    // String nextScript = "home.jsp";
    String nextScript = request.getParameter("nextscript");
    OutputStream toClient;
    HttpSession session = request.getSession();
    boolean success = false;
    String userIDs = (String) session.getAttribute("user.id");
    long userID = Long.parseLong(userIDs);

    command = (command != null && command.compareTo(" ") > 0) ? command : "form";
    nextScript = (nextScript != null && nextScript.compareTo(" ") > 0) ? nextScript : "roles.jsp";

    //    inputstring = (inputstring != null && inputstring.compareTo(" ") > 0) ? inputstring : "";

    DbConn myConn = null;
    try {

      Context initCtx = new InitialContext();
      // String csiSchema = (String) initCtx.lookup("java:comp/env/csi-schema-path");
      String acronym = (String) initCtx.lookup("java:comp/env/SystemAcronym");
      myConn = new DbConn();
      String csiSchema = myConn.getSchemaPath();
      if (command.equals("add")) {
        Role item = new Role();
        item.setDescription(description);
        item.setStatus(status);
        getPermissions(request, item);
        getPositions(request, item);
        item.add(myConn, userID);
        GlobalMembership.refresh(myConn);
        success = true;
        outLine = "";

      } else if (command.equals("update")) {
        Role item = new Role(myConn, Long.parseLong(id));
        item.setDescription(description);
        item.setStatus(status);
        getPermissions(request, item);
        getPositions(request, item);
        item.save(myConn, userID);
        GlobalMembership.refresh(myConn);
        success = true;
        outLine = "";
      } else if (command.equals("drop")) {
        Role item = new Role(myConn, Long.parseLong(id));
        item.drop(myConn, userID);
        success = true;
        outLine = "Role " + item.getDescription() + " Removed";
      } else if (command.equals("test")) {
        outLine = "test";
      }

    } catch (IllegalArgumentException e) {
      outLine = outLine + "IllegalArgumentException caught: " + e.getMessage();
      ALog.logActivity(userID, "csi", 0, "Role error: '" + outLine + "'");
      // log(outLine);
    } catch (NullPointerException e) {
      outLine = outLine + "NullPointerException caught: " + e.getMessage();
      ALog.logActivity(userID, "csi", 0, "Role error: '" + outLine + "'");
      // log(outLine);
    }

    // catch (IOException e) {
    //    outLine = outLine + "IOException caught: " + e.getMessage();
    //    ALog.logActivity(userID, "csi", 0, "Role error: '" + outLine + "'");
    //    //log(outLine);
    // }

    catch (Exception e) {
      outLine = outLine + "Exception caught: " + e.getMessage();
      ALog.logActivity(userID, "csi", 0, "Role error: '" + outLine + "'");
      // log(outLine);
    } finally {
      try {
        generateResponse(outLine, command, nextScript, success, response);
      } catch (Exception i) {
      }

      myConn.release();
      // log("Test log message\n");
    }

    return outLine;
  }
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html");
      pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("<!--%@ page errorPage=\"/error.jsp\" %-->\n");

      response.setHeader("Pragma", "no-cache"); // HTTP 1.0
      response.setDateHeader("Expires", 0);
      response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1

      String _adminid = "";
      String _adminname = "";
      String _admintype = "";
      String _admingroup = "";
      String _approval = "";
      String _adminclass = "";
      String _adminmail = "";

      try {

        _adminid = (String) session.getAttribute("adminid");

        if (_adminid == null || _adminid.length() == 0 || _adminid.equals("null")) {
          response.sendRedirect("/admin/login_first.html");
          return;
        }

        _adminname = (String) session.getAttribute("adminname");
        _admintype = (String) session.getAttribute("admintype");
        _admingroup = (String) session.getAttribute("admingroup");
        _approval = (String) session.getAttribute("approval");
        _adminclass = (String) session.getAttribute("adminclass");
        _adminmail = (String) session.getAttribute("admin_email");
        // session.setMaxInactiveInterval(60*60);

      } catch (Exception e) {
        response.sendRedirect("/admin/login_first.html");
        return;
      }

      out.write('\n');
      out.write('\n');
      out.write('\n');

      String password = request.getParameter("password");
      String fromURL = request.getParameter("fromURL");
      String oldPassword = "";

      String sql = "";
      int iCnt = 0;
      boolean isSucceeded = false;
      String strMsg = "";
      Connection conn = null;
      MatrixDataSet matrix = null;
      DataProcess dataProcess = null;
      PreparedStatement pstmt = null;

      String targetUrl = "";

      try {

        if (password.equals("1111")) {
          throw new UserDefinedException(
              "The new password is not acceptable. Change your password.");
        }

        Context ic = new InitialContext();
        DataSource ds = (DataSource) ic.lookup("java:comp/env/jdbc/scm");
        conn = ds.getConnection();
        matrix = new dbconn.MatrixDataSet();
        dataProcess = new DataProcess();

        sql =
            " select  password " + " from    admin_01t " + " where   adminid = '" + _adminid + "' ";

        iCnt = dataProcess.RetrieveData(sql, matrix, conn);

        if (iCnt > 0) {
          oldPassword = matrix.getRowData(0).getData(0);
        } else {
          throw new UserDefinedException("Can't find User Information.");
        }

        if (password.equals(oldPassword)) {
          throw new UserDefinedException(
              "The new password is not acceptable. Change your password.");
        }

        // update ó¸®...
        int idx = 0;
        conn.setAutoCommit(false);

        sql =
            " update  admin_01t "
                + " set     password = ?, pw_date = sysdate() "
                + " where   adminid = ? ";

        pstmt = conn.prepareStatement(sql);
        pstmt.setString(++idx, password);
        pstmt.setString(++idx, _adminid);

        iCnt = pstmt.executeUpdate();

        if (iCnt != 1) {
          throw new UserDefinedException("Password update failed.");
        }

        conn.commit();
        isSucceeded = true;

      } catch (UserDefinedException ue) {
        try {
          conn.rollback();
        } catch (Exception ex) {
        }

        strMsg = ue.getMessage();
      } catch (Exception e) {
        try {
          conn.rollback();
        } catch (Exception ex) {
        }

        System.out.println("Exception /admin/resetAdminPasswd : " + e.getMessage());
        throw e;
      } finally {
        if (pstmt != null) {
          try {
            pstmt.close();
          } catch (Exception e) {
          }
        }

        if (conn != null) {
          try {
            conn.setAutoCommit(true);
          } catch (Exception e) {
          }
          conn.close();
        }
      }

      // °á°ú ¸Þ½ÃÁö ó¸®
      if (isSucceeded) {
        // where to go?
        if (fromURL.equals("menu")) {
          targetUrl = "";
        } else {
          targetUrl = "/admin/index2.jsp";
        }
        strMsg = "The data are successfully processed.";
      } else {
        strMsg = "The operation failed.\\n" + strMsg;
        targetUrl = "/admin/resetAdminPasswdForm.jsp";
      }

      out.write("\n");
      out.write("<html>\n");
      out.write("<head>\n");
      out.write("<title></title>\n");
      out.write("<link href=\"/common/css/style.css\" rel=\"stylesheet\" type=\"text/css\">\n");
      out.write("</head>\n");
      out.write("<body leftmargin='0' topmargin='0' marginwidth='0' marginheight='0'>\n");
      out.write("<form name=\"form1\" method=\"post\" action=\"");
      out.print(targetUrl);
      out.write("\">\n");
      out.write("<input type='hidden' name='fromURL' value='");
      out.print(fromURL);
      out.write("'>\n");
      out.write("</form>\n");
      out.write("<script language=\"javascript\">\n");
      if (targetUrl.length() > 0) {
        out.write("\n");
        out.write("  alert('");
        out.print(strMsg);
        out.write("');\n");
        out.write("  document.form1.submit();\n");
      }
      out.write("\n");
      out.write("</script>\n");
      out.write("<table width='840' border='0' cellspacing='0' cellpadding='0'><tr><td>\n");
      out.write("\n");
      out.write("<table width='99%' border='0' cellspacing='0' cellpadding='0'>\n");
      out.write("<tr>\n");
      out.write("  <td height='15' colspan='2'></td>\n");
      out.write("</tr>\n");
      out.write("<tr>\n");
      out.write("  <td width='3%'><img src='/img/title_icon.gif'></td>\n");
      out.write("  <td width='*' class='left_title'>Password Change</td>\n");
      out.write("</tr>\n");
      out.write("<tr>\n");
      out.write("  <td width='100%' height='2' colspan='2'><hr width='100%'></td>\n");
      out.write("</tr>\n");
      out.write("<tr>\n");
      out.write("  <td height='10' colspan='2'></td>\n");
      out.write("</tr>\n");
      out.write("</table>\n");
      out.write("\n");
      out.write("<table width='90%' border='0' cellspacing='0' cellpadding='0' align='center'>\n");
      out.write("<tr>\n");
      out.write("  <td width='100%' align='center'><img border=\"0\" src=\"/img/pass.jpg\">\n");
      out.write("    <br><br>\n");
      out.write("    <b>The Password has been changed successfully.</b></td>\n");
      out.write("</tr>\n");
      out.write("</table>\n");

      out.println(CopyRightLogo());

      out.write("\n");
      out.write("</tr></td></table>\n");
      out.write("</body>\n");
      out.write("</html>");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)) {
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try {
            out.clearBuffer();
          } catch (java.io.IOException e) {
          }
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
  protected void sendPasswordResetEMail(
      HttpServletRequest request, ICFSecuritySecUserObj resetUser, ICFSecurityClusterObj cluster)
      throws AddressException, MessagingException, NamingException {

    final String S_ProcName = "sendPasswordResetEMail";

    Properties props = System.getProperties();
    String clusterDescription = cluster.getRequiredDescription();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAsterisk26SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(
              getClass(), S_ProcName, 0, "JNDI lookup for CFAsterisk26SmtpEmailFrom");
    }

    smtpUsername = (String) ctx.lookup("java:comp/env/CFAsterisk26SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(
              getClass(), S_ProcName, 0, "JNDI lookup for CFAsterisk26SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFAsterisk26SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(
              getClass(), S_ProcName, 0, "JNDI lookup for CFAsterisk26SmtpPassword");
    }

    Session emailSess =
        Session.getInstance(
            props,
            new Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpUsername, smtpPassword);
              }
            });

    String thisURI =
        request.getScheme()
            + "://"
            + request.getServerName()
            + ":"
            + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID resetUUID = resetUser.getOptionalPasswordResetUuid();

    String msgBody =
        "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n"
            + "<HTML>\n"
            + "<BODY>\n"
            + "<p>\n"
            + "You requested a password reset for "
            + resetUser.getRequiredEMailAddress()
            + " used for accessing "
            + clusterDescription
            + ".\n"
            + "<p>"
            + "Please click on the following link to reset your password:<br>\n"
            + "<A HRef=\""
            + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID="
            + resetUUID.toString()
            + "\">"
            + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID="
            + resetUUID.toString()
            + "</A>\n"
            + "<p>"
            + "Or click on the following link to cancel the reset request:<br>\n"
            + "<A HRef=\""
            + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID="
            + resetUUID.toString()
            + "\">"
            + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID="
            + resetUUID.toString()
            + "</A>\n"
            + "</BODY>\n"
            + "</HTML>\n";

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject(
        "You requested a password reset for your account with " + clusterDescription + "?");
    msg.setContent(msgBody, "text/html");
    msg.setSentDate(new Date());
    msg.saveChanges();

    Transport.send(msg);
  }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    final String S_ProcName = "doPost";

    ICFAsteriskSchemaObj schemaObj;
    HttpSession sess = request.getSession(false);
    if (sess == null) {
      sess = request.getSession(true);
      schemaObj = new CFAsteriskSchemaPooledObj();
      sess.setAttribute("SchemaObj", schemaObj);
    } else {
      schemaObj = (ICFAsteriskSchemaObj) sess.getAttribute("SchemaObj");
      if (schemaObj == null) {
        throw CFLib.getDefaultExceptionFactory()
            .newNullArgumentException(getClass(), S_ProcName, 0, "schemaObj");
      }
    }

    ICFAsteriskSchema dbSchema = null;
    try {
      CFSecurityAuthorization auth = schemaObj.getAuthorization();
      if (auth != null) {
        response.sendRedirect("CFAsteriskSMWarSecurityMainHtml");
        return;
      }

      dbSchema = (ICFAsteriskSchema) CFAsteriskSchemaPool.getSchemaPool().getInstance();
      schemaObj.setBackingStore(dbSchema);
      schemaObj.beginTransaction();
      ICFSecuritySecUserObj systemUser =
          schemaObj.getSecUserTableObj().readSecUserByULoginIdx("system");
      String passwordHash = systemUser.getRequiredPasswordHash();
      if ((passwordHash == null)
          || (passwordHash.length() <= 0)
          || passwordHash.equals("bootstrap")) {
        response.sendRedirect("CFAsteriskSMWarSetSystemPasswordHtml");
      }

      ICFSecurityClusterObj resolvedCluster;
      ICFSecuritySysClusterObj sysCluster =
          schemaObj.getSysClusterTableObj().readSysClusterByIdIdx(1, false);
      if (sysCluster == null) {
        throw CFLib.getDefaultExceptionFactory()
            .newNullArgumentException(getClass(), S_ProcName, 0, "sysCluster");
      }
      resolvedCluster = sysCluster.getRequiredContainerCluster();
      if (resolvedCluster == null) {
        throw CFLib.getDefaultExceptionFactory()
            .newNullArgumentException(getClass(), S_ProcName, "resolvedCluster");
      }
      String clusterDomainName = resolvedCluster.getRequiredFullDomainName();
      String clusterDescription = resolvedCluster.getRequiredDescription();

      String loginId = (String) request.getParameter("LoginId");
      if ((loginId == null) || (loginId.length() <= 0)) {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
        out.println("<HTML>");
        out.println("<BODY>");
        out.println(
            "<form method=\"post\" formaction=\"CFAsteriskSMWarRequestResetPasswordHtml\">");
        out.println(
            "<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
        out.println("<H2 style=\"text-align:center\">ERROR</H2>");
        out.println("<p style=\"text-align:center\">");
        out.println("You must specify a login id to reset.");
        out.println("<p style=\"text-align:center\">");
        out.println("Enter the login you'd like to request a password reset for.");
        out.println("<p>");
        out.println("<center>");
        out.println("<table style=\"width:60%\">");
        out.println(
            "<tr><th style=\"text-align:left\">Login Id:</th><td><input type=\"text\" name=\"LoginId\"/></td></tr>");
        out.println(
            "<tr><td colspan=\"2\" style=\"text-align:center\"><button type=\"submit\" name=\"Ok, Request Password Reset\"\">Ok</button></td></tr>");
        out.println(
            "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"CFAsteriskSMWarLoginHtml\">Back to "
                + clusterDescription
                + " Security Manager Login</A></td></tr>");
        out.println("</table>");
        out.println("</center>");
        out.println("</form>");
        out.println("</BODY>");
        out.println("</HTML>");
        return;
      }

      ICFSecuritySecUserObj authenticatingUser =
          schemaObj.getSecUserTableObj().readSecUserByULoginIdx(loginId, true);
      if (authenticatingUser == null) {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
        out.println("<HTML>");
        out.println("<BODY>");
        out.println(
            "<form method=\"post\" formaction=\"CFAsteriskSMWarRequestResetPasswordHtml\">");
        out.println(
            "<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
        out.println("<H2 style=\"text-align:center\">ERROR</H2>");
        out.println("<p style=\"text-align:center\">");
        out.println("Login id not found.");
        out.println("<p style=\"text-align:center\">");
        out.println("Enter the login you'd like to request a password reset for.");
        out.println("<p>");
        out.println("<center>");
        out.println("<table style=\"width:60%\">");
        out.println(
            "<tr><th style=\"text-align:left\">Login Id:</th><td><input type=\"text\" name=\"LoginId\"/></td></tr>");
        out.println(
            "<tr><td colspan=\"2\" style=\"text-align:center\"><button type=\"submit\" name=\"Ok, Request Password Reset\"\">Ok</button></td></tr>");
        out.println(
            "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"CFAsteriskSMWarLoginHtml\">Back to "
                + clusterDescription
                + " Security Manager Login</A></td></tr>");
        out.println("</table>");
        out.println("</center>");
        out.println("</form>");
        out.println("</BODY>");
        out.println("</HTML>");
        return;
      }

      if (null != authenticatingUser.getOptionalPasswordResetUuid()) {

        sendPasswordResetEMail(request, authenticatingUser, resolvedCluster);

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
        out.println("<HTML>");
        out.println("<BODY>");
        out.println(
            "<form method=\"post\" formaction=\"CFAsteriskSMWarRequestResetPasswordHtml\">");
        out.println(
            "<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
        out.println("<H2 style=\"text-align:center\">INFO</H2>");
        out.println("<p style=\"text-align:center\">");
        out.println("Password reset email resent.");
        out.println("<center>");
        out.println("<table style=\"width:60%\">");
        out.println(
            "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"CFAsteriskSMWarLoginHtml\">Back to "
                + clusterDescription
                + " Security Manager Login</A></td></tr>");
        out.println("</table>");
        out.println("</center>");
        out.println("</form>");
        out.println("</BODY>");
        out.println("</HTML>");
      }

      ICFSecurityClusterObj systemCluster =
          schemaObj.getClusterTableObj().readClusterByUDomainNameIdx("system");
      ICFSecurityTenantObj systemTenant =
          schemaObj
              .getTenantTableObj()
              .readTenantByUNameIdx(systemCluster.getRequiredId(), "system");
      ICFSecuritySecSessionObj systemSession = schemaObj.getSecSessionTableObj().newInstance();
      ICFSecuritySecSessionEditObj editSystemSession =
          (ICFSecuritySecSessionEditObj) systemSession.beginEdit();
      editSystemSession.setRequiredContainerSecUser(systemUser);
      editSystemSession.setRequiredStart(Calendar.getInstance());
      systemSession = editSystemSession.create();
      editSystemSession.endEdit();

      auth = new CFSecurityAuthorization();
      auth.setSecCluster(systemCluster);
      auth.setSecTenant(systemTenant);
      auth.setSecSession(systemSession);
      schemaObj.setAuthorization(auth);

      ICFSecuritySecUserEditObj editAuthenticatingUser = authenticatingUser.beginEdit();
      editAuthenticatingUser.setOptionalPasswordResetUuid(UUID.randomUUID());
      editAuthenticatingUser.update();
      editAuthenticatingUser.endEdit();

      editSystemSession = (ICFSecuritySecSessionEditObj) systemSession.beginEdit();
      editSystemSession.setOptionalFinish(Calendar.getInstance());
      editSystemSession.update();
      editSystemSession.endEdit();

      schemaObj.setAuthorization(null);

      schemaObj.commit();

      sendPasswordResetEMail(request, authenticatingUser, resolvedCluster);

      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
      out.println("<HTML>");
      out.println("<BODY>");
      out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarRequestResetPasswordHtml\">");
      out.println(
          "<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
      out.println("<H2 style=\"text-align:center\">INFO</H2>");
      out.println("<p style=\"text-align:center\">");
      out.println(
          "Password reset email sent.  Please use the links in the email to set a new password or to cancel the request.");
      out.println("<center>");
      out.println("<table style=\"width:60%\">");
      out.println(
          "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"CFAsteriskSMWarLoginHtml\">Back to "
              + clusterDescription
              + " Security Manager Login</A></td></tr>");
      out.println("</table>");
      out.println("</center>");
      out.println("</form>");
      out.println("</BODY>");
      out.println("</HTML>");
    } catch (MessagingException e) {
      throw CFLib.getDefaultExceptionFactory()
          .newRuntimeException(
              getClass(), S_ProcName, "Caught MessagingException -- " + e.getMessage(), e);
    } catch (NamingException e) {
      throw CFLib.getDefaultExceptionFactory()
          .newRuntimeException(
              getClass(), S_ProcName, "Caught NamingException -- " + e.getMessage(), e);
    } catch (RuntimeException e) {
      throw CFLib.getDefaultExceptionFactory()
          .newRuntimeException(
              getClass(), S_ProcName, "Caught RuntimeException -- " + e.getMessage(), e);
    } finally {
      if (dbSchema != null) {
        try {
          if (schemaObj.isTransactionOpen()) {
            schemaObj.rollback();
          }
        } catch (RuntimeException e) {
        }
        schemaObj.setBackingStore(null);
        CFAsteriskSchemaPool.getSchemaPool().releaseInstance(dbSchema);
      }
    }
  }
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    JspFactory _jspxFactory = null;
    javax.servlet.jsp.PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;

    try {
      _jspxFactory = JspFactory.getDefaultFactory();
      response.setContentType("text/html;charset=ISO-8859-1");
      pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\n\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n\n");

      // This JSP handles cross context communications from wt-monitor
      // to wt-core for use in accessing wt-core functionality that is
      // needed in WTnav-tree.jsp.

      // Assign a pooled DB connection handle
      Context ctx = new InitialContext();
      DataSource ds = (DataSource) ctx.lookup(WTConstants.WATCHTOWERDB_CONN);
      int iIndex = 6100;
      GraphViewManager graphman = new GraphViewManager(ds);
      // Vector views = graphman.getViews();

      Vector views = new Vector();
      WTOrganization[] orgs = null;

      WTAccountCredentials ac =
          (WTAccountCredentials)
              request.getSession().getAttribute(WTAccountCredentials.SESSION_ATTRIBUTE_AC);
      if (ac != null) {
        // WTOrganization[] orgs = null;
        int selectedOrg = ac.getCurrentManagedId();

        boolean siteUser = ac.getIsSiteUser();
        int userId = ac.getUserId();

        // Get list of organizations for the current user
        if (siteUser) {
          try {
            orgs = DAOImpl.OrgDAO.getWTOrganization();
          } catch (Exception e) {
            e.printStackTrace();
          }
        } else {
          if (!(userId < 0)) {
            try {
              orgs = DAOImpl.OrgDAO.getWTOrganizationsByUser(userId);
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        }

        // Get the list of actively managed nodes
        if (selectedOrg == WTAccountCredentials.ALL_ORGS) {
          if (siteUser) {
            views = graphman.getViews();
          } else {
            if (orgs != null) {
              int[] orgsIds = new int[orgs.length];
              for (int i = 0; i < orgs.length; i++) {
                orgsIds[i] = orgs[i].getID();
              }
              views = graphman.getViews(orgsIds);
            }
          }
        } else {
          views = graphman.getViews(selectedOrg);
        }
      }

      // My Graph Views is an experimental feature and is commented out until all kinks are worked
      // out. LS

      String strOutput = null;
      // 	if( views.size()==0 ) {
      //		strOutput = "nav.add(6100, 6000, 'My Graph Views', '/wt-monitor/report/index.jsp', 'My
      // Customized Graph Views', 'mainContentsFrame', icon16_basedir + 'bs_chart.gif',
      // icon16_basedir + 'bs_chart.gif', '');\r\n";
      //	} else {
      //		strOutput = "nav.add(6100, 6000, 'My Graph Views', '', 'My Customized Graph Views',
      // 'mainContentsFrame', icon16_basedir + 'bs_chart.gif', icon16_basedir + 'bs_chart.gif',
      // '');\r\n";
      //	}
      //	for (int i=0; i<views.size(); i++)
      //	{
      //		iIndex++;
      //		String strViewName = ((GraphViewJB)views.elementAt(i)).getName();
      //		int strOrgId = ((GraphViewJB)views.elementAt(i)).getOrgId();
      //		String orgName = null;
      //       for(int j=0;j<orgs.length;j++){
      //	        if(orgs[j].getID() != -1 && orgs[j].getID() == strOrgId){
      //	        	orgName = orgs[j].getName();
      //	        }
      //		}
      //
      //		strOutput +="nav.add(" + iIndex +
      //		            ", 6100, '" + strViewName +
      //		            "', 'javascript:
      // PopupCenteredWindow(\\'/wt-core/jsp/sysmon/graphview/GraphView.jsp?view=" + strViewName +
      // "&orgname="+orgName +"&start=01&end=02" + "\\', \\'graphview\\', \\'yes\\', \\'yes\\',
      // \\'yes\\', \\'900\\', \\'1010\\'); location.href=\\'/wt-monitor/wt-jsp/WTnav-tree.jsp\\';',
      // 'Open " + strViewName + " Graph View', '', icon16_basedir + 'bs_chart.gif', icon16_basedir
      // + 'bs_chart.gif', '');\r\n";
      // }

      out.write("\n\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n\n");
      out.print(strOutput);
      out.write("\n");
    } catch (Throwable t) {
      out = _jspx_out;
      if (out != null && out.getBufferSize() != 0) out.clearBuffer();
      if (pageContext != null) pageContext.handlePageException(t);
    } finally {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(pageContext);
    }
  }
Ejemplo n.º 16
0
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    PageContext pageContext = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html; charset=ISO-8859-1");
      pageContext = _jspxFactory.getPageContext(this, request, response, null, false, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("<!--\n");
      out.write("Copyright 2012 The Infinit.e Open Source Project\n");
      out.write("\n");
      out.write("Licensed under the Apache License, Version 2.0 (the \"License\");\n");
      out.write("you may not use this file except in compliance with the License.\n");
      out.write("You may obtain a copy of the License at\n");
      out.write("\n");
      out.write("  http://www.apache.org/licenses/LICENSE-2.0\n");
      out.write("\n");
      out.write("Unless required by applicable law or agreed to in writing, software\n");
      out.write("distributed under the License is distributed on an \"AS IS\" BASIS,\n");
      out.write("WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n");
      out.write("See the License for the specific language governing permissions and\n");
      out.write("limitations under the License.\n");
      out.write("-->\n");
      out.write("\n");
      out.write("\n");
      out.write("<!--\n");
      out.write("Copyright 2012 The Infinit.e Open Source Project\n");
      out.write("\n");
      out.write("Licensed under the Apache License, Version 2.0 (the \"License\");\n");
      out.write("you may not use this file except in compliance with the License.\n");
      out.write("You may obtain a copy of the License at\n");
      out.write("\n");
      out.write("  http://www.apache.org/licenses/LICENSE-2.0\n");
      out.write("\n");
      out.write("Unless required by applicable law or agreed to in writing, software\n");
      out.write("distributed under the License is distributed on an \"AS IS\" BASIS,\n");
      out.write("WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n");
      out.write("See the License for the specific language governing permissions and\n");
      out.write("limitations under the License.\n");
      out.write("-->\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write('\n');
      out.write('\n');
      out.write('\n');

      // !---------- Read AppConstants.js to get the API_ROOT value  ----------!
      if (API_ROOT == null) {
        URL baseUrl =
            new URL(request.getScheme(), request.getServerName(), request.getServerPort(), "");
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("javascript");
        String appConstantFile = null;

        InputStream in = null;
        // Use file from local deployment always
        try {
          in = new FileInputStream(application.getRealPath("/") + "AppConstants.js");
          appConstantFile = IOUtils.toString(in);
        } catch (Exception e) {
          // System.out.println("Exception: " + e.getMessage());
        }

        // Eval the file as JavaScript through or JS engine and call getEndPointUrl
        try {
          engine.eval(appConstantFile);
          engine.eval("output = getEndPointUrl();");
          API_ROOT = (String) engine.get("output");
        } catch (Exception e) {
          // System.out.println("Exception: " + e.getMessage());
        }
        if (null == API_ROOT) {
          // Default to localhost
          API_ROOT = "http://localhost:8080/api/";
        }

        if (API_ROOT.contains("localhost")) {
          localCookie = true;
        } else {
          localCookie = false;
        }
      }

      boolean isLoggedIn = false;
      messageToDisplay = "";

      // Page request is a post back from the login form
      if (request.getParameter("username") != null && request.getParameter("password") != null) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        isLoggedIn = getLogin(username, password, request, response);

        // Temp fix, refresh the page to retrieve the new cookie that was set
        out.println("<meta http-equiv=\"refresh\" content=\"0\">");
      }
      // Make sure user is already logged in and retrieve their user id
      else {
        isLoggedIn = isLoggedIn(request, response);
      }

      out.write("\n");
      out.write("\n");
      out.write("\t\n");
      out.write('\n');
      out.write('\n');
      out.write('\n');

      messageToDisplay = "";

      //
      if (isLoggedIn) {
        // Determine which action is being called for by the user
        String action = "";
        if (request.getParameter("action") != null)
          action = request.getParameter("action").toLowerCase();
        if (request.getParameter("dispatchAction") != null)
          action = request.getParameter("dispatchAction").toLowerCase();

        try {
          if (action.equals("logout")) {
            logOut(request, response);
            out.println("<meta http-equiv=\"refresh\" content=\"0;url=index.jsp\">");
          }
        } catch (Exception e) {
          // System.out.println(e.getMessage());
        }
      }

      out.write("\n");
      out.write("\n");
      out.write(
          "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
      out.write("<html>\n");
      out.write("<head>\n");
      out.write("\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">\n");
      out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"inc/manager.css\" />\n");
      out.write("\t<title>Infinit.e.Manager - Home</title>\n");
      out.write("</head>\n");
      out.write("<body>\n");
      out.write("\n");
      out.write("<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" >\n");
      out.write("<tr valign=\"middle\">\n");
      out.write("\t<td width=\"100%\" background=\"image/infinite_logo_bg.png\">\n");
      out.write("\t\t<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" >\n");
      out.write("\t\t\t<tr valign=\"bottom\">\n");
      out.write(
          "\t\t\t\t<td width=\"200\"><a href=\"index.jsp\"><img src=\"image/infinite_logo.png\" border=\"0\"></a></td>\n");
      out.write("\t\t\t\t<td>\n");
      out.write(
          "\t\t\t\t\t<a href=\"people.jsp\" class=\"headerLink\" title=\"Add/Edit Users\">People</a> &nbsp; &nbsp;\n");
      out.write(
          "\t\t\t\t\t<a href=\"communities.jsp\" class=\"headerLink\" title=\"Add/Edit Communities\">Communities</a> &nbsp; &nbsp;\n");
      out.write(
          "\t\t\t\t\t<a href=\"sources.jsp\" class=\"headerLink\" title=\"Add/Edit Sources\">Sources</a> &nbsp; &nbsp;\n");
      out.write(
          "\t\t\t\t\t<!-- <a href=\"widgets.jsp\" class=\"headerLink\" title=\"Add/Edit Widgets\">Widgets</a> &nbsp; &nbsp; -->\n");
      out.write(
          "\t\t\t\t\t<!-- <a href=\"hadoop.jsp\" class=\"headerLink\" title=\"Add/Edit Hadoop Jars\">Hadoop</a> &nbsp; &nbsp; -->\n");
      out.write(
          "\t\t\t\t\t<!-- <a href=\"shares.jsp\" class=\"headerLink\" title=\"Add/Edit Shares\">Shares</a> &nbsp; &nbsp; -->\n");
      out.write(
          "\t\t\t\t\t<a href=\"index.jsp\" class=\"headerLink\" title=\"Home\">Home</a> &nbsp; &nbsp;\n");
      out.write(
          "\t\t\t\t\t<a href=\"?action=logout\" class=\"headerLink\" title=\"Logout\">Logout</a>\n");
      out.write("\t\t\t\t</td>\n");
      out.write(
          "\t\t\t\t<td align=\"right\" width=\"120\" background=\"image/ikanow_logo_smaller_bg.png\"></td>\n");
      out.write("\t\t\t</tr>\n");
      out.write("\t\t</table>\n");
      out.write("\t</td>\n");
      out.write("</tr>\n");
      out.write("<tr>\n");
      out.write("\t<td bgcolor=\"#ffffff\">\n");
      out.write('\n');
      out.write('\n');

      if (!isLoggedIn) {

        out.write('\n');
        out.write('	');
        out.write('	');
        out.write("<!-- Begin login_form.jsp  -->\n");
        out.write("\n");
        out.write("<br />\n");
        out.write("<br />\n");
        out.write("<br />\n");
        out.write("<br />\n");
        out.write("<center>\n");
        out.write("<form method=\"post\" name=\"login_form\">\n");
        out.write(
            "<table class=\"standardTable\" cellpadding=\"5\" cellspacing=\"1\" width=\"35%\" >\n");
        out.write("\t<tr>\n");
        out.write("\t\t<td colspan=\"2\" align=\"center\">\n");
        out.write("\t\t\t<font color=\"white\"><b>Login to Infinit.e.Manager</b></font>\n");
        out.write("\t\t</td>\n");
        out.write("\t</tr>\n");
        out.write("\t<tr>\n");
        out.write("\t\t<td bgcolor=\"white\" width=\"40%\">User Name:</td>\n");
        out.write(
            "\t\t<td bgcolor=\"white\" width=\"60%\"><input type=\"text\" name=\"username\" size=\"40\"></td>\n");
        out.write("\t</tr>\n");
        out.write("\t<tr>\n");
        out.write("\t\t<td bgcolor=\"white\" width=\"40%\">Password:</td>\n");
        out.write(
            "\t\t<td bgcolor=\"white\" width=\"60%\"><input type=\"password\" name=\"password\" size=\"40\"></td>\n");
        out.write("\t</tr>\n");
        out.write("\t<tr>\n");
        out.write("\t\t<td colspan=\"2\" align=\"right\"><input type=\"submit\"></td>\n");
        out.write("\t</tr>\n");
        out.write("</table>\n");
        out.write("</form>\n");
        out.write("</center>\n");
        out.write("<br />\n");
        out.write("<br />\n");
        out.write("<br />\n");
        out.write("<br />\n");
        out.write("<!-- End login_form.jsp  -->");
        out.write('\n');

      } else {

        out.write("\n");
        out.write(
            "\t<table class=\"standardTable\" cellpadding=\"5\" cellspacing=\"1\" width=\"100%\" >\n");
        out.write("\t<tr>\n");
        out.write("\t\t<td width=\"100%\" bgcolor=\"#ffffff\">\n");
        out.write("\t\t\t<br />\n");
        out.write("\t\t\t<br />\n");
        out.write("\t\t\t\n");
        out.write("\t\t\t<center>\n");
        out.write(
            "\t\t\t<table class=\"standardTable\" cellpadding=\"5\" cellspacing=\"1\" width=\"50%\">\n");
        out.write("\t\t\t\t<tr>\n");
        out.write("\t\t\t\t\t<td>&nbsp</td>\n");
        out.write("\t\t\t\t</tr>\n");
        out.write("\t\t\t\t<tr>\n");
        out.write("\t\t\t\t\t<td bgcolor=\"white\">\n");
        out.write("\t\t\t\t\t\t<ul>\n");
        out.write(
            "\t\t\t\t\t\t\t<li><b><a href=\"people.jsp\" title=\"Add/Edit Users\">People</a></b> - Add/Edit Users</li>\n");
        out.write(
            "\t\t\t\t\t\t\t<li><b><a href=\"communities.jsp\" title=\"Add/Edit Users\">Communities</a></b> - Add/Edit Communities and Membership</li>\n");
        out.write(
            "\t\t\t\t\t\t\t<li><b><a href=\"sources.jsp\" title=\"Add/Edit Users\">Sources</a></b> - Add/Edit Sources\n");
        out.write(
            "\t\t\t\t\t\t\t\t<ul><li><b><a href=\"sourcemonitor.jsp\" title=\"Monitor Sources\" target=\"_blank\">Source Monitoring</a></b> (new tab)</li></ul>\n");
        out.write("\t\t\t\t\t\t\t</li>\n");
        out.write("\t\t\t\t\t\t</ul>\n");
        out.write("\t\t\t\t\t\t<ul>\n");
        out.write(
            "\t\t\t\t\t\t\t<li><b><a href=\"fileUploader.jsp\" title=\"Add/Edit Users\" target=\"_blank\">File Uploader</a></b> - Add/Edit Files or JSON (new tab)</li>\n");
        out.write(
            "\t\t\t\t\t\t\t<li><b><a href=\"widgetUploader.jsp\" title=\"Add/Edit Users\" target=\"_blank\">Widget Uploader</a></b> - Add/Edit Widgets (new tab)</li>\n");
        out.write(
            "\t\t\t\t\t\t\t<li><b><a href=\"pluginManager.jsp\" title=\"Add/Edit Users\" target=\"_blank\">Plugin Manager</a></b> - Add/Edit Hadoop Plugins (new tab)</li>\t\t\t\t\t\t\n");
        out.write("\t\t\t\t\t\t</ul>\n");
        out.write("\t\t\t\t\t\t<ul>\n");
        out.write(
            "\t\t\t\t\t\t\t<li><b><a href=\"chrome.html\" title=\"Install Chrome Source Extension\" target=\"_blank\">Infinit.e Chrome Extension</a></b> - Create Sources from Chrome</li>\n");
        out.write("\t\t\t\t\t\t</ul>\n");
        out.write("\t\t\t\t\t</td>\n");
        out.write("\t\t\t\t</tr>\n");
        out.write("\t\t\t</table>\n");
        out.write("\t\t\t</center>\n");
        out.write("\n");
        out.write("\t\t\t<br />\n");
        out.write("\t\t\t<br />\n");
        out.write("\t\t\t<br />\n");
        out.write("\t\t\t<br />\n");
        out.write("\t\t\t<br />\n");
        out.write("\t\t\t<br />\n");
        out.write("\t\t</td>\n");
        out.write("\t<tr>\n");
        out.write("\t</table>\n");
      }

      out.write('\n');
      out.write('\n');
      out.write("\t\n");
      out.write("\t</td>\n");
      out.write("<tr>\n");
      out.write("<tr>\n");
      out.write("\t<td align=\"right\" bgcolor=\"#000000\">\n");
      out.write("\t\t&nbsp;\n");
      out.write(
          "\t\t<!-- <a href=\"http://www.ikanow.com\" title=\"www.ikanow.com\"><img src=\"image/ikanow_logo_small.png\" border=\"0\"></a> -->\n");
      out.write("\t</td>\n");
      out.write("</tr>\n");
      out.write("</table>\n");
      out.write("\n");
      out.write("\n");
      out.write("</body>\n");
      out.write("</html>");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)) {
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try {
            out.clearBuffer();
          } catch (java.io.IOException e) {
          }
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
Ejemplo n.º 17
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      String jsppath = "rhccinvoice";
      String year = "";
      String spin = "";
      String frn = "";
      String invid = "";
      String invno = "";
      String spinnm = "";
      String frame = "";
      String user = "";
      Vector vector = new Vector();
      HttpSession session = request.getSession(false);

      if (session == null) {
        jsppath = "login";
        USFEnv.getLog().writeCrit("RhccInvviewServlet: Inside Session is null", this, null);
        USFEnv.getLog()
            .writeWarn("RhccInvviewServlet: Inside frame session calling JSP Login", this, null);
        includeJSP(request, response, jsppath, "Login");
      } else {

        jsppath = "rhccinvoice";
        frame = request.getParameter("frame");
        user = (String) session.getValue("cuid");
        USFEnv.getLog()
            .writeDebug("RhccInvviewServlet: Inside doPost Login CUID is: " + user, this, null);
        USFEnv.getLog()
            .writeWarn("RhccInvviewServlet: Inside InvreconServlet Frame is:" + frame, this, null);

        if (frame.equals("iview_frn")) {
          boolean discountview_flag = false;
          if ((request.getParameter("idiscountview") != null)
              && (request.getParameter("idiscountview").equals("TRUE"))) {
            year = request.getParameter("iyear");
            session.putValue("Iyear", year);
            discountview_flag = true;
          }

          if ((discountview_flag) || (session.getValue("Iyear") != null)) {

            if ((request.getParameter("ifrn")) != null) {
              frn = request.getParameter("ifrn");
              USFEnv.getLog().writeDebug("RhccInvviewServlet: FRN Value :" + frn, this, null);
              if (!(discountview_flag)) {
                year = (String) session.getValue("Iyear");
              }
              Vector frninvnos = new Vector();
              Vector invnolist = new Vector();
              Vector invpending = new Vector();
              boolean frn_flag = false;
              String frnerrmsg = "";

              try {
                invviewEJBean.connect();
                USFEnv.getLog()
                    .writeWarn(
                        "RhccInvviewServlet: Inside frame rhcciview_frn connected to RhccInvviewBean",
                        this,
                        null);

                if (discountview_flag) {
                  frn_flag = true;
                } else {
                  frn_flag = invviewEJBean.validateFRN(frn, year);
                  USFEnv.getLog()
                      .writeWarn(
                          "RhccInvviewServlet:Inside frame rhcciview_frn data from validateFRN"
                              + frn_flag,
                          this,
                          null);
                }

                if (frn_flag) {
                  frninvnos = invviewEJBean.getFrninvnos(year, frn);
                  USFEnv.getLog().writeWarn("ouside the block", this, null);

                  invviewEJBean.release();
                  USFEnv.getLog()
                      .writeWarn(
                          "RhccInvviewServlet: Inside frame Rhcciview_frn released RhccInvviewBean",
                          this,
                          null);
                } else {
                  USFEnv.getLog()
                      .writeWarn(
                          "RhccInvviewServlet: Inside frame iview_frn Inside the else block",
                          this,
                          null);

                  frnerrmsg = invviewEJBean.setErrmsg();

                  invviewEJBean.release();
                  USFEnv.getLog()
                      .writeWarn(
                          "RhccInvviewServlet: Inside frame iview_frn released RhccInvviewBean"
                              + frnerrmsg,
                          this,
                          null);
                  invgenEJBean.connect();
                  USFEnv.getLog()
                      .writeWarn(
                          "RhccInvviewServlet: Inside frame iview_frn connected to RhccInvgenBean"
                              + invnolist,
                          this,
                          null);
                  invnolist = invgenEJBean.getRhccInvnos(year);
                  USFEnv.getLog().writeWarn("outside of this " + invnolist, this, null);

                  invgenEJBean.release();
                  USFEnv.getLog()
                      .writeWarn(
                          "RhccInvviewServlet: Inside frame iview_frn released RhccInvgenBean",
                          this,
                          null);
                }
                USFEnv.getLog()
                    .writeWarn(
                        "RhccInvviewServlet: Inside frame iview_frn Inside the else block--2--",
                        this,
                        null);

                if (discountview_flag) {
                  USFEnv.getLog()
                      .writeWarn(
                          "RhccInvviewServlet: Inside -3---" + discountview_flag, this, null);
                  USFEnv.getLog().writeWarn("RhccInvviewServlet: Inside -3---" + frn, this, null);
                  USFEnv.getLog().writeWarn("RhccInvviewServlet: Inside -3---" + year, this, null);
                  session.putValue("Ifrn", frn);
                  invgenEJBean.connect();
                  USFEnv.getLog()
                      .writeWarn("RhccInvviewServlet: Inside frame----88 " + frn, this, null);
                  invpending = invgenEJBean.getRhccInvpending(null, year, frn);
                  USFEnv.getLog()
                      .writeWarn(
                          "RhccInvviewServlet: Inside frame iview_frn connected to InvgenBean",
                          this,
                          null);
                  invgenEJBean.release();
                  USFEnv.getLog()
                      .writeWarn(
                          "RhccInvviewServlet: Inside frame iview_frn released InvgenBean",
                          this,
                          null);
                }

              } catch (RemoteException e) {

                USFEnv.getLog().writeCrit("I m here", this, null);

                USFEnv.getLog()
                    .writeCrit(
                        "RhccInvviewServlet: Inside Remote Exception of getFrninvnos ", this, null);
              }

              if (frn_flag) {
                USFEnv.getLog()
                    .writeWarn(
                        "RhccInvviewServlet: Inside frame iview_frn calling JSP RhccIInvviewfrn"
                            + frn_flag,
                        this,
                        null);

                request.setAttribute("frn", frn);
                request.setAttribute("frninv", frninvnos);
                USFEnv.getLog()
                    .writeWarn(
                        "RhccInvviewServlet: Inside frame iview_frn calling JSP RhccIInvviewfrn",
                        this,
                        null);

                if (discountview_flag) {
                  if ((request.getParameter("invrejn") != null)
                      && (request.getParameter("invrejn").equals("true")))
                    request.setAttribute("invrejn", "true");

                  request.setAttribute("frnpend", invpending);
                  includeJSP(request, response, jsppath, "RhccIDiscountview");
                } else {
                  USFEnv.getLog()
                      .writeWarn(
                          "RhccInvviewServlet:  Inside frame iview_frn calling JSP RhccIInvviewfrn inside else",
                          this,
                          null);

                  includeJSP(request, response, jsppath, "RhccIInvviewfrn");
                }
              } else {
                request.setAttribute("invnolist", invnolist);
                request.setAttribute("invviewmsg", frnerrmsg);
                USFEnv.getLog()
                    .writeWarn(
                        "RhccInvviewServlet: Inside frame iview_frn calling JSP IMenu", this, null);
                includeJSP(request, response, jsppath, "RhccIMenu");
              }
            }
          }
        }

        if (frame.equals("iview_file")) {
          boolean discountview_flag = false;
          frn = request.getParameter("ifrn");
          invid = request.getParameter("iview_no");
          USFEnv.getLog()
              .writeWarn(
                  "RhccInvviewServlet: Inside frame iview_file released InvviewBean" + frn,
                  this,
                  null);
          USFEnv.getLog()
              .writeWarn(
                  "RhccInvviewServlet: Inside frame iview_file released InvviewBean" + invid,
                  this,
                  null);

          Vector invfil = new Vector();

          if ((request.getParameter("idiscountview") != null)
              && (request.getParameter("idiscountview").equals("TRUE"))) {
            year = request.getParameter("iyear");
            session.putValue("Iyear", year);
            discountview_flag = true;
          }

          if (invid != null) {
            if (session.getValue("Iyear") != null) {
              year = (String) session.getValue("Iyear");

              try {
                invviewEJBean.connect();
                USFEnv.getLog()
                    .writeWarn(
                        "RhccInvviewServlet: Inside frame iview_file connected to RhccInvviewBean",
                        this,
                        null);
                invno = invviewEJBean.getInvno(invid);
                spinnm = invviewEJBean.getSPINname(invid);
                invfil = invviewEJBean.getFiledetails(frn, invid, year);
                invviewEJBean.release();
                USFEnv.getLog()
                    .writeWarn(
                        "RhccInvviewServlet: Inside frame iview_file released RhccInvviewBean",
                        this,
                        null);
              } catch (RemoteException e) {
                USFEnv.getLog()
                    .writeCrit("RhccInvviewServlet: Inside Remote Exception for Inv ", this, null);
              }
            }
          }

          if (discountview_flag) {
            request.setAttribute("vdsflag", "TRUE");
          }
          if ((request.getParameter("invrejn") != null)
              && (request.getParameter("invrejn").equals("true")))
            request.setAttribute("invrejn", "true");

          request.setAttribute("frn", frn);
          request.setAttribute("invno", invno);
          request.setAttribute("spinnm", spinnm);
          request.setAttribute("invfil", invfil);
          USFEnv.getLog()
              .writeWarn(
                  "RhccInvviewServlet: Inside frame iview_file calling JSP RhccIInvviewfil",
                  this,
                  null);
          includeJSP(request, response, jsppath, "RhccIInvviewfil");
        }
      }
    } catch (Exception e) {
      if (invviewEJBean != null) {
        // calling bean release method
        try {
          invviewEJBean.release();
        } catch (Exception ex) {
          USFEnv.getLog().writeCrit(" Exception in calling release() method ", this, e);
        }
      }
      USFEnv.getLog().writeCrit("RhccInvviewServlet: Inside Exception" + e, this, null);
      USFEnv.getLog()
          .writeWarn("RhccInvviewServlet: Inside Exception calling JSP Login", this, null);
      includeJSP(request, response, "login", "Login");
    }
  }
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    final String S_ProcName = "doGet";
    ICFAsteriskSchemaObj schemaObj;
    HttpSession sess = request.getSession(false);
    if (sess == null) {
      sess = request.getSession(true);
      schemaObj = new CFAsteriskSchemaPooledObj();
      sess.setAttribute("SchemaObj", schemaObj);
    } else {
      schemaObj = (ICFAsteriskSchemaObj) sess.getAttribute("SchemaObj");
      if (schemaObj == null) {
        schemaObj = new CFAsteriskSchemaPooledObj();
        sess.setAttribute("SchemaObj", schemaObj);
      }
    }

    ICFAsteriskSchema dbSchema = null;
    try {
      CFSecurityAuthorization auth = schemaObj.getAuthorization();
      if (auth != null) {
        response.sendRedirect("CFAsteriskSMWarSecurityMainHtml");
        return;
      }

      dbSchema = (ICFAsteriskSchema) CFAsteriskSchemaPool.getSchemaPool().getInstance();
      schemaObj.setBackingStore(dbSchema);
      schemaObj.beginTransaction();
      ICFSecuritySecUserObj systemUser =
          schemaObj.getSecUserTableObj().readSecUserByULoginIdx("system");
      String passwordHash = systemUser.getRequiredPasswordHash();
      if ((passwordHash == null)
          || (passwordHash.length() <= 0)
          || passwordHash.equals("bootstrap")) {
        response.sendRedirect("CFAsteriskSMWarSetSystemPasswordHtml");
        return;
      }

      ICFSecuritySysClusterObj sysCluster =
          schemaObj.getSysClusterTableObj().readSysClusterByIdIdx(1, false);
      if (sysCluster == null) {
        throw CFLib.getDefaultExceptionFactory()
            .newNullArgumentException(getClass(), S_ProcName, 0, "sysCluster");
      }

      ICFSecurityClusterObj resolvedCluster = sysCluster.getRequiredContainerCluster();
      if (resolvedCluster == null) {
        throw CFLib.getDefaultExceptionFactory()
            .newNullArgumentException(getClass(), S_ProcName, "resolvedCluster");
      }
      String clusterDomainName = resolvedCluster.getRequiredFullDomainName();
      String clusterDescription = resolvedCluster.getRequiredDescription();

      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
      out.println("<HTML>");
      out.println("<BODY>");
      out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarRequestResetPasswordHtml\">");
      out.println(
          "<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
      out.println(
          "<H2 style=\"text-align:center\">Enter the login you'd like to request a password reset for.</H2>");
      out.println("<p>");
      out.println("<center>");
      out.println("<table style=\"width:60%\">");
      out.println(
          "<tr><th style=\"text-align:left\">Login Id:</th><td><input type=\"text\" name=\"LoginId\"/></td></tr>");
      out.println(
          "<tr><td colspan=\"2\" style=\"text-align:center\"><button type=\"submit\" name=\"Ok, Request Password Reset\"\">Ok</button></td></tr>");
      out.println(
          "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"CFAsteriskSMWarLoginHtml\">Back to "
              + clusterDescription
              + " Security Manager Login</A></td></tr>");
      out.println("</table>");
      out.println("</center>");
      out.println("</form>");
      out.println("</BODY>");
      out.println("</HTML>");
    } catch (RuntimeException e) {
      throw CFLib.getDefaultExceptionFactory()
          .newRuntimeException(
              getClass(), S_ProcName, "Caught RuntimeException -- " + e.getMessage(), e);
    } finally {
      if (dbSchema != null) {
        try {
          if (schemaObj.isTransactionOpen()) {
            schemaObj.rollback();
          }
        } catch (RuntimeException e) {
        }
        schemaObj.setBackingStore(null);
        CFAsteriskSchemaPool.getSchemaPool().releaseInstance(dbSchema);
      }
    }
  }
Ejemplo n.º 19
0
  /**
   * This is the main controller logic for item selection servlet. This determines whether to show a
   * list of items for a WorkOrder, add a item, edit a item's detail information, or delete a item.
   * The product_action parameter is past to this servlet to determine what action to perform. The
   * product_action parameter is a button defined by JSPs related to product presentation screens.
   *
   * <p>The default action is to show all product related to a parent WorkOrder.
   *
   * @param req HttpServlet request
   * @param resp HttpServlet response
   */
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    WorkOrderDetailRemote workorderdetEJBean = null;

    securityChecks(req, resp);

    // Get the current session
    HttpSession session = req.getSession(false);
    if (session == null) return;

    String sTmp = "";

    // Get a new business logic EJB (custInfoEJBean)
    USFEnv.getLog().writeDebug("getting buslogic EJB", this, null);
    try {
      workorderdetEJBean = workorderdetHome.create();
      USFEnv.getLog().writeDebug("EJBean Created", this, null);
    } catch (CreateException e) {
      String errorMsg = "Critical Exception in ItemsServlet";
      USFEnv.getLog().writeCrit(errorMsg + " failed EJB creation", this, e);
      errorJSP(req, resp, errorMsg);
      return;
    } catch (RemoteException e) {
      String errorMsg = "Critical Exception in ItemsServlet";
      USFEnv.getLog().writeCrit(errorMsg + " failed EJB connect", this, e);
      errorJSP(req, resp, errorMsg);
      return;
    } catch (Exception e) {
      String errorMsg = "Critical Exception no EJB created";
      USFEnv.getLog().writeCrit(errorMsg + " failed EJB creation", this, e);
      errorJSP(req, resp, errorMsg);
      return;
    }

    try {

      // Button user pressed in the itemselection.jsp
      String sJSPAction = req.getParameter("product_action");
      USFEnv.getLog().writeWarn("product_action from JSP: " + sJSPAction, this, null);

      short year = Short.valueOf((String) session.getValue("Iyear")).shortValue();
      long customerId = Long.valueOf((String) session.getValue("rcustId")).longValue();
      long applicationId = Long.valueOf((String) session.getValue("rappid")).longValue();
      long workorderId = 0;
      long bkId = 0;
      long billkeyId = 0;
      long bsId = 0;
      long wodId = 0;
      String editflag = "";
      String bsNm = "";

      java.sql.Date strtDate = null;
      java.sql.Date endDate = null;
      String prodError = "";

      // Check to make sure session does have an WorkOrder ID
      if (session.getValue("WorkOrderId") != null) {
        // If Yes get the parent WorkOrder ID from session
        workorderId = Long.valueOf((String) session.getValue("WorkOrderId")).longValue();
      }

      // Button Action from JSP is empty then show the Default page of the
      // Product Listing.
      if (USFUtil.isBlank(sJSPAction)) {
        USFEnv.getLog().writeDebug("Display product list for FRN.", this, null);
        // list items for parent Work Order Number

        Vector billingsystems = null;

        WrkOrdrDets workorderdets = new WrkOrdrDets();

        billingsystems = workorderdets.getBillingSystems();

        req.setAttribute("BillingSystems", billingsystems);

        for (int s = 0; s < billingsystems.size(); s++)
          USFEnv.getLog()
              .writeDebug("INSIDE BILLING SYSTEMS " + billingsystems.elementAt(s), this, null);

        listProducts(workorderId, workorderdetEJBean, session, req, resp);
        return;
      }

      // Button action from JSP is to Add a new Item
      else if (sJSPAction.equals("add")) {
        // Remove the Product Object from session
        session.removeValue("prodObj");

        editflag = "addnew";
        req.setAttribute("editflag", editflag);

        // Read the Item and the Billing System for adding the New
        // Item.
        String formProdBsId = (String) req.getParameter("formProdId");
        String formProdId = formProdBsId.substring(0, formProdBsId.indexOf("|"));
        String formProdName = formProdBsId.substring(formProdBsId.indexOf("|") + 1);
        long rscId = (new Long(formProdId).longValue());
        // bsId = (new Long( formBsId ).longValue()) ;
        String billSystem = formProdName.substring(0, formProdName.indexOf("-"));
        String itemName = formProdName.substring(formProdName.indexOf("-") + 1);

        BlgSys blgSys = new BlgSys();
        bsId = blgSys.getBsId(billSystem);

        // Create db connection for EJB
        workorderdetEJBean.connect();

        // Get the WorkOrder Object.
        WorkOrder woObj = workorderdetEJBean.getWorkOrderInfo(workorderId);

        // Get the list of Billing Keys for the Billing System.
        String[] blgKeys = workorderdetEJBean.getBillingKeys(customerId, bsId);

        // Release db connection for EJB
        workorderdetEJBean.release();

        // If no Billing Keys for the Billing System selected then redirect
        // to the List Items screen and show the error Message.
        if (blgKeys == null) {
          BlgSys blgsys = new BlgSys();
          Hashtable bSysList = (Hashtable) blgsys.searchBlgSys();
          //	Hashtable bSysList = (Hashtable) USFEnv.getBillSystems();

          // Set the JSP error message
          req.setAttribute("errorMsg", "No BTNs for Billing System " + billSystem);

          // list products for parent WorkOrder Number
          listProducts(workorderId, workorderdetEJBean, session, req, resp);
          return;
        }

        req.setAttribute("prodcredit", "N");
        req.setAttribute("bsystem", String.valueOf(bsId));
        req.setAttribute("bkList", blgKeys);
        req.setAttribute("prodId", formProdId);
        String wid = String.valueOf(workorderId);

        session.putValue("workorderId", wid);

        req.setAttribute("billingsystem", billSystem);

        req.setAttribute("itemname", itemName);

        // Include the JSP to Edit Product
        includeJSP(req, resp, ITEM_JSP_PATH, "editItem");
        return;
      }

      // Button action from JSP is to Edit a Product
      else if (sJSPAction.equals("edit")) {
        String bsysid = req.getParameter("bsId");
        session.putValue("bysysidforedit", bsysid);

        wodId = (new Long((String) req.getParameter("wodId"))).longValue();
        // bkId = (new Long( (String) req.getParameter("bkId"))).longValue() ;

        session.putValue("workorderdetid", String.valueOf(wodId));

        bsId = (new Long((String) req.getParameter("bsId"))).longValue();

        BlgSys blgSys = new BlgSys();
        bsNm = blgSys.getBsName(bsId);

        // Create db connection for EJB
        workorderdetEJBean.connect();

        // WorkOrder woObj = workorderdetEJBean.getWorkOrderInfo(workorderId);

        // Get the WorkOrder Number Object
        WrkOrdrDets wodets_obj = new WrkOrdrDets();
        wodets_obj = workorderdetEJBean.getProductInfo(wodId);

        // Get the List of Billing Keys for the Billing System.
        String[] blgKeys = workorderdetEJBean.getBillingKeys(customerId, bsId);

        // Check if the Item has any Credits. If any credits then Billing
        // Key is not Editable else Editable.
        if (workorderdetEJBean.hasCredits(wodId)) {
          req.setAttribute("prodcredit", "Y");
        } else {
          req.setAttribute("prodcredit", "N");
        }

        // Release db connection for EJB
        workorderdetEJBean.release();

        // If Item Object is not null (which generally is the case) then
        // set the Attributes for the JSP.
        if (wodets_obj != null) {
          // Put the Item Object in session
          editflag = "edit";
          session.putValue("wodets", wodets_obj);
          req.setAttribute("editflag", editflag);

          // Set the attributes for the Billing System, Billing Key List,
          req.setAttribute("bkList", blgKeys);
          req.setAttribute("bsname", bsNm);

          // Include the JSP to Edit the Item.
          includeJSP(req, resp, ITEM_JSP_PATH, "editItem");
          return;
        }

        // If Item Object is null (which generally should not Occur) show
        // the Default page of Item List for the WorkOrder Number
        else {
          // Set the JSP error message
          req.setAttribute(
              "errorMsg", "Product Key - " + wodId + " Information not available in the Data Base");

          // list items for parent WorkOrder Number
          listProducts(workorderId, workorderdetEJBean, session, req, resp);
          return;
        }

      }

      // Button action from JSP is to Delete an Item
      else if (sJSPAction.equals("delete")) {
        String formWodId = req.getParameter("wodId");

        wodId = (new Long((String) req.getParameter("wodId"))).longValue();

        // Create db connection for EJB
        workorderdetEJBean.connect();

        // Delete the Item
        if (workorderdetEJBean.deleteProduct(wodId)) {
          req.setAttribute("errorMsg", "Product Key - " + wodId + " Deleted");
        } else {
          req.setAttribute(
              "errorMsg",
              "Deletion Failed. Product Key - " + wodId + " is associated with amounts.");
        }
        // Release db connection for EJB
        workorderdetEJBean.release();

        // Show the Item List screen
        listProducts(workorderId, workorderdetEJBean, session, req, resp);
        return;

      }

      // Button action from JSP is to Save a Product. This includes Insertion
      // of New Product or Updation of an Existing Product.

      else if (sJSPAction.equals("save")) {
        boolean save = false;
        boolean newProd = false;
        // long qty=0;

        // Read the Billing System Id
        String formBsId = (String) req.getParameter("bs_id");

        String bsysid = (String) req.getParameter("bsysid");
        /*
        String trans_type = (String) req.getParameter("trans_type");

        //String quantity = (String) req.getParameter("qty");
        String quantity="";
        if (!(req.getParameter("qty").equals("")))
        {
        	quantity=(String) req.getParameter("qty");

        	qty = (new Long(quantity).longValue());
        } */
        String prod_stat = (String) req.getParameter("prod_stat");

        double nrcg_dscnt =
            (new Double((String) req.getParameter("NonRecurringDiscount"))).doubleValue();

        double rcg_dscnt =
            (new Double((String) req.getParameter("RecurringDiscount"))).doubleValue();

        String start_month = (String) req.getParameter("strt_month");
        String start_day = (String) req.getParameter("strt_day");
        String start_year = (String) req.getParameter("strt_year");
        String end_month = (String) req.getParameter("end_month");
        String end_day = (String) req.getParameter("end_day");
        String end_year = (String) req.getParameter("end_year");

        String start_date = start_month + "-" + start_day + "-" + start_year;

        String end_date = end_month + "-" + end_day + "-" + end_year;

        long wrkordrid = (new Long((String) session.getValue("WorkOrderId"))).longValue();

        String for_editing = req.getParameter("for_editing");
        String for_new = req.getParameter("for_new");

        String formBkId = (String) req.getParameter("bk_id");

        String formBKId = formBkId.substring(0, formBkId.indexOf("|"));

        String formBTN = formBkId.substring(formBkId.indexOf("|") + 1);

        billkeyId = (new Long(formBKId)).longValue();

        try {
          bsId = (new Long((String) req.getParameter("bs_id"))).longValue();
        } catch (Exception e) {
          USFEnv.getLog().writeDebug("Exception is " + e, this, null);
        }

        RHCCBlgKeys blgkeys = new RHCCBlgKeys();

        if (for_editing.equals("editing")) {
          blgkeys.setRbkId(billkeyId);
          blgkeys.setRbkKeys(formBTN);
          blgkeys.setBsId(new Long(bsysid).longValue());
        }

        if (for_new.equals("new")) {
          blgkeys.setRbkId(billkeyId);
          blgkeys.setRbkKeys(formBTN);
          blgkeys.setBsId(bsId);
        }

        int index = 0;

        WrkOrdrDets wod_obj = new WrkOrdrDets();

        // wod_obj.setTxTyp(trans_type);
        // wod_obj.setQty(qty);
        wod_obj.setNonRcrgDscnt(nrcg_dscnt);
        wod_obj.setRcrgDscnt(rcg_dscnt);
        wod_obj.setRBKID(billkeyId);
        wod_obj.setWodStat(prod_stat);
        wod_obj.setWOID(wrkordrid);

        if (!(start_date.equals(""))) {
          strtDate =
              new java.sql.Date((new SimpleDateFormat("MM-dd-yyyy")).parse(start_date).getTime());
          wod_obj.setStrtDat(strtDate);
        }
        // Else if the Start Date is null update the Item Object Date to
        // null
        else {
          wod_obj.setStrtDat(null);
        }

        // If Item Service End Date is not null read the date and update
        // the Item Object with the date
        if (!(end_date.equals(""))) {
          endDate =
              new java.sql.Date((new SimpleDateFormat("MM-dd-yyyy")).parse(end_date).getTime());
          wod_obj.setEndDat(endDate);
        }
        // Else if the End Date is null update the Item Object Date to null
        else {
          wod_obj.setEndDat(null);
        }

        // Check if the Start Date is after the End Date or equals End Date
        if ((strtDate != null) && (endDate != null) && (strtDate.after(endDate))) {
          prodError = "Product Service Start Date is after Product Service End Date. \n";
          index = 1;
        } else if ((strtDate != null) && (endDate != null) && (strtDate.equals(endDate))) {
          prodError = "Product Service Start Date equals Product Service End Date. \n";
        }

        workorderdetEJBean.connect();

        if (for_editing.equals("editing")) {
          long workorderdetID = (new Long((String) session.getValue("workorderdetid"))).longValue();
          wod_obj.setWODID(workorderdetID);

          if (index == 0) {
            save = workorderdetEJBean.saveProduct(wod_obj);
          }

          if (save) {
            prodError =
                prodError + "<BR> Product Key - " + wod_obj.getWODID() + " Information updated";
            req.setAttribute("error", prodError);
          } else {
            prodError = prodError + "<BR> Failed to update Product Information";
            req.setAttribute("error", prodError);
          }
        }

        if (for_new.equals("new")) {
          if (index == 0) {
            int prodId = Integer.parseInt(req.getParameter("prod_Id"));
            wod_obj.setProd_id(prodId);
            save = workorderdetEJBean.saveProduct(wod_obj);
          }

          if (save) {
            prodError =
                prodError + "<BR> Product Key - " + wod_obj.getWODID() + " Information Saved";
            req.setAttribute("error", prodError);
          } else {
            prodError = prodError + "<BR> Failed to Save Product Information";
            req.setAttribute("error", prodError);
          }
        }

        workorderdetEJBean.release();

        listProducts(wrkordrid, workorderdetEJBean, session, req, resp);
      }

    } // End of try block
    catch (Exception e) {
      if (workorderdetEJBean != null) {
        // calling bean release method
        try {
          workorderdetEJBean.release();
        } catch (Exception ex) {
          USFEnv.getLog().writeCrit(" Exception in calling release() method ", this, e);
        }
      }
      String errorMsg = "Processing Exception in Items Servlet: ";
      USFEnv.getLog().writeCrit(errorMsg, this, e);
      errorJSP(req, resp, errorMsg);
    } // End of catch block
  } // end of doPost()