public void init(final ServletContext context, final Map<String, String> paras) {
   _startTime = new Date();
   _context = context;
   _sipFactory = (SipFactory) context.getAttribute(ServletContextConstants.SIP_FACTORY);
   _mrcpFactory = (MrcpFactory) context.getAttribute(ServletContextConstants.MRCP_FACTORY);
   _appJarUrl =
       _context.getRealPath("/")
           + "WEB-INF"
           + File.separator
           + "lib"
           + File.separator
           + "tropo.jar";
   _cache = Collections.synchronizedMap(new WeakHashMap<Object, Application>());
   _tmx = ManagementFactory.getThreadMXBean();
   _mmx = ManagementFactory.getMemoryMXBean();
   try {
     _tropoBuildDate = Utils.getManifestAttribute(_appJarUrl, "Build-Date");
   } catch (final IOException t) {
     LOG.error(t.toString(), t);
     _tropoBuildDate = "Unknown";
   }
   try {
     _tropoVersionNo = Utils.getManifestAttribute(_appJarUrl, "Version-No");
   } catch (final IOException t) {
     LOG.error(t.toString(), t);
     _tropoVersionNo = "Unknown";
   }
   try {
     _tropoBuildNo = Utils.getManifestAttribute(_appJarUrl, "Build-No");
   } catch (final IOException t) {
     LOG.error(t.toString(), t);
     _tropoBuildNo = "Unknown";
   }
   LOG.info(toString() + " / " + getVersionNo() + " / " + getBuildNo());
 }
  @Override
  public void contextInitialized(ServletContextEvent sce) {

    ServletContext context = sce.getServletContext();
    cdiContainer = (CdiContainer) context.getAttribute("org.ops4j.pax.cdi.container");
    cdiContainer.start(context);
    WeldManager manager = cdiContainer.unwrap(WeldManager.class);

    CdiInstanceFactoryBuilder builder = new CdiInstanceFactoryBuilder(manager);
    @SuppressWarnings("unchecked")
    Map<String, Object> attributes =
        (Map<String, Object>) context.getAttribute("org.ops4j.pax.web.attributes");
    if (attributes != null) {
      attributes.put("org.ops4j.pax.cdi.ClassIntrospecter", builder);
      log.info("registered CdiInstanceFactoryBuilder for Undertow");
    }
    context.setAttribute("org.ops4j.pax.cdi.BeanManager", cdiContainer.getBeanManager());

    JspFactory jspFactory = JspFactory.getDefaultFactory();
    if (jspFactory != null) {
      JspApplicationContext jspApplicationContext = jspFactory.getJspApplicationContext(context);

      jspApplicationContext.addELResolver(manager.getELResolver());
      jspApplicationContext.addELContextListener(new WeldELContextListener());
    }
    super.contextInitialized(sce);
  }
Ejemplo n.º 3
0
  /**
   * Does the user sending the HttpServletRequest have the administrator ACLs? If it isn't the case,
   * response will be modified to send an error to the user.
   *
   * @param servletContext
   * @param request
   * @param response used to send the error response if user does not have admin access.
   * @return true if admin-authorized, false otherwise
   * @throws IOException
   */
  static boolean hasAdministratorAccess(
      ServletContext servletContext, HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    Configuration conf = (Configuration) servletContext.getAttribute(CONF_CONTEXT_ATTRIBUTE);
    // If there is no authorization, anybody has administrator access.
    if (!conf.getBoolean(CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, false)) {
      return true;
    }

    String remoteUser = request.getRemoteUser();
    if (remoteUser == null) {
      response.sendError(
          HttpServletResponse.SC_UNAUTHORIZED,
          "Unauthenticated users are not " + "authorized to access this page.");
      return false;
    }

    if (servletContext.getAttribute(ADMINS_ACL) != null
        && !userHasAdministratorAccess(servletContext, remoteUser)) {
      response.sendError(
          HttpServletResponse.SC_UNAUTHORIZED,
          "User " + remoteUser + " is unauthorized to access this page.");
      return false;
    }

    return true;
  }
