/**
   * Sets an application attribute.
   *
   * @param name the name of the attribute
   * @param value the value of the attribute
   */
  public void setAttribute(String name, Object value) {
    Object oldValue;

    synchronized (_attributes) {
      if (value != null) oldValue = _attributes.put(name, value);
      else oldValue = _attributes.remove(name);
    }

    // Call any listeners
    if (_applicationAttributeListeners != null) {
      ServletContextAttributeEvent event;

      if (oldValue != null) event = new ServletContextAttributeEvent(this, name, oldValue);
      else event = new ServletContextAttributeEvent(this, name, value);

      for (int i = 0; i < _applicationAttributeListeners.size(); i++) {
        ServletContextAttributeListener listener;

        Object objListener = _applicationAttributeListeners.get(i);
        listener = (ServletContextAttributeListener) objListener;

        try {
          if (oldValue != null) listener.attributeReplaced(event);
          else listener.attributeAdded(event);
        } catch (Exception e) {
          log.log(Level.FINE, e.toString(), e);
        }
      }
    }
  }
Пример #2
0
  String formatScriptResultHTML(
      String script, Object result, Exception error, StringBuffer scriptOutput) throws IOException {
    SimpleTemplate tmplt;

    if (error != null) {
      tmplt = new SimpleTemplate(getClass().getResource("error.template"));

      String errString;

      if (error instanceof bsh.EvalError) {
        int lineNo = ((EvalError) error).getErrorLineNumber();
        String msg = error.getMessage();
        int contextLines = 4;
        errString = escape(msg);
        if (lineNo > -1) errString += "<hr>" + showScriptContextHTML(script, lineNo, contextLines);
      } else errString = escape(error.toString());

      tmplt.replace("error", errString);
    } else {
      tmplt = new SimpleTemplate(getClass().getResource("result.template"));
      tmplt.replace("value", escape(String.valueOf(result)));
      tmplt.replace("output", escape(scriptOutput.toString()));
    }

    return tmplt.toString();
  }
Пример #3
0
 static {
   try {
   } catch (Exception e) {
     e.printStackTrace();
     throw new RuntimeException(e);
   }
 }
Пример #4
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();
    }
  }
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   ProfesorRepository profesores = (ProfesorRepository) context.getBean("profesorRepository");
   try {
     String id = request.getParameter("id");
     int idProf = Integer.parseInt(id);
     String cedula = request.getParameter("cedula");
     String nombre = request.getParameter("nombre");
     String titulo = request.getParameter("titulo");
     String area = request.getParameter("area");
     String telefono = request.getParameter("telefono");
     Profesor prof = profesores.findProfesor(idProf);
     try {
       if (cedula != null) prof.setCedula(cedula);
       if (nombre != null) prof.setNombre(nombre);
       if (titulo != null) prof.setTitulo(titulo);
       if (area != null) prof.setArea(area);
       if (telefono != null) prof.setTelefono(telefono);
       profesores.updateProfesor(prof);
     } catch (Exception e) {
     }
     response.sendRedirect("listaProfesores");
   } catch (Exception e) {
     request.setAttribute("mensaje", e.getMessage());
     forward("/paginaError.jsp", request, response);
   }
 }
Пример #6
0
 protected collegeTable getCollege(String id, Connection con) throws SQLException {
   try {
     ResultSet rs = null;
     Statement statement = con.createStatement();
     rs =
         statement.executeQuery(
             "SELECT * FROM "
                 + TABLECOLLEGES
                 + " WHERE "
                 + collegeTable.ID
                 + " = "
                 + id
                 + " LIMIT 1");
     // if found
     if (rs.next()) {
       collegeTable table = new collegeTable();
       table.setID(id);
       table.setShort(rs.getString(collegeTable.SHORTNAME));
       table.setFull(rs.getString(collegeTable.FULLNAME));
       return table;
     } else {
       return null; // not found
     }
   } catch (Exception e) {
     log.writeException(e.getMessage());
     throw new SQLException(e.getMessage());
   }
 } // end getCollege
  public void service(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

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

    try {
      userObj = new User();
      tmsManager = new TMSManager();

      RequestDispatcher rd1 = request.getRequestDispatcher("./header");
      rd1.include(request, response);

      out.println("<html><head><title>UpdateUser</title></head>");
      out.println("<body onload=onSubmit() bgcolor =\"#ffcc00\">");
      out.println("<form  method =\"POST\"  action =\"./updateUser\" ><br><br><br>");
      out.println("<table border = 1 width = \"40%\" align = \"center\" bgcolor = \"#bbccff\">");
      out.println("<caption><b>UpdateUser</b></caption>");
      out.println("<tr><td style = font face: verdana>Enter User ID</td>");
      out.println("<td><input type = \"text\" name = \"user_id\" ></td></tr>");
      out.println(
          "<tr><td colspan = 2 align = \"center\"><input type = \"submit\"  name = \"Submit\" value = \"Submit\">");
      out.println("<input type = \"Reset\"  name = \"Reset\" value = \"Clear\"></td></tr>");
      out.println("</table>");
      out.println("</body></html>");

      // String user_id = request.getParameter("user_id");
      //    userObj = tmsManager.getUser(user_id);
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }

    RequestDispatcher rd2 = request.getRequestDispatcher("./footer");
    rd2.include(request, response);
  }
Пример #8
0
  // getListOfSharesByType -
  private Map<String, String> getListOfSharesByType(
      String type, HttpServletRequest request, HttpServletResponse response) {
    Map<String, String> allShares = new HashMap<String, String>();

    // publishedSources - array of source._ids of published sources
    ArrayList<String> publishedSources = new ArrayList<String>();
    try {
      JSONObject sharesObject = new JSONObject(searchSharesByType(type, request, response));
      JSONObject json_response = sharesObject.getJSONObject("response");

      if (json_response.getString("success").equalsIgnoreCase("true")) {
        if (sharesObject.has("data")) {
          // Iterate over share objects and write to our collection
          JSONArray shares = sharesObject.getJSONArray("data");
          for (int i = 0; i < shares.length(); i++) {
            JSONObject share = shares.getJSONObject(i);
            allShares.put(share.getString("title"), share.getString("_id"));
          }
        }
      }
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
    return allShares;
  }
Пример #9
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter writer = response.getWriter();
    HttpSession session = request.getSession();

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String type = request.getParameter("type");
    System.out.println(username + password + type);

    session.setAttribute("user", username);

    try {
      writer.println("<html>");
      writer.println("<body bgcolor=green>");
      writer.println("<center>");
      ps.setString(1, username);
      ps.setString(2, password);
      ps.setString(3, type);
      ResultSet rs = ps.executeQuery();

      if (rs.next()) {
        writer.println("<h1>LOGIN SUCCESSFUL</h1><br><br>");
        writer.println("<a href=account.html>click here to see your account</a>");
      } else {
        writer.println("<h1>LOGIN FAILED</h1><br><br>");
        writer.println("<a href=login.html>click here to login again</a>");
      }
      writer.println("</center>");
      writer.println("</body>");
      writer.println("</html>");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #10
0
  public ActionForward execute(
      ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      GpsImportForm gpsForm = (GpsImportForm) form;
      User user = (User) req.getSession().getAttribute("user");
      int entryId = gpsForm.getEntryId();
      String fileName = gpsForm.getFileName();
      String title = gpsForm.getTitle();
      String activityId = gpsForm.getActivityId();
      String xml = gpsForm.getXml();
      log.debug(xml);

      List<GpsTrack> tracks = new TcxParser().parse(xml.getBytes());
      GpsTrack track = tracks.get(0); // Horrible hack.
      createAttachment(user, entryId, fileName, title, activityId, track);
      createGeotag(fileName, track);

      req.setAttribute("status", "success");
      req.setAttribute("message", "");
      log.debug("Returning status: success.");
      return mapping.findForward("results");
    } catch (Exception e) {
      log.fatal("Error processing incoming Garmin XML", e);
      req.setAttribute("status", "failure");
      req.setAttribute("message", e.toString());
      return mapping.findForward("results");
    }
  }
Пример #11
0
  public synchronized void service(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    HttpSession dbSession = request.getSession();
    JspFactory _jspxFactory = JspFactory.getDefaultFactory();
    PageContext pageContext =
        _jspxFactory.getPageContext(this, request, response, "", true, 8192, true);
    ServletContext dbApplication = dbSession.getServletContext();

    ServletContext application;
    HttpSession session = request.getSession();
    nseer_db_backup1 finance_db = new nseer_db_backup1(dbApplication);

    try {

      if (finance_db.conn((String) dbSession.getAttribute("unit_db_name"))) {
        String finance_cheque_id = request.getParameter("finance_cheque_id");
        String sql = "delete from finance_bill where id='" + finance_cheque_id + "'";
        finance_db.executeUpdate(sql);
        finance_db.commit();
        finance_db.close();

      } else {
        response.sendRedirect("error_conn.htm");
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Пример #12
0
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   EstacionBombeoModule module = (EstacionBombeoModule) context.getBean("estacionBombeoModule");
   try {
     String presionSalida = request.getParameter("presionSalida");
     int presionSalidaObj = Integer.parseInt(presionSalida);
     String presionEntrada = request.getParameter("presionEntrada");
     int presionEntradaObj = Integer.parseInt(presionEntrada);
     String cantidadBombas = request.getParameter("cantidadBombas");
     int cantidadBombasObj = Integer.parseInt(cantidadBombas);
     String capacidadMaxima = request.getParameter("capacidadMaxima");
     int capacidadMaximaObj = Integer.parseInt(cantidadBombas);
     String idAcueducto = request.getParameter("idAcueducto");
     int idAcueductoObj = Integer.parseInt(idAcueducto);
     String encargado = request.getParameter("encargado");
     String tipo = request.getParameter("tipo");
     String telefono = request.getParameter("telefono");
     String nombreEstacion = request.getParameter("nombreEstacion");
     module.insertar(
         presionSalidaObj,
         tipo,
         capacidadMaximaObj,
         cantidadBombasObj,
         encargado,
         telefono,
         presionEntradaObj,
         idAcueductoObj,
         nombreEstacion);
     response.sendRedirect("listaEstacionBombeos");
   } catch (Exception e) {
     request.setAttribute("mensaje", e.getMessage());
     forward(e.getMessage(), request, response);
   }
 }
Пример #13
0
 private void doMailBackup() {
   try {
     rmtApi.createConfigBackupFile(RemoteApi.BackupFileDisposition.Mail);
   } catch (Exception e) {
     errMsg = "Error: " + e.getMessage();
   }
 }
Пример #14
0
 public void destroy() {
   super.destroy();
   try {
     link.close();
   } catch (Exception e) {
     System.err.println(e.getMessage());
   }
 }
 public ServletInputStream getInputStream() {
     try {
         bais = new ByteArrayInputStream(buffer);
         bsis = new BufferedServletRequestStream(bais);
     } catch (Exception ex) {
         ex.printStackTrace();
     }
     return bsis;
 }
Пример #16
0
 public void destroy() {
   try {
     // session.close();
     ps.close();
     con.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Пример #17
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    try {

      request.setAttribute("body", "/WEB-INF/jsp/testimonial.jsp");
      layoutPage.forward(request, response);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #18
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());
  }
Пример #19
0
  public static void init() throws ServletException {
    try {
      // récupération de la source de donnée
      Context initCtx = new InitialContext();
      ds = (DataSource) initCtx.lookup("java:comp/env/jdbc/digitlibpool");

    } catch (Exception e) {
      throw new UnavailableException(e.getMessage());
    }
  }
Пример #20
0
 private void forceV3Poll() {
   ArchivalUnit au = getAu();
   if (au == null) return;
   try {
     callV3ContentPoll(au);
   } catch (Exception e) {
     log.error("Can't start poll", e);
     errMsg = "Error: " + e.toString();
   }
 }
Пример #21
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);
 }
Пример #22
0
 // This happens very early - check it.
 static {
   try {
     log = LogFactory.getLog(Servlet.class);
   } catch (Exception ex) {
     System.err.println("Exception creating the logger");
     System.err.println("Commons logging jar files in WEB-INF/lib/?");
     System.err.println(ex.getMessage());
     // ex.printStackTrace(System.err) ;
   }
 }
Пример #23
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    try {
      System.out.println(request.getReader().readLine());
    } catch (Exception e) {
      // e.printStackTrace();
      _log.error(" error " + e.getMessage());
    }
  }
 /*
  * Inicialización del servlet
  */
 public final void init() throws ServletException {
   try {
     // new es.tid.frawa.common.TdiFrawaTraceListener().trace(getClass().getName() + ".init()");
     new es.tid.frawa.common.TdiFrawaTraceListener().trace(getClass().getName() + ".init()");
     frawaInit();
   } catch (Exception e) {
     // new es.tid.frawa.common.TdiFrawaTraceListener().trace(e);
     new es.tid.frawa.common.TdiFrawaTraceListener().trace(e);
     throw new ServletException(getClass().getName() + ".init() " + e.getMessage());
   }
 }
Пример #25
0
  private Connection getConnection() {
    Connection con = null;
    try {

      con = new MyConnection().getConnection();
    } catch (Exception e) {
      // System.out.println(e);
      e.printStackTrace();
    }
    return con;
  }
Пример #26
0
  public void destroy() {
    try {
      System.out.println("Stopping Penrose Server...");
      penroseServer.stop();

      System.out.println("Penrose Server stopped.");

    } catch (Exception e) {
      System.out.println("Failed stopping Penrose Server: " + e.getMessage());
    }
  }
 /**
  * Utilizado como controlador de página para la acción de listar medidores.
  *
  * @param request
  * @param response
  * @throws ServletException
  * @throws IOException
  */
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   MedidorModule module = (MedidorModule) context.getBean("medidorModule");
   try {
     List data = module.listado();
     request.setAttribute("medidores", data);
     forward("/listaMedidores.jsp", request, response);
   } catch (Exception e) {
     request.setAttribute("mensaje", e.getMessage());
     forward("/paginaError.jsp", request, response);
   }
 }
Пример #28
0
 public boolean processParams(HttpServletRequest request) {
   try {
     if (request.getParameter("case") != null) {
       tc = request.getParameter("case");
     }
     return true;
   } catch (Exception ex) {
     System.err.println("Exception when processing the request params");
     ex.printStackTrace();
     return false;
   }
 }
Пример #29
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");
      }
    }
  }
Пример #30
0
  /**
   * this is the main method of the servlet that will service all get requests.
   *
   * @param request HttpServletRequest
   * @param responce HttpServletResponce
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = null;
    try {
      try {
        session = request.getSession(true);
      } catch (Exception e) {
        Log.error(e, "PingSession2.doGet(...): error getting session");
        // rethrow the exception for handling in one place.
        throw e;
      }

      // Get the session data value
      Integer ival = (Integer) session.getAttribute("sessiontest.counter");
      // if there is not a counter then create one.
      if (ival == null) {
        ival = new Integer(1);
      } else {
        ival = new Integer(ival.intValue() + 1);
      }
      session.setAttribute("sessiontest.counter", ival);
      // if the session count is equal to five invalidate the session
      if (ival.intValue() == 5) {
        session.invalidate();
      }

      try {
        // Output the page
        response.setContentType("text/html");
        response.setHeader("SessionTrackingTest-counter", ival.toString());

        PrintWriter out = response.getWriter();
        out.println(
            "<html><head><title>Session Tracking Test 2</title></head><body><HR><BR><FONT size=\"+2\" color=\"#000066\">HTTP Session Test 2: Session create/invalidate <BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time: "
                + initTime
                + "</FONT><BR><BR>");
        hitCount++;
        out.println(
            "<B>Hit Count: " + hitCount + "<BR>Session hits: " + ival + "</B></body></html>");
      } catch (Exception e) {
        Log.error(e, "PingSession2.doGet(...): error getting session information");
        // rethrow the exception for handling in one place.
        throw e;
      }

    } catch (Exception e) {
      // log the excecption
      Log.error(e, "PingSession2.doGet(...): error.");
      // set the server responce to 500 and forward to the web app defined error page
      response.sendError(500, "PingSession2.doGet(...): error. " + e.toString());
    }
  } // end of the method