public static UIComponent addTransient(
      FacesContext context, ServletRequest req, UIComponent parent, String prevId, Class childClass)
      throws Exception {
    if (context == null) context = FacesContext.getCurrentInstance();

    if (parent == null) {
      UIComponentClassicTagBase parentTag =
          (UIComponentClassicTagBase) req.getAttribute("caucho.jsf.parent");

      parent = parentTag.getComponentInstance();

      BodyContent body = parentTag.getBodyContent();

      if (body != null) addVerbatim(parent, body);
    }

    UIComponent child = null;
    ;

    if (child == null) child = (UIComponent) childClass.newInstance();

    child.setTransient(true);

    addChild(parent, prevId, child);

    return child;
  }
예제 #2
0
 @Nonnull
 public ServletHealthInterceptor loadInterceptor(@Nonnull String interceptorTypeName)
     throws ServletException {
   final Class<?> interceptorType;
   try {
     interceptorType = currentThread().getContextClassLoader().loadClass(interceptorTypeName);
   } catch (ClassNotFoundException e) {
     throw new ServletException(
         "Could not find interceptor of type " + interceptorTypeName + ".", e);
   }
   if (!ServletHealthInterceptor.class.isAssignableFrom(interceptorType)) {
     throw new ServletException(
         "Defined interceptor type "
             + interceptorTypeName
             + " does not implements "
             + ServletHealthInterceptor.class.getName()
             + ".");
   }
   try {
     return (ServletHealthInterceptor) interceptorType.newInstance();
   } catch (Exception e) {
     throw new ServletException(
         "Could not create an instance of interceptor " + interceptorType.getName() + ".", e);
   }
 }
예제 #3
0
  protected void initKeyProvider() {
    if (!doSupportSignature()) {
      return;
    }

    SPType configuration = getConfiguration();
    KeyProviderType keyProvider = configuration.getKeyProvider();

    if (keyProvider == null && doSupportSignature()) {
      throw new RuntimeException(
          ErrorCodes.NULL_VALUE + "KeyProvider is null for context=" + getContextPath());
    }

    try {
      String keyManagerClassName = keyProvider.getClassName();
      if (keyManagerClassName == null) {
        throw new RuntimeException(ErrorCodes.NULL_VALUE + "KeyManager class name");
      }

      Class<?> clazz = SecurityActions.loadClass(getClass(), keyManagerClassName);

      if (clazz == null) {
        throw new ClassNotFoundException(ErrorCodes.CLASS_NOT_LOADED + keyManagerClassName);
      }

      TrustKeyManager keyManager = (TrustKeyManager) clazz.newInstance();

      List<AuthPropertyType> authProperties = CoreConfigUtil.getKeyProviderProperties(keyProvider);

      keyManager.setAuthProperties(authProperties);
      keyManager.setValidatingAlias(keyProvider.getValidatingAlias());

      String identityURL = configuration.getIdentityURL();

      // Special case when you need X509Data in SignedInfo
      if (authProperties != null) {
        for (AuthPropertyType authPropertyType : authProperties) {
          String key = authPropertyType.getKey();
          if (GeneralConstants.X509CERTIFICATE.equals(key)) {
            // we need X509Certificate in SignedInfo. The value is the alias name
            keyManager.addAdditionalOption(
                GeneralConstants.X509CERTIFICATE, authPropertyType.getValue());
            break;
          }
        }
      }
      keyManager.addAdditionalOption(
          ServiceProviderBaseProcessor.IDP_KEY, new URL(identityURL).getHost());
      this.keyManager = keyManager;
    } catch (Exception e) {
      logger.trustKeyManagerCreationError(e);
      throw new RuntimeException(e.getLocalizedMessage());
    }

    logger.trace("Key Provider=" + keyProvider.getClassName());
  }
예제 #4
0
  public void processAction(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    System.out.println("processing test driver request ... ");

    processParams(request);
    boolean status = false;
    System.out.println("tc:" + tc);

    response.setContentType("text/plain");
    ServletOutputStream out = response.getOutputStream();
    out.println("TestCase: " + tc);

    if (tc != null) {

      try {
        Class<?> c = getClass();
        Object t = this;

        Method[] allMethods = c.getDeclaredMethods();
        for (Method m : allMethods) {
          String mname = m.getName();
          if (!mname.equals(tc.trim())) {
            continue;
          }

          System.out.println("Invoking : " + mname);
          try {
            m.setAccessible(true);
            Object o = m.invoke(t);
            System.out.println("Returned => " + (Boolean) o);
            status = new Boolean((Boolean) o).booleanValue();
            // Handle any methods thrown by method to be invoked
          } catch (InvocationTargetException x) {
            Throwable cause = x.getCause();

            System.err.format("invocation of %s failed: %s%n", mname, cause.getMessage());
          } catch (IllegalAccessException x) {
            x.printStackTrace();
          }
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }

      if (status) {
        out.println(tc + ":pass");
      } else {
        out.println(tc + ":fail");
      }
    }
  }
예제 #5
0
 private void addPrebuiltJsp(String path, String className) {
   try {
     Class clazz =
         Class.forName(
             className); // ttt2 see if possible to not use this, preferably without doing
                         // redirections like RedirectServlet
     Object obj = clazz.newInstance();
     addServlet(new ServletHolder((Servlet) obj), path);
     LOG.info("Added prebuilt JSP: " + obj.toString());
   } catch (Exception e) {
     LOG.fatal(String.format("Failed to load prebuilt JSP for %s and %s", path, className), e);
   }
 }
예제 #6
0
  static {
    String password = "";
    String user = "";

    props.put("user", user);
    props.put("password", password);
    try {

      Class clazz = Class.forName("org.jiql.jdbc.Driver");
      driver = (Driver) clazz.newInstance();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public static UIComponent addFacet(
      FacesContext context,
      ServletRequest req,
      UIComponent parent,
      String facetName,
      ValueExpression binding,
      Class childClass)
      throws Exception {
    if (context == null) context = FacesContext.getCurrentInstance();

    if (parent == null) {
      UIComponentClassicTagBase parentTag =
          (UIComponentClassicTagBase) req.getAttribute("caucho.jsf.parent");

      parent = parentTag.getComponentInstance();
    }

    UIComponent child = null;

    if (binding != null) child = (UIComponent) binding.getValue(context.getELContext());

    if (child == null) child = (UIComponent) childClass.newInstance();

    if (parent != null) parent.getFacets().put(facetName, child);

    if (binding != null) binding.setValue(context.getELContext(), child);

    return child;
  }
  public static UIComponent addPersistent(
      FacesContext context,
      ServletRequest req,
      UIComponent parent,
      ValueExpression binding,
      Class childClass)
      throws Exception {
    if (context == null) context = FacesContext.getCurrentInstance();

    if (parent == null) {
      UIComponentClassicTagBase parentTag =
          (UIComponentClassicTagBase) req.getAttribute("caucho.jsf.parent");

      parent = parentTag.getComponentInstance();

      BodyContent body = parentTag.getBodyContent();

      addVerbatim(parent, body);
    }

    UIComponent child = null;

    if (binding != null) child = (UIComponent) binding.getValue(context.getELContext());

    if (child == null) {
      child = (UIComponent) childClass.newInstance();

      // jsf/3251
      if (binding != null) binding.setValue(context.getELContext(), child);
    }

    if (parent != null) parent.getChildren().add(child);

    return child;
  }
예제 #9
0
  public String checkValidLogin(String myUserName, String myPW) {

    try {
      Class.forName(javaSQLDriverPath);
      Connection conn =
          (Connection) DriverManager.getConnection(ConnectionPath, ConnectionUser, ConnectionPW);
      Statement st = conn.createStatement();
      String query = "Select * from User";

      ResultSet rs = st.executeQuery(query);
      while (rs.next()) {
        // return rs.getString("Username");
        if (myUserName.equals(rs.getString("Username"))) {
          if (myPW.equals(rs.getString("Password"))) {
            setUserVariables(myUserName);
            return "success";
          } else {
            return "wrongPassword";
          }
        }
      }

      rs.close();
      st.close();
      conn.close();

      return "userNotFound";
    } catch (Exception e) {

      return e.getMessage();
    }
  }
예제 #10
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    Statement stmt;
    ResultSet rs;
    Connection con = null;

    try {
      Class.forName("com.mysql.jdbc.Driver");
      String connectionUrl = "jdbc:mysql://localhost/myflickr?" + "user=root&password=123456";
      con = DriverManager.getConnection(connectionUrl);

      if (con != null) {
        System.out.println("connected to mysql");
      }
    } catch (SQLException e) {
      System.out.println("SQL Exception: " + e.toString());
    } catch (ClassNotFoundException cE) {
      System.out.println("Class Not Found Exception: " + cE.toString());
    }

    try {
      stmt = con.createStatement();

      System.out.println("SELECT * FROM flickrusers WHERE name='" + username + "'");
      rs = stmt.executeQuery("SELECT * FROM flickrusers WHERE name='" + username + "'");

      while (rs.next()) {

        if (rs.getObject(1).toString().equals(username)) {

          out.println("<h1>To username pou epileksate uparxei hdh</h1>");
          out.println("<a href=\"project3.html\">parakalw dokimaste kapoio allo.</a>");

          stmt.close();
          rs.close();
          return;
        }
      }
      stmt.close();
      rs.close();

      stmt = con.createStatement();

      if (!stmt.execute("INSERT INTO flickrusers VALUES('" + username + "', '" + password + "')")) {
        out.println("<h1>Your registration is completed  " + username + "</h1>");
        out.println("<a href=\"index.jsp\">go to the login menu</a>");
        registerListener.Register(username);
      } else {
        out.println("<h1>To username pou epileksate uparxei hdh</h1>");
        out.println("<a href=\"project3.html\">Register</a>");
      }
    } catch (SQLException e) {
      throw new ServletException("Servlet Could not display records.", e);
    }
  }
예제 #11
0
 /** Adds a listener of the given class type to this ServletContext. */
 @Override
 public void addListener(Class<? extends EventListener> listenerClass) {
   if (SecurityUtil.isPackageProtectionEnabled()) {
     doPrivileged(
         "addListener", new Class[] {Class.class}, new Object[] {listenerClass.getName()});
   } else {
     context.addListener(listenerClass);
   }
 }
예제 #12
0
  public JxpSource getJxpServlet(String name) {
    JxpSource source = _httpServlets.get(name);
    if (source != null) return source;

    try {
      Class c = Class.forName(name);
      Object n = c.newInstance();
      if (!(n instanceof HttpServlet))
        throw new RuntimeException("class [" + name + "] is not a HttpServlet");

      HttpServlet servlet = (HttpServlet) n;
      servlet.init(createServletConfig(name));
      source = new ServletSource(servlet);
      _httpServlets.put(name, source);
      return source;
    } catch (Exception e) {
      throw new RuntimeException("can't load [" + name + "]", e);
    }
  }
예제 #13
0
 public static String loadDriver() {
   String sErr = "";
   try {
     java.sql.DriverManager.registerDriver(
         (java.sql.Driver) (Class.forName(DBDriver).newInstance()));
   } catch (Exception e) {
     sErr = e.toString();
   }
   return (sErr);
 }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    PrintWriter out = response.getWriter();
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
      System.out.println("Enrollno: 130050131049");
      // STEP 2: Register JDBC driver
      Class.forName(JDBC_DRIVER);

      // STEP 3: Open a connection
      System.out.println("Connecting to a selected database...");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      System.out.println("Connected database successfully...");

      // STEP 2: Executing query
      String sql = "SELECT * FROM logindetails WHERE name = ?";
      pstmt = conn.prepareStatement(sql);
      pstmt.setString(1, "Krut");

      ResultSet rs = pstmt.executeQuery();
      out.print("| <b>Name</b>| ");
      out.print("<b>Password</b>| ");
      out.println("</br>\n-------------------------------</br>");
      while (rs.next()) {
        out.println();
        out.print("| " + rs.getString(1));
        out.print("| " + rs.getString(2) + "|");
        out.println("</br>");
      }

    } catch (SQLException se) {
      // Handle errors for JDBC
      se.printStackTrace();
    } catch (Exception e) {
      // Handle errors for Class.forName
      e.printStackTrace();
    } finally {
      // finally block used to close resources
      try {
        if (pstmt != null) conn.close();
      } catch (SQLException se) {
      } // do nothing
      try {
        if (conn != null) conn.close();
      } catch (SQLException se) {
        se.printStackTrace();
      } // end finally try
    } // end try
  }
  /**
   * Method called at start of is_summary Tag
   *
   * @return EVAL_BODY if current message while walking a thread is greater than or equal to the
   *     users message_depth but less than the users thread_depth or SKIP_BODY
   */
  public final int doStartTag() throws JspException {
    // Find the parent walk ta
    WalkTag wt = null;
    try {
      wt =
          (WalkTag) this.findAncestorWithClass(this, Class.forName("com.Yasna.forum.tags.WalkTag"));
    } catch (Exception e) {
      return SKIP_BODY;
    }

    if (wt != null && wt.isSummaryMessage()) return EVAL_BODY_INCLUDE;
    return SKIP_BODY;
  }
예제 #16
0
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    try {

      int a;
      a = 3;
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      String url = "jdbc:odbc:books";
      connection = DriverManager.getConnection(url);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #17
0
 public void init(ServletConfig servletconfig) throws ServletException {
   super.init(servletconfig);
   try {
     System.out.println("inside init");
     Class.forName("oracle.jdbc.driver.OracleDriver");
     System.out.println("driver is created");
     con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "care", "care");
     System.out.println("Connection is created");
     st = con.createStatement();
     System.out.println("statement is created");
   } catch (Exception exception) {
     System.out.println(exception);
   }
 }
예제 #18
0
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      Connection con =
          DriverManager.getConnection(Utility.connection, Utility.username, Utility.password);

      String email = request.getParameter("email_id");

      String number = "";
      boolean exists = false;
      String user_name = "";
      int user_id = -1;
      String str1 = "SELECT USER_ID,NAME,PHONE_NUMBER FROM USERS WHERE EMAIL_ID=?";
      PreparedStatement prep1 = con.prepareStatement(str1);
      prep1.setString(1, email);
      ResultSet rs1 = prep1.executeQuery();
      if (rs1.next()) {
        exists = true;
        user_id = rs1.getInt("USER_ID");
        user_name = rs1.getString("NAME");
        number = rs1.getString("PHONE_NUMBER");
      }
      int verification = 0;
      JSONObject data = new JSONObject();
      if (exists) {
        verification = (int) (Math.random() * 9535641 % 999999);
        System.out.println("Number " + number + "\nVerification: " + verification);
        SMSProvider.sendSMS(
            number, "Your One Time Verification Code for PeopleConnect Is " + verification);
      }

      data.put("user_name", user_name);
      data.put("user_id", user_id);
      data.put("verification_code", "" + verification);
      data.put("phone_number", number);

      String toSend = data.toJSONString();
      out.print(toSend);
      System.out.println(toSend);

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      out.close();
    }
  }
예제 #19
0
  /**
   * Gets the value of the given parameter from the request converted to an Object. If the parameter
   * is not set or not parseable, the default value is returned.
   *
   * @param pReq the servlet request
   * @param pName the parameter name
   * @param pType the type of object (class) to return
   * @param pFormat the format to use (might be {@code null} in many cases)
   * @param pDefault the default value
   * @return the value of the parameter converted to a boolean, or the default value, if the
   *     parameter is not set.
   * @throws IllegalArgumentException if {@code pDefault} is non-{@code null} and not an instance of
   *     {@code pType}
   * @throws NullPointerException if {@code pReq}, {@code pName} or {@code pType} is {@code null}.
   * @todo Well, it's done. Need some thinking... We probably don't want default if conversion
   *     fails...
   * @see Converter#toObject
   */
  static <T> T getParameter(
      final ServletRequest pReq,
      final String pName,
      final Class<T> pType,
      final String pFormat,
      final T pDefault) {
    // Test if pDefault is either null or instance of pType
    if (pDefault != null && !pType.isInstance(pDefault)) {
      throw new IllegalArgumentException(
          "default value not instance of " + pType + ": " + pDefault.getClass());
    }

    String str = pReq.getParameter(pName);

    if (str == null) {
      return pDefault;
    }

    try {
      return pType.cast(Converter.getInstance().toObject(str, pType, pFormat));
    } catch (ConversionException ce) {
      return pDefault;
    }
  }
  public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
    try {
      res.setContentType("text/html");
      pw = res.getWriter();
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      con = DriverManager.getConnection("jdbc:odbc:com", "o7it58", "yajiv32737");
      st = con.createStatement();
      pw.println("<html>");
      pw.println("<head><title>Welcome</title></head>");
      pw.println("<body>");

      s = req.getParameter("login");
      if (s.equals("Submit")) {
        uname = req.getParameter("firstname");
        pass = req.getParameter("pwd");
        PrintWriter out = new PrintWriter(new FileWriter("log.txt"), true);
        out.println(uname);
        rs =
            st.executeQuery(
                "select type from login where username='******' and password='******'");
        if (rs.next()) {
          type = rs.getString("type");
        } else {
          pw.println("<center>");
          pw.println("User does not exists");
          pw.println("</center>");
        }
        if (type.equals("admin")) {

          pw.println(
              "<a href=\"http://localhost:8080/servlet/AdminLogin\">Hello Admin.Please Click Here</a>");
        } else if (type.equals("staff")) {
          pw.println(
              "<a href=\"http://localhost:8080/servlet/StaffLogin\">Hello Staff.Please Click Here</a>");
        } else {
          pw.println(
              "<a href=\"http://localhost:8080/servlet/StudentLogin\">Hello Student.Please Click Here</a>");
        }
      }
      pw.println("</body></html>");
    } catch (Exception e) {
    }
  }
예제 #21
0
파일: AddSong.java 프로젝트: mode14/myfavs
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {

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

    /* Get Session */
    HttpSession s = req.getSession(true);
    /* Make sure user is logged in */
    if (s.getAttribute("login") == null || (String) s.getAttribute("login") != "go") {
      req.getRequestDispatcher("login.jsp").forward(req, res);
    }

    try {
      String dbuser = this.getServletContext().getInitParameter("dbuser");
      String dbpassword = this.getServletContext().getInitParameter("dbpassword");

      Class.forName("com.mysql.jdbc.Driver");
      Connection conn =
          DriverManager.getConnection("jdbc:mysql://localhost/project", dbuser, dbpassword);

      Statement stmt = conn.createStatement();
      stmt.execute(
          "INSERT INTO songs VALUES(null, '"
              + req.getParameter("song_name")
              + "', '"
              + req.getParameter("artist")
              + "', '"
              + req.getParameter("album")
              + "', '"
              + req.getParameter("genre")
              + "', 0)");

      stmt.close();
      conn.close();

      // delete memcache since new song is now added
      MemcachedClient c = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
      c.delete("master");

      req.getRequestDispatcher("add_song_success.jsp").forward(req, res);

    } catch (Exception e) {
      out.println(e.getMessage());
    }
  }
예제 #22
0
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      Connection con =
          DriverManager.getConnection(Utility.connection, Utility.username, Utility.password);

      int user_id = Integer.parseInt(request.getParameter("user_id"));
      int question_id = Integer.parseInt(request.getParameter("question_id"));
      int option = Integer.parseInt(request.getParameter("option"));

      System.out.println("uid: " + user_id + "\nquestion: " + question_id + "\noption: " + option);
      String str1 = "INSERT INTO VOTES(USER_ID, QUESTION_ID,OPTION_VOTED) VALUES (?,?,?)";
      PreparedStatement prep1 = con.prepareStatement(str1);
      prep1.setInt(1, user_id);
      prep1.setInt(3, option);
      prep1.setInt(2, question_id);
      prep1.execute();

      String str2 = "SELECT OPTION_" + option + " FROM ARCHIVE_VOTES WHERE QUESTION_ID=?";
      PreparedStatement prep2 = con.prepareStatement(str2);
      prep2.setInt(1, question_id);
      int count = 0;
      ResultSet rs2 = prep2.executeQuery();
      if (rs2.next()) {
        count = rs2.getInt("OPTION_" + option);
      }
      count++;
      String str3 = "UPDATE ARCHIVE_VOTES SET OPTION_" + option + "=? WHERE QUESTION_ID=?";
      PreparedStatement prep3 = con.prepareStatement(str3);
      prep3.setInt(1, count);
      prep3.setInt(2, question_id);
      prep3.executeUpdate();

      out.print("You Vote has been recorded! Thank you!");
      System.out.println(
          "Voted for question " + question_id + ", by user " + user_id + ", for option " + option);

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      out.close();
    }
  }
예제 #23
0
 public void init(ServletConfig sc) throws ServletException {
   super.init(sc);
   try {
     Class.forName("com.mysql.jdbc.Driver");
     System.out.println("driver is loaded");
     con = DriverManager.getConnection(url, un, password);
     System.out.println("connected");
     stmt = con.createStatement();
     System.out.println("wrapper created");
   } catch (ClassNotFoundException cnfe) {
     System.out.println("driver Not Loaded" + cnfe.getMessage());
     return;
   } catch (SQLException sqle) {
     System.out.println("connection problem" + sqle.getMessage());
     return;
   }
 }
예제 #24
0
  public void init() throws ServletException {

    ServletContext context = getServletContext();
    String driver = context.getInitParameter("p1");
    String cs = context.getInitParameter("p2");
    String username = context.getInitParameter("p3");
    String password = context.getInitParameter("p4");

    try {

      Class.forName(driver);
      con = DriverManager.getConnection(cs, username, password);
      ps =
          con.prepareStatement(
              "select * from registration1 where username=? and password=? and user_type=?");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #25
0
 public void service(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   try {
     String username = request.getParameter("t1");
     String password = request.getParameter("t2");
     String email = request.getParameter("t4");
     String college = request.getParameter("t5");
     String phone = request.getParameter("t6");
     String country = request.getParameter("t7");
     String languages = request.getParameter("t8");
     Class.forName("oracle.jdbc.driver.OracleDriver");
     Connection con =
         DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "tiger");
     PreparedStatement pst = con.prepareStatement("insert into stu_tab values(?,?,?,?,?,?,?)");
     pst.setString(1, username);
     pst.setString(2, password);
     pst.setString(3, email);
     pst.setString(4, college);
     pst.setString(5, phone);
     pst.setString(6, country);
     pst.setString(7, languages);
     int i = pst.executeUpdate();
     if (i != 0) {
       out.println("<html><body align=center bgcolor=#C0C0C0 text=black>");
       out.println("<h3>!.. Registration Successful !..</h3>");
       out.println(
           "<a href=Slogin1.html style=text-decoration:none>click here</a>&nbsp;to go back to login page");
       out.println("</body></html>");
     } else {
       out.println("<html><body align=center bgcolor=#C0C0C0 text=black>");
       out.println("<h3>!.. Registration Failed !..</h3>");
       out.println(
           "<a href=Slogin1.html style=text-decoration:none>click here</a>&nbsp;to go back to login page");
       out.println("</body></html>");
     }
   } catch (Exception e) {
     out.println(e);
   }
 }
예제 #26
0
  private Connection getConnectiontoDB() {

    Connection con = null;
    /*	String url = "jdbc:postgresql://10.16.194.69:5432/ls";
    String user = "******";
    String password = "******";*/

    String url = "jdbc:postgresql://localhost:5432/ls";
    String user = "******";
    String password = "******";

    try {

      Class.forName("org.postgresql.Driver");
      con = DriverManager.getConnection(url, user, password);

    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return con;
  }
예제 #27
0
 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   // I use "session" in order to throws the object named user bean.
   HttpSession session = request.getSession(true);
   response.setContentType("text/html");
   request.setCharacterEncoding("UTF-8");
   UserBean ub = (UserBean) session.getAttribute("user");
   if (ub == null) {
     String haveLogin = "******";
     session.setAttribute("haveLogin", haveLogin);
     response.sendRedirect("cart");
   } else {
     String mID = ub.getmID();
     String iID = (String) request.getParameter("iID");
     // String idx = (String)request.getParameter("idx");
     Connection conn = null;
     try {
       // Getting the connection from database.
       Class.forName("com.mysql.jdbc.Driver");
       /*conn = DriverManager
       .getConnection("jdbc:mysql://localhost/se?"
       		+ "user=root");*/
       conn =
           DriverManager.getConnection(
               "jdbc:mysql://localhost/user_register?"
                   + "user=sqluser&password=sqluserpw&useUnicode=true&characterEncoding=UTF-8");
       String sql = "delete from cart_item_mapping where mID=? and iID = ?";
       PreparedStatement pst = conn.prepareStatement(sql);
       // Using preparedstatement by set the parameter related to "?" symbol.
       pst.setString(1, mID);
       pst.setString(2, iID);
       pst.executeUpdate();
       pst.close();
       response.sendRedirect("ShowCartController");
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
예제 #28
0
  /**
   * Gets the current scoreboard and prints the users' names and scores in descending order.
   *
   * @return true if the scoreboard is printed successfully
   */
  private boolean getScoreboard() {
    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      conn =
          DriverManager.getConnection(
              "jdbc:mysql://localhost:3306/getoffthecouch", "XXXXXX", "XXXXXX");

      Statement getScoresStmt = conn.createStatement();
      String getScoresQuery =
          "SELECT user_id, user_name, total_score FROM user ORDER BY total_score DESC";
      ResultSet getScoresResult = getScoresStmt.executeQuery(getScoresQuery);
      String userId = "";
      String userName = "";
      int totalScore = -1;
      while (getScoresResult.next()) {
        userId = getScoresResult.getString("user_id");
        userName = getScoresResult.getString("user_name");
        totalScore = getScoresResult.getInt("total_score");
        out.println(userId + "|" + userName + "|" + totalScore);
      }
      getScoresStmt.close();
      return true;
    } catch (InstantiationException e) {
      e.printStackTrace(out);
      return false;
    } catch (IllegalAccessException e) {
      e.printStackTrace(out);
      return false;
    } catch (ClassNotFoundException e) {
      e.printStackTrace(out);
      return false;
    } catch (SQLException e) {
      e.printStackTrace(out);
      return false;
    }
  }
예제 #29
0
  protected void processConfiguration(FilterConfig filterConfig) {
    InputStream is;

    if (isNullOrEmpty(this.configFile)) {
      is = servletContext.getResourceAsStream(CONFIG_FILE_LOCATION);
    } else {
      try {
        is = new FileInputStream(this.configFile);
      } catch (FileNotFoundException e) {
        throw logger.samlIDPConfigurationError(e);
      }
    }

    PicketLinkType picketLinkType;

    String configurationProviderName = filterConfig.getInitParameter(CONFIGURATION_PROVIDER);

    if (configurationProviderName != null) {
      try {
        Class<?> clazz = SecurityActions.loadClass(getClass(), configurationProviderName);

        if (clazz == null) {
          throw new ClassNotFoundException(ErrorCodes.CLASS_NOT_LOADED + configurationProviderName);
        }

        this.configProvider = (SAMLConfigurationProvider) clazz.newInstance();
      } catch (Exception e) {
        throw new RuntimeException(
            "Could not create configuration provider [" + configurationProviderName + "].", e);
      }
    }

    try {
      // Work on the IDP Configuration
      if (configProvider != null) {
        try {
          if (is == null) {
            // Try the older version
            is =
                servletContext.getResourceAsStream(
                    GeneralConstants.DEPRECATED_CONFIG_FILE_LOCATION);

            // Additionally parse the deprecated config file
            if (is != null && configProvider instanceof AbstractSAMLConfigurationProvider) {
              ((AbstractSAMLConfigurationProvider) configProvider).setConfigFile(is);
            }
          } else {
            // Additionally parse the consolidated config file
            if (is != null && configProvider instanceof AbstractSAMLConfigurationProvider) {
              ((AbstractSAMLConfigurationProvider) configProvider).setConsolidatedConfigFile(is);
            }
          }

          picketLinkType = configProvider.getPicketLinkConfiguration();
          picketLinkType.setIdpOrSP(configProvider.getSPConfiguration());
        } catch (ProcessingException e) {
          throw logger.samlSPConfigurationError(e);
        } catch (ParsingException e) {
          throw logger.samlSPConfigurationError(e);
        }
      } else {
        if (is != null) {
          try {
            picketLinkType = ConfigurationUtil.getConfiguration(is);
          } catch (ParsingException e) {
            logger.trace(e);
            throw logger.samlSPConfigurationError(e);
          }
        } else {
          is = servletContext.getResourceAsStream(GeneralConstants.DEPRECATED_CONFIG_FILE_LOCATION);
          if (is == null) {
            throw logger.configurationFileMissing(configFile);
          }

          picketLinkType = new PicketLinkType();

          picketLinkType.setIdpOrSP(ConfigurationUtil.getSPConfiguration(is));
        }
      }

      // Close the InputStream as we no longer need it
      if (is != null) {
        try {
          is.close();
        } catch (IOException e) {
          // ignore
        }
      }

      Boolean enableAudit = picketLinkType.isEnableAudit();

      // See if we have the system property enabled
      if (!enableAudit) {
        String sysProp = SecurityActions.getSystemProperty(GeneralConstants.AUDIT_ENABLE, "NULL");
        if (!"NULL".equals(sysProp)) {
          enableAudit = Boolean.parseBoolean(sysProp);
        }
      }

      if (enableAudit) {
        if (auditHelper == null) {
          String securityDomainName = PicketLinkAuditHelper.getSecurityDomainName(servletContext);

          auditHelper = new PicketLinkAuditHelper(securityDomainName);
        }
      }

      SPType spConfiguration = (SPType) picketLinkType.getIdpOrSP();
      processIdPMetadata(spConfiguration);

      this.serviceURL = spConfiguration.getServiceURL();
      this.canonicalizationMethod = spConfiguration.getCanonicalizationMethod();
      this.picketLinkConfiguration = picketLinkType;

      this.issuerID = filterConfig.getInitParameter(ISSUER_ID);
      this.characterEncoding = filterConfig.getInitParameter(CHARACTER_ENCODING);
      this.samlHandlerChainClass = filterConfig.getInitParameter(SAML_HANDLER_CHAIN_CLASS);

      logger.samlSPSettingCanonicalizationMethod(canonicalizationMethod);
      XMLSignatureUtil.setCanonicalizationMethodType(canonicalizationMethod);

      try {
        this.initKeyProvider();
        this.initializeHandlerChain(picketLinkType);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }

      logger.trace("Identity Provider URL=" + getConfiguration().getIdentityURL());
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    HttpSession session = request.getSession(true);

    try {
      Object accountObject = session.getValue(ACCOUNT);

      // If no account object was put in the session, or
      // if one exists but it is not a hashtable, then
      // redirect the user to the original login page

      if (accountObject == null)
        throw new RuntimeException("You need to log in to use this service!");

      if (!(accountObject instanceof Hashtable))
        throw new RuntimeException("You need to log in to use this service!");

      Hashtable account = (Hashtable) accountObject;

      String userName = (String) account.get("name");

      //////////////////////////////////////////////
      // Display Messages for the user who logged in
      //////////////////////////////////////////////
      out.println("<HTML>");
      out.println("<HEAD>");
      out.println("<TITLE>Contacts for " + userName + "</TITLE>");
      out.println("</HEAD>");
      out.println("<BODY BGCOLOR='#EFEFEF'>");
      out.println("<H3>Welcome " + userName + "</H3>");

      out.println("<CENTER>");

      Connection con = null;
      Statement stmt = null;
      ResultSet rs = null;
      try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        con =
            DriverManager.getConnection(
                "jdbc:mysql://localhost/contacts?user=kareena&password=kapoor");

        stmt = con.createStatement();
        rs =
            stmt.executeQuery(
                "SELECT * FROM contacts WHERE userName='******' ORDER BY contactID");

        out.println("<form name='deleteContactsForm' method='post' action='deleteContact'>");

        out.println("<TABLE BGCOLOR='#EFEFFF' CELLPADDING='2' CELLSPACING='4' BORDER='1'>");
        out.println("<TR BGCOLOR='#D6DFFF'>");
        out.println("<TD ALIGN='center'><B>Contact ID</B></TD>");
        out.println("<TD ALIGN='center'><B>Contact Name</B></TD>");
        out.println("<TD ALIGN='center'><B>Comment</B></TD>");
        out.println("<TD ALIGN='center'><B>Date</B></TD>");
        out.println("<TD ALIGN='center'><B>Delete Contacts</B></TD>");
        out.println("</TR>");

        int nRows = 0;
        while (rs.next()) {
          nRows++;
          String messageID = rs.getString("contactID");
          String fromUser = rs.getString("contactName");
          String message = rs.getString("comments");
          String messageDate = rs.getString("dateAdded");

          out.println("<TR>");
          out.println("<TD>" + messageID + "</TD>");
          out.println("<TD>" + fromUser + "</TD>");
          out.println("<TD>" + message + "</TD>");
          out.println("<TD>" + messageDate + "</TD>");
          out.println(
              "<TD><input type='checkbox' name='msgList' value='" + messageID + "'> Delete</TD>");
          out.println("</TR>");
        }

        out.println("<TR>");
        out.println(
            "<TD COLSPAN='6' ALIGN='center'><input type='submit' value='Delete Selected Contacts'></TD>");
        out.println("</TR>");

        out.println("</TABLE>");
        out.println("</FORM>");
      } catch (Exception e) {
        out.println("Could not connect to the users database.<P>");
        out.println("The error message was");
        out.println("<PRE>");
        out.println(e.getMessage());
        out.println("</PRE>");
      } finally {
        if (rs != null) {
          try {
            rs.close();
          } catch (SQLException ignore) {
          }
        }
        if (stmt != null) {
          try {
            stmt.close();
          } catch (SQLException ignore) {
          }
        }
        if (con != null) {
          try {
            con.close();
          } catch (SQLException ignore) {
          }
        }
      }

      out.println("</CENTER>");
      out.println("</BODY>");
      out.println("</HTML>");

    } catch (RuntimeException e) {
      out.println("<script language=\"javascript\">");
      out.println("alert(\"You need to log in to use this service!\");");
      out.println("</script>");

      out.println("<a href='index.html'>Click Here</a> to go to the main page.<br><br>");

      out.println(
          "Or Click on the button to exit<FORM><INPUT onClick=\"javascipt:window.close()\" TYPE=\"BUTTON\" VALUE=\"Close Browser\" TITLE=\"Click here to close window\" NAME=\"CloseWindow\" STYLE=\"font-family:Verdana, Arial, Helvetica; font-size:smaller; font-weight:bold\"></FORM>");

      log(e.getMessage());
      return;
    }
  }