Ejemplo n.º 4
0
 @Override
 public void init(ServletConfig config) throws ServletException {
   super.init(config);
   ServletContext context = config.getServletContext();
   recommender = (OryxRecommender) context.getAttribute(RECOMMENDER_KEY);
   rescorerProvider = (RescorerProvider) context.getAttribute(RESCORER_PROVIDER_KEY);
 }
  public void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
      out.println("<!DOCTYPE html>");
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet E2</title>");
      out.println("</head>");
      out.println("<body>");
      ServletContext sc = getServletContext();

      out.println("<h2> Your Result:</h2>");
      Integer scoree = (Integer) sc.getAttribute("score");
      Integer size = (Integer) sc.getAttribute("bankSize");
      int passingScore = (int) (0.60 * size);

      if (scoree >= passingScore) {
        out.println("<h2> Congratulations!!!</h2>" + scoree);
        double percentage = 100 * scoree / size;
        out.println("<h3> YOU GOT&nbsp" + percentage + "!!</h3>");

      } else {

        out.println("<h2> SORRY You Failed!!!</h2>");
        double percentage = 100 * scoree / size;
        out.println("<h3> YOU GOT&nbsp" + percentage + "!!</h3>");
      }
      out.println("</body>");
      out.println("</html>");
    } catch (Exception e) {
      System.out.println("Exception in Servlet CalculateResult");
    }
  }
Ejemplo n.º 6
0
 private boolean findOnlineUser(String userid) {
   HttpSession session = request.getSession();
   ServletContext application = (ServletContext) session.getServletContext();
   ArrayList users = (ArrayList) application.getAttribute("users");
   HashMap ipUser = (HashMap) application.getAttribute("ipusers");
   if (null != users && users.contains(userid)) {
     if (ipUser != null
         && ((String) ipUser.get(userid)).equals((String) request.getRemoteAddr())) {
       session.setAttribute("username", userid);
       return true;
     } else {
       return false;
     }
   } else {
     session.setAttribute("username", userid);
     if (users == null) {
       users = new ArrayList();
     }
     users.add(userid);
     if (ipUser == null) {
       ipUser = new HashMap();
     }
     ipUser.put(userid, request.getRemoteAddr());
     application.setAttribute("ipusers", ipUser);
     application.setAttribute("users", users);
     return true;
   }
 }
Ejemplo n.º 7
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    ServletContext context = getServletContext();
    int nuc = 0;
    if (context.getAttribute("nowUserCnt") != null) {
      nuc = (Integer) context.getAttribute("nowUserCnt");
    }

    HttpSession session = request.getSession();
    if (session.getAttribute("isLogin") == null) {
      // response.encodeRedirectURL("/board/login");
      response.sendRedirect("/board/login");
      return;
    }

    // 1. model에서 데이터 조회
    List<Board> boards = boardRepository.getBoards();

    for (Board board : boards) {
      System.out.println("board = " + board);
    }

    // 2. request에 데이터 셋팅
    request.setAttribute("boards", boards);
    request.setAttribute("nowUserCnt", nuc);

    // 3. jsp찾아서 이동
    RequestDispatcher view = request.getRequestDispatcher("/board/boardList.jsp");
    view.forward(request, response);
  }
Ejemplo n.º 8
0
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    ServletContext sc = request.getServletContext();
    SessionFactory sf = (SessionFactory) sc.getAttribute("sf");
    Session session = sf.openSession();
    log.trace("paso por la  sf.openSession()");

    int n_petis = (int) sc.getAttribute("contador");
    n_petis++;
    sc.setAttribute("contador", n_petis);

    String s_id = request.getParameter("id");
    int id = Integer.parseInt(s_id);
    EmployessServices es = new EmployessServices();
    InterfacRecuperable iRecuperable = new EmpleadoHibertDao();
    es.setiRecuperable(iRecuperable);

    Employees emp = (Employees) es.leerEmpleado(id);
    if (emp != null) {
      response.setContentType("text/html");
      request.setAttribute("empleadoBean", emp);
      request.getRequestDispatcher("/MostrarEmpleadoEL.jsp").forward(request, response);
      log.trace(" paso por el....................................");
    } else {
      log.error("El número o carazter introducido es incorrecto");
    }
  }
Ejemplo n.º 9
0
  public boolean loadQuestionRevision(HttpSession session, Long questionNumber) {

    String countryrevision = ConcurrencyKeys.COUNTRY_REVISION.toString();

    User usr = (User) session.getAttribute(SESSION_USER);
    String iso3 = UserUtil.getSingleIso3(usr);

    QuestionsUserTable qut = (QuestionsUserTable) context.getAttribute(USER_MAP_NAME);
    if (qut == null) {
      qut = new QuestionsUserTable();
      context.setAttribute(USER_MAP_NAME, qut);
      context.getAttribute(USER_MAP_NAME);
    }
    boolean amITheFirst = qut.amITheFirst(usr, questionNumber.intValue());
    qut.addUser(usr, questionNumber.intValue());

    session.removeAttribute(countryrevision);

    Question question = surveyService.findQuestion(questionNumber);
    Country countryEntity = surveyService.searchCountry(iso3);

    QuestionRevision qr = surveyService.getQuestionRevisionNumber(countryEntity, question);
    if (qr == null) {
      QuestionRevision qrNew = new QuestionRevision();
      qrNew.setVersion(0l);
      qrNew.setQuestion(question);
      qrNew.setCountry(countryEntity);
      surveyService.insertQuestionRevisionNumber(qrNew);
      qr = surveyService.getQuestionRevisionNumber(countryEntity, question);
    }
    session.setAttribute(countryrevision, qr);

    return amITheFirst;
  }
 @Override
 public void init() throws ServletException {
   super.init();
   ServletContext context = this.getServletContext();
   nnConf = (Configuration) context.getAttribute("name.conf");
   nn = (NameNode) context.getAttribute("name.node");
 }
 public void init(ServletConfig config) throws ServletException {
   super.init(config);
   ServletContext sc = config.getServletContext();
   ICP = (InterfaceCachePojo) sc.getAttribute("ICP");
   useInterfaceCaching = (String) sc.getAttribute("useInterfaceCaching");
   defaultCacheName = (String) sc.getAttribute("DefaultCacheName");
 }
 /**
  * @param filterInvocation
  * @return
  */
 @SuppressWarnings("unchecked")
 private Map<String, Set<String>> getUrlAuthorities(FilterInvocation filterInvocation) {
   ServletContext servletContext =
       filterInvocation.getHttpRequest().getSession().getServletContext();
   this.roleUrlsMap = (Map<String, Set<String>>) servletContext.getAttribute("urlAuthorities");
   return (Map<String, Set<String>>) servletContext.getAttribute("urlAuthorities");
 }
Ejemplo n.º 13
0
 /** Run once when servlet loaded. */
 public void init(ServletConfig config) throws ServletException {
   super.init(config);
   context = config.getServletContext();
   theApp = (LockssApp) context.getAttribute(ServletManager.CONTEXT_ATTR_LOCKSS_APP);
   servletMgr = (ServletManager) context.getAttribute(ServletManager.CONTEXT_ATTR_SERVLET_MGR);
   if (theApp instanceof LockssDaemon) {
     acctMgr = getLockssDaemon().getAccountManager();
   }
 }
  @SuppressWarnings("unchecked")
  protected void peek() {
    ServletContext application = getActionServlet().getServletContext();
    HttpSession session = getSession();

    ApplicationContext wac =
        (ApplicationContext)
            application.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    logger.debug(wac);

    ApplicationContext parent = wac.getParent();
    if (parent != null) logger.debug(parent.toString());

    for (String n : wac.getBeanDefinitionNames()) {
      logger.debug(n);
    }

    // notice the dot . in the key name!
    wac =
        (ApplicationContext)
            application.getAttribute("org.springframework.web.struts.ContextLoaderPlugIn.CONTEXT.");
    if (wac != null) {
      logger.debug("struts ContextLoaderPlugIn context");
      for (String n : wac.getBeanDefinitionNames()) {
        logger.debug(n);
      }
    } else {
      logger.debug("ContextLoaderPlugIn ac is null");
    }
    parent = wac.getParent();
    if (parent != null) {
      logger.debug("Parent = " + parent.toString());
    }

    logger.debug("Servlet context");
    for (Enumeration e = application.getAttributeNames(); e.hasMoreElements(); ) {
      String key = (String) e.nextElement();
      String s = String.format("%s=%s", key, application.getAttribute(key));
      logger.debug(s);
    }

    logger.debug("Session");
    for (Enumeration e = session.getAttributeNames(); e.hasMoreElements(); ) {
      String key = (String) e.nextElement();
      String s = String.format("%s=%s", key, session.getAttribute(key));
      logger.debug(s);
    }

    logger.debug("request attributes:");
    HttpServletRequest request = getRequest();
    for (Enumeration e = request.getAttributeNames(); e.hasMoreElements(); ) {
      String key = (String) e.nextElement();
      String s = String.format("%s=%s", key, request.getAttribute(key));
      logger.debug(s);
    }
  }
Ejemplo n.º 15
0
  @Override
  public void contextInitialized(ServletContextEvent servletContextEvent) {
    ServletContext servletContext = servletContextEvent.getServletContext();
    File homeDir = null;
    if (servletContext.getAttribute("homedir") != null) {
      homeDir = new File((String) servletContext.getAttribute("homedir"));
    }
    if (homeDir == null && servletContext.getInitParameter("homedir") != null) {
      homeDir = new File(servletContext.getInitParameter("homedir"));
    }

    boolean autoMigrate = false;
    if (servletContext.getAttribute("autoMigrate") != null) {
      autoMigrate = (boolean) servletContext.getAttribute("autoMigrate");
    }
    if (autoMigrate == false && servletContext.getInitParameter("autoMigrate") != null) {
      autoMigrate = Boolean.valueOf(servletContext.getInitParameter("autoMigrate"));
    }

    String realPath = servletContext.getRealPath("/");
    if (!realPath.endsWith("/")) {
      realPath = realPath + "/";
    }
    File baseDir = new File(realPath + "www/WEB-INF");
    if (homeDir == null) {
      homeDir = baseDir;
    }
    ResourceFetcher resourceFetcher = new WarResourceFetcher(servletContext, homeDir);
    BimServerConfig config = new BimServerConfig();
    config.setAutoMigrate(autoMigrate);
    config.setHomeDir(homeDir);
    config.setResourceFetcher(resourceFetcher);
    config.setClassPath(makeClassPath(resourceFetcher.getFile("lib")));
    config.setStartEmbeddedWebServer(false);
    bimServer = new BimServer(config);

    Logger LOGGER = LoggerFactory.getLogger(WarServerInitializer.class);
    LOGGER.info("Servlet Context Name: " + servletContext.getServletContextName());

    File file = resourceFetcher.getFile("plugins");
    try {
      bimServer.getPluginManager().loadAllPluginsFromDirectoryOfJars(file);
      bimServer.start();
    } catch (ServerException e) {
      LOGGER.error("", e);
    } catch (DatabaseInitException e) {
      LOGGER.error("", e);
    } catch (BimserverDatabaseException e) {
      LOGGER.error("", e);
    } catch (PluginException e) {
      LOGGER.error("", e);
    } catch (DatabaseRestartRequiredException e) {
      LOGGER.error("", e);
    }
    servletContext.setAttribute("bimserver", bimServer);
  }
Ejemplo n.º 16
0
  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; charset=UTF-8");
      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;
      _jspx_resourceInjector =
          (org.apache.jasper.runtime.ResourceInjector)
              application.getAttribute("com.sun.appserv.jsp.resource.injector");

      out.write('\n');
      out.write('\n');
      out.write("\n<!DOCTYPE html>\n<html>\n<head>\n");
      JspHelper.createTitle(out, request, request.getParameter("filename"));
      out.write("\n</head>\n<body onload=\"document.goto.dir.focus()\">\n");

      Configuration conf = (Configuration) getServletContext().getAttribute(JspHelper.CURRENT_CONF);
      generateFileChunks(out, request, conf);

      out.write("\n<hr>\n");

      generateFileDetails(out, request, conf);

      out.write("\n\n<h2>Local logs</h2>\n<a href=\"/logs/\">Log</a> directory\n\n");

      out.println(ServletUtil.htmlFooter());

      out.write('\n');
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)) {
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0) out.clearBuffer();
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
  public void contextInitialized(final ServletContextEvent sce) {
    final ServletContext context = sce.getServletContext();

    // create a container if there is none yet
    if (context.getAttribute(PlexusConstants.PLEXUS_KEY) == null) {
      try {
        appContext =
            createContainerContext(
                context, (AppContext) context.getAttribute(AppContext.APPCONTEXT_KEY));

        final ContainerConfiguration plexusConfiguration =
            new DefaultContainerConfiguration()
                .setName(context.getServletContextName())
                .setContainerConfigurationURL(plexusXmlFile.toURI().toURL())
                .setContext((Map) appContext.flatten())
                .setAutoWiring(true)
                .setClassPathScanning(PlexusConstants.SCANNING_INDEX)
                .setComponentVisibility(PlexusConstants.GLOBAL_VISIBILITY);

        final ArrayList<Module> modules = new ArrayList<Module>(2);
        modules.add(new NexusWebModule(sce.getServletContext()));
        modules.add(new AppContextModule(appContext));

        // Add support for @Timed
        modules.add(new TimingModule());

        final Module[] customModules = (Module[]) context.getAttribute(CUSTOM_MODULES);

        if (customModules != null) {
          modules.addAll(Arrays.asList(customModules));
        }

        plexusContainer =
            new DefaultPlexusContainer(
                plexusConfiguration, modules.toArray(new Module[modules.size()]));

        context.setAttribute(PlexusConstants.PLEXUS_KEY, plexusContainer);

        context.setAttribute(AppContext.APPCONTEXT_KEY, appContext);
      } catch (PlexusContainerException e) {
        sce.getServletContext().log("Could not start Plexus container!", e);

        throw new IllegalStateException("Could not start Plexus container!", e);
      } catch (IOException e) {
        sce.getServletContext().log("Could not start Plexus container!", e);

        throw new IllegalStateException("Could not start Plexus container!", e);
      }

      // fire startable
      appContext.getLifecycleManager().invokeHandler(Startable.class);
    }
  }
Ejemplo n.º 18
0
 /** Create a {@link NameNode} proxy from the current {@link ServletContext}. */
 protected ClientProtocol createNameNodeProxy() throws IOException {
   ServletContext context = getServletContext();
   // if we are running in the Name Node, use it directly rather than via rpc
   NameNode nn = (NameNode) context.getAttribute("name.node");
   if (nn != null) {
     return nn;
   }
   InetSocketAddress nnAddr = (InetSocketAddress) context.getAttribute("name.node.address");
   Configuration conf =
       new Configuration((Configuration) context.getAttribute(JspHelper.CURRENT_CONF));
   return DFSClient.createNamenode(nnAddr, conf);
 }
  @Override
  public String execute() throws Exception {
    ServletContext scx = ServletActionContext.getServletContext();
    UserTransaction utx = (UserTransaction) scx.getAttribute("utx");
    EntityManagerFactory emf = (EntityManagerFactory) scx.getAttribute("emf");
    EntityManager em = emf.createEntityManager();
    utx.begin();
    em.merge(supplier);
    utx.commit();

    return SUCCESS;
  }
Ejemplo n.º 20
0
 public boolean stopRun(String runid, ServletContext context) {
   ExecutionMonitorAPI monitor = config.getDomainExecutionMonitor();
   if (monitor.getRunDetails(runid).getRuntimeInfo().getStatus() == RuntimeInfo.Status.RUNNING) {
     PlanExecutionEngine engine = (PlanExecutionEngine) context.getAttribute("engine_" + runid);
     RuntimePlan rplan = (RuntimePlan) context.getAttribute("plan_" + runid);
     if (engine != null && rplan != null) {
       engine.abort(rplan);
       return true;
     }
   }
   return false;
 }
Ejemplo n.º 21
0
  protected void checkTilesDefinitionsFactory() {
    ServletContext servletContext = getServletContext();

    if (servletContext.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY) != null) {

      return;
    }

    servletContext.setAttribute(
        TilesUtilImpl.DEFINITIONS_FACTORY,
        servletContext.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY));
  }
Ejemplo n.º 22
0
  @Override
  public void init() throws ServletException {
    ServletContext sctx = getServletContext();

    ServletException e = (ServletException) sctx.getAttribute("exception");
    if (null != e) {
      throw e;
    }

    this.jds_pool = ((JedisPool) sctx.getAttribute("jds_connection_pool"));

    return;
  }
Ejemplo n.º 23
0
 /** Obtains the {@link WebApp} associated with the given {@link ServletContext}. */
 public static WebApp get(ServletContext context) {
   Object o = context.getAttribute(WebApp.class.getName());
   if (o == null) {
     synchronized (WebApp.class) {
       o = context.getAttribute(WebApp.class.getName());
       if (o == null) {
         o = new WebApp(context);
         context.setAttribute(WebApp.class.getName(), o);
       }
     }
   }
   return (WebApp) o;
 }
Ejemplo n.º 24
0
  void setAttributeVariables(Calendar calendar) {

    SimpleDateFormat monthNameFormat = new SimpleDateFormat("MMMM", new Locale("es", "ES"));
    SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
    SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
    SimpleDateFormat yearMontFormat = new SimpleDateFormat("yyyy-MM");
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-d");

    context.setAttribute("userFullName", user.getUserFullName());
    context.setAttribute(
        "selectedMonthName", WordUtils.capitalize(monthNameFormat.format(calendar.getTime())));
    context.setAttribute("selectedYear", yearFormat.format(calendar.getTime()));
    context.setAttribute("selectedMonth", monthFormat.format(calendar.getTime()));

    Map<String, String> monthsList = new LinkedHashMap<String, String>();

    for (int i = 0; i < 4; i++) {
      monthsList.put(
          yearMontFormat.format(calendar.getTime()),
          WordUtils.capitalize(monthNameFormat.format(calendar.getTime())));
      calendar.add(Calendar.MONTH, 1);
    }

    context.setAttribute("monthsList", monthsList);

    calendar.add(Calendar.MONTH, -4);
    calendar.set(Calendar.DATE, 1);
    Timestamp fromDate = new Timestamp(calendar.getTime().getTime());
    calendar.add(Calendar.MONTH, 1);
    Timestamp toDate = new Timestamp(calendar.getTime().getTime());

    eqRestrictions.clear();
    eqRestrictions.put("startDate", new FieldCondition(fromDate, 1));
    eqRestrictions.put("endDate", new FieldCondition(toDate, -1));
    eqRestrictions.put("user", new FieldCondition(user));

    List<?> availableDates = new LinkedList<String>();
    availableDates =
        service.GetModelDataList(RefereeAvailability.class, eqRestrictions, "startDate", true);
    context.setAttribute("availableDates", availableDates);

    List<String> availableStartDates = new LinkedList<String>();
    availableDates.forEach(
        ad ->
            availableStartDates.add(dateFormat.format(((RefereeAvailability) ad).getStartDate())));
    context.setAttribute("availableStartDates", availableStartDates);

    context.setAttribute(
        "dateStr",
        context.getAttribute("selectedYear") + "-" + context.getAttribute("selectedMonth"));
  }
Ejemplo n.º 25
0
  @GET
  @Path("/{studyOID}/getSchedule")
  @Produces(MediaType.APPLICATION_XML)
  public String getSchedule(
      @Context HttpServletRequest request,
      @Context HttpServletResponse response,
      @Context ServletContext context,
      @PathParam("studyOID") String studyOID,
      @RequestHeader("Authorization") String authorization)
      throws Exception {

    String ssoid = request.getParameter("studySubjectOID");
    StudySubjectDAO ssdao = new StudySubjectDAO<String, ArrayList>(dataSource);
    StudySubjectBean ssBean = ssdao.findByOid(ssoid);
    if (!mayProceedSubmission(studyOID, ssBean)) return null;

    HashMap<String, String> urlCache =
        (HashMap<String, String>) context.getAttribute("pformURLCache");
    context.getAttribute("subjectContextCache");
    if (ssoid == null) {
      return "<error>studySubjectOID is null :(</error>";
    }

    try {
      // Need to retrieve crf's for next event
      StudyEventDAO eventDAO = new StudyEventDAO(getDataSource());
      StudyEventBean nextEvent = (StudyEventBean) eventDAO.getNextScheduledEvent(ssoid);
      CRFVersionDAO versionDAO = new CRFVersionDAO(getDataSource());
      ArrayList<CRFVersionBean> crfs =
          versionDAO.findDefCRFVersionsByStudyEvent(nextEvent.getStudyEventDefinitionId());
      PFormCache cache = PFormCache.getInstance(context);
      for (CRFVersionBean crfVersion : crfs) {
        String enketoURL = cache.getPFormURL(studyOID, crfVersion.getOid());
        String contextHash =
            cache.putSubjectContext(
                ssoid,
                String.valueOf(nextEvent.getStudyEventDefinitionId()),
                String.valueOf(nextEvent.getSampleOrdinal()),
                crfVersion.getOid());
      }
    } catch (Exception e) {
      LOGGER.debug(e.getMessage());
      LOGGER.debug(ExceptionUtils.getStackTrace(e));
      return "<error>" + e.getMessage() + "</error>";
    }

    response.setHeader("Content-Type", "text/xml; charset=UTF-8");
    response.setHeader("Content-Disposition", "attachment; filename=\"schedule.xml\";");
    response.setContentType("text/xml; charset=utf-8");
    return "<result>success</result>";
  }
Ejemplo n.º 26
0
	public void loginRoom(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		HttpSession session = request.getSession();
		String username=request.getParameter("username");	//获得登录用户名
		UserInfo user=UserInfo.getInstance();		//获得UserInfo类的对象
		session.setMaxInactiveInterval(600);		//设置Session的过期时间为10分钟
		Vector vector=user.getList();
		boolean flag=true;		//标记是否登录的变量
		//判断用户是否登录
		System.out.println("vector的size:"+vector.size());
		if(vector!=null&&vector.size()>0){
			for(int i=0;i<vector.size();i++){
				System.out.println("vector"+i+":"+vector.elementAt(i)+" user:"******"<script language='javascript'>alert('该用户已经登录');window.location.href='index.jsp';</script>");
					} catch (IOException e) {
						e.printStackTrace();
					}
					flag=false;
					break;
				}
			}
		}
		//保存用户信息
		if(flag){
			UserListener ul=new UserListener();					//创建UserListener的对象
			ul.setUser(username);								//添加用户
			user.addUser(ul.getUser());							//添加用户到UserInfo类的对象中
			session.setAttribute("user",ul);						//将UserListener对象绑定到Session中
			session.setAttribute("username",username);	//保存当前登录的用户名
			session.setAttribute("loginTime",new Date().toLocaleString());		//保存登录时间
        ServletContext application=getServletContext();

        String sourceMessage="";

        if(null!=application.getAttribute("message")){
            sourceMessage=application.getAttribute("message").toString();
        }
        sourceMessage+="系统公告:<font color='gray'>" + username + "走进了聊天室!</font><br>";
        application.setAttribute("message",sourceMessage);
        try {
            request.getRequestDispatcher("login_ok.jsp").forward(request, response);
        } catch (Exception ex) {
            Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, ex);
        }
		}
	}
Ejemplo n.º 27
0
  public GenericWebAppContext(
      ServletContext servletContext,
      HttpServletRequest request,
      HttpServletResponse response,
      SessionProvider sessionProvider,
      ManageableRepository repository) {

    initialize(servletContext, request, response);

    this.sessionProvider = sessionProvider;
    this.repository = repository;

    // log.info("WEb context ---------------");
    // initialize context with all props
    Enumeration en = servletContext.getInitParameterNames();
    while (en.hasMoreElements()) {
      String name = (String) en.nextElement();
      put(name, servletContext.getInitParameter(name));
      LOG.debug("ServletContext init param: " + name + "=" + servletContext.getInitParameter(name));
    }

    en = servletContext.getAttributeNames();
    while (en.hasMoreElements()) {
      String name = (String) en.nextElement();
      put(name, servletContext.getAttribute(name));
      LOG.debug("ServletContext: " + name + "=" + servletContext.getAttribute(name));
    }

    HttpSession session = request.getSession(false);
    if (session != null) {
      en = session.getAttributeNames();
      while (en.hasMoreElements()) {
        String name = (String) en.nextElement();
        put(name, session.getAttribute(name));
        LOG.debug("Session: " + name + "=" + session.getAttribute(name));
      }
    }

    en = request.getAttributeNames();
    while (en.hasMoreElements()) {
      String name = (String) en.nextElement();
      put(name, request.getAttribute(name));
    }

    en = request.getParameterNames();
    while (en.hasMoreElements()) {
      String name = (String) en.nextElement();
      put(name, request.getParameter(name));
      LOG.debug("Request: " + name + "=" + request.getParameter(name));
    }
  }
Ejemplo n.º 28
0
  @Override
  public void init() throws ServletException {
    logger.info("ExamServlet initiation started");

    ServletContext servletContext = getServletContext();
    examService = (ExamService) servletContext.getAttribute("examService");
    subjectService = (SubjectService) servletContext.getAttribute("subjectService");
    examSubmissionMapper =
        (ExamSubmissionMapper) servletContext.getAttribute("examSubmissionMapper");
    examCreationMapper = (ExamCreationMapper) servletContext.getAttribute("examCreationMapper");
    examChecker = (ExamChecker) servletContext.getAttribute("examChecker");

    logger.info("ExamServlet initiation finished");
  }
  /**
   * @param sctx {@link ServletContext}
   * @return actual ExoContainer instance
   */
  protected KernelContainer getContainer(ServletContext sctx) {
    KernelContainer container = KernelContainerContext.getCurrentContainer();
    if (container instanceof RootContainer) {
      String containerName = null;
      // check attribute in servlet context first
      if (sctx.getAttribute(SetCurrentIdentityFilter.PORTAL_CONTAINER_NAME) != null)
        containerName = (String) sctx.getAttribute(SetCurrentIdentityFilter.PORTAL_CONTAINER_NAME);

      // if not set then use default name.
      if (containerName == null) containerName = "portal";
      container = RootContainer.getInstance().getPortalContainer(containerName);
    }
    return container;
  }
Ejemplo n.º 30
0
  public String rewriteHref(ServletContext context, HttpServletRequest request, String href)
      throws ISPACException {

    String contextPath = request.getContextPath();
    String ispacbase = (String) context.getAttribute("ispacbase");

    String skin = (String) request.getSession().getAttribute("skin");
    if (StringUtils.isEmpty(skin)) {
      skin = (String) context.getAttribute("skin");
    }

    return StaticContext.rewriteHref(
        StaticContext.getInstance().getBaseUrl(contextPath), ispacbase, skin, href);
  }