Exemple #1
0
  // ----------- CONSTRUCTEUR ------------
  public Mod_autoRnDipl(WOContext context) {
    super(context);

    autorisationGestionSortieRN = ((Session) session()).monApp.autorisationSortirRN();

    if (autorisationGestionSortieRN) monAutornDiplCtrlr = new RNDiplCtrlr((Session) session());
    //  	System.out.println("ZZZZZZZZZZZZZZZZZZZZZZZZZ  init mod datesIpDipl");

    // s'enregistrer pour les notifs (chgt d'année en cours)
    NSNotificationCenter.defaultCenter()
        .addObserver(
            this, // on doit me prévenir moi-même !
            new NSSelector(
                "chgtAnnee", // via cette méthode
                new Class[] {NSNotification.class}), // argument obligatoire !!!
            "chgtAnneeEnCours", // la signature de la notif qui me plait
            (Session) this.session()); // instance de celui qui la poste !

    // chgt dans la liste des dipl. autorisant les RN :
    NSNotificationCenter.defaultCenter()
        .addObserver(
            this, // on doit me prévenir moi-même !
            new NSSelector(
                "chgtListeDiplAutoRN", // via cette méthode
                new Class[] {NSNotification.class}), // argument obligatoire !!!
            "chgtDiplAutoRN", // la signature de la notif qui me plait
            (Session) this.session()); // instance de celui qui la poste !
  }
  public CoreSession() {
    super();
    logger.trace("-----+ constructor");

    NSNotificationCenter.defaultCenter()
        .addObserver(
            this,
            new NSSelector<Object>("sessionWillAwake", new Class[] {NSNotification.class}),
            ERXSession.SessionWillAwakeNotification,
            null);

    NSNotificationCenter.defaultCenter()
        .addObserver(
            this,
            new NSSelector<Object>("sessionDidCreate", new Class[] {NSNotification.class}),
            WOSession.SessionDidCreateNotification,
            null);

    NSNotificationCenter.defaultCenter()
        .addObserver(
            this,
            new NSSelector<Object>("sessionDidTimeOut", new Class[] {NSNotification.class}),
            WOSession.SessionDidTimeOutNotification,
            null);

    CoreSession.properties = new CoreProperties(System.getProperties());
  }
  private static void StaticInitializer() {
    LOG.info("[-STATIC-] APPLICATION");

    ERXProperties.setOperatorForKey(
        new StartsWithOperator(ERXProperties.stringForKey("os.arch")),
        "arch"); // 'x86', 'x86_64', ...
    ERXProperties.setOperatorForKey(
        new StartsWithOperator(ERXProperties.stringForKey("os.name")),
        "osname"); // 'Windows XP', 'Mac OS X', ...
    ERXProperties.setOperatorForKey(
        new StartsWithOperator(ERXProperties.stringForKey("os.version")),
        "osvers"); // '5.1', '10.8.2', ...

    ERXProperties.setOperatorForKey(
        new StartsWithOperator(ERXProperties.stringForKey("user.name")), "user");
    ERXProperties.setOperatorForKey(
        new StartsWithOperator(
            ERXProperties.stringForKey("catalina.home") == null ? "apache" : "tomcat"),
        "envo");

    // ------------------------------------------------------------------------------------------------
    LOG.info("[-STATIC-] APPLICATION - SET UP NOTIFICATION OBSERVERS");
    Observer observer = new Observer();
    _retainer = new NSArray<Observer>(observer);

    NSNotificationCenter.defaultCenter()
        .addObserver(
            observer,
            new NSSelector<Object>("appWillLaunch", new Class[] {NSNotification.class}),
            com.webobjects.appserver.WOApplication.ApplicationWillFinishLaunchingNotification,
            null);

    NSNotificationCenter.defaultCenter()
        .addObserver(
            observer,
            new NSSelector<Object>("appDidLaunch", new Class[] {NSNotification.class}),
            com.webobjects.appserver.WOApplication.ApplicationDidFinishLaunchingNotification,
            null);

    NSNotificationCenter.defaultCenter()
        .addOmniscientObserver(
            observer,
            new NSSelector<Object>("allNotifications", new Class[] {NSNotification.class}));

    // ------------------------------------------------------------------------------------------------
    LOG.info("[-STATIC-] APPLICATION - CLASSPATH CHECK");
    NSArray<String> classPathComponents =
        NSArray.componentsSeparatedByString(
            ERXProperties.stringForKey("java.class.path"),
            ERXProperties.stringForKey("path.separator"));
    for (String classPathComponent : classPathComponents) { // enumerate the class path ...
      try { // ... can each library be found
        if ((new File(classPathComponent)).isFile())
          LOG.trace("classpath [jar] {}", classPathComponent);
        else LOG.trace("classpath [bin] {}", classPathComponent);
      } catch (Exception x) {
        LOG.error("{} Exception validating classpath", classPathComponent, x);
      }
    }
  }
  public void appendToResponse(WOResponse response, WOContext context) {
    // set the numberOfObjectsPerBatch
    Number newNumberOfObjectsPerBatch = (Number) ERXThreadStorage.valueForKey(_threadStorageKey);
    if (newNumberOfObjectsPerBatch != null
        && newNumberOfObjectsPerBatch.intValue() != displayGroup().numberOfObjectsPerBatch()) {
      if (displayGroup() != null) {
        NSArray selection = selection();

        if (log.isDebugEnabled())
          log.debug("Setting db # of objects per batch to " + newNumberOfObjectsPerBatch);
        displayGroup().setNumberOfObjectsPerBatch(newNumberOfObjectsPerBatch.intValue());

        if (log.isDebugEnabled()) log.debug("The batch index is being set to : " + 1);
        displayGroup().setCurrentBatchIndex(1);
        clearSelection(selection);
      }
      Object d2wcontext = valueForBinding("d2wContext");
      if (d2wcontext != null) {
        NSNotificationCenter.defaultCenter()
            .postNotification(
                "BatchSizeChanged",
                ERXConstant.integerForInt(newNumberOfObjectsPerBatch.intValue()),
                new NSDictionary(d2wcontext, "d2wContext"));
      }
      ERXThreadStorage.takeValueForKey(null, _threadStorageKey);
    }

    if (displayGroup() != null && !displayGroup().hasMultipleBatches()) {
      if (currentBatchIndex() != 0) setCurrentBatchIndex(ERXConstant.ZeroInteger);
    }
    super.appendToResponse(response, context);
  }
    /*------------------------------------------------------------------------------------------------*
     *  A P P L I C A T I O N   W I L L   L A U N C H                     [ N O T I F I C A T I O N ]
     *------------------------------------------------------------------------------------------------*/
    public void appWillLaunch(NSNotification notification) {
      LOG.info("[-NOTIFY-] appWillLaunch");

      NSNotificationCenter.defaultCenter()
          .removeObserver(
              this,
              com.webobjects.appserver.WOApplication.ApplicationWillFinishLaunchingNotification,
              null);

      NSArray<EOModel> modelArray = ERXModelGroup.defaultGroup().models();
      for (EOModel model : modelArray) {
        LOG.info("[OBSERVER] modelName={} ({})", model.name(), model.adaptorName());
      }

      if (ERXProperties.booleanForKey("pachy.exitBeforeLaunching")) {
        LOG.info("[APPLICATION] EXIT BEFORE LAUNCHING [pachy.exitBeforeLaunching == true]");
        System.exit(0);
        /* ######################################### MIGHT STOP HERE (pachy.exitBeforeLaunching) #### */
      }

      if (ERXProperties.booleanForKeyWithDefault("pachy.optionEnableTimers", false)) {
        startTenMinuteTimerTask();
        startDayChangeTimerTask();
      }
    }
    /*------------------------------------------------------------------------------------------------*
     *  A P P L I C A T I O N   D I D   L A U N C H                       [ N O T I F I C A T I O N ]
     *------------------------------------------------------------------------------------------------*/
    public void appDidLaunch(NSNotification notification) {
      LOG.info("[-NOTIFY-] appDidLaunch");

      NSNotificationCenter.defaultCenter()
          .removeObserver(
              this,
              com.webobjects.appserver.WOApplication.ApplicationWillFinishLaunchingNotification,
              null);
    }
Exemple #7
0
  /**
   * Sets up the logging system with the given configuration in {@link java.util.Properties} format.
   *
   * @param properties with the logging configuration
   */
  public static synchronized void configureLogging(Properties properties) {
    LogManager.resetConfiguration();
    BasicConfigurator.configure();
    // AK: we re-configure the logging a few lines later from the
    // properties, but in case
    // no config is set, we set the root level to info, install the brigde
    // which sets it's own logging level to DEBUG
    // and the output should be pretty much the same as with plain WO
    Logger.getRootLogger().setLevel(Level.INFO);
    boolean is522OrHigher = ERXProperties.webObjectsVersionIs522OrHigher();
    if (is522OrHigher) {
      int allowedLevel = NSLog.debug.allowedDebugLevel();
      if (!(NSLog.debug instanceof ERXNSLogLog4jBridge)) {
        NSLog.setOut(new ERXNSLogLog4jBridge(ERXNSLogLog4jBridge.OUT));
        NSLog.setErr(new ERXNSLogLog4jBridge(ERXNSLogLog4jBridge.ERR));
        NSLog.setDebug(new ERXNSLogLog4jBridge(ERXNSLogLog4jBridge.DEBUG));
      }
      NSLog.debug.setAllowedDebugLevel(allowedLevel);
    }
    PropertyConfigurator.configure(properties);
    // AK: if the root logger has no appenders, something is really broken
    // most likely the properties didn't read correctly.
    if (!Logger.getRootLogger().getAllAppenders().hasMoreElements()) {
      Appender appender =
          new ConsoleAppender(
              new ERXPatternLayout("%-5p %d{HH:mm:ss} (%-20c:%L):  %m%n"), "System.out");
      Logger.getRootLogger().addAppender(appender);
      Logger.getRootLogger().setLevel(Level.DEBUG);
      Logger.getRootLogger()
          .error("Logging prefs couldn't get read from properties, using defaults");
    }
    if (ERXLogger.log == null) {
      ERXLogger.log = Logger.getLogger(Logger.class.getName());
    }
    ERXLogger.log.info("Updated the logging configuration with the current system properties.");
    if (ERXLogger.log.isDebugEnabled()) {
      ERXLogger.log.debug("log4j.loggerFactory: " + System.getProperty("log4j.loggerFactory"));
      ERXLogger.log.debug("Factory: " + ERXLogger.factory);
      // MS: This just trips everyone up, and it really seems to only be
      // used by PW developers, so I say we just turn it on when we need it.
      // log.debug("", new RuntimeException(
      // "This is not a real exception. It is just to show you where logging was initialized."
      // ));
    }
    // PropertyPrinter printer = new PropertyPrinter(new
    // PrintWriter(System.out));
    // printer.print(new PrintWriter(System.out));
    if (ERXLogger.factory != null) {
      ERXLogger.factory.loggingConfigurationDidChange();
    }

    NSNotificationCenter.defaultCenter()
        .postNotification(ERXConfigurationManager.ConfigurationDidChangeNotification, null);
  }
  // @Override
  public WOResponse handleRequest(WORequest request) {
    if (!ERSelenium.testsEnabled()) {
      return new WOResponse();
    }

    NSArray pathElements = request.requestHandlerPathArray();

    StringBuilder builder = new StringBuilder();
    Iterator iter = pathElements.iterator();
    while (iter.hasNext()) {
      builder.append(iter.next());
      if (iter.hasNext()) builder.append("/");
    }

    String filePath = builder.toString();
    log.debug("Processing file '" + filePath + "'");

    /*
     * Syncrhonization mistakes are possible here, but not fatal at all.
     * At the worst case the file will be read 2-or-more times instead of 1 (if process 1
     * checks that the file is not cached and process 2 does the same check before
     * process 1 has updated the cache).
     */

    CachedFile cachedFile;
    synchronized (_cache) {
      cachedFile = (CachedFile) _cache.objectForKey(filePath);
    }

    if (cachedFile == null) {
      cachedFile = new CachedFile();

      URL fileUrl =
          WOApplication.application()
              .resourceManager()
              .pathURLForResourceNamed(filePath, "ERSelenium", null);
      if (fileUrl == null) {
        throw new RuntimeException("Can't find specified resource ('" + filePath + "')");
      }
      cachedFile.mimeType =
          WOApplication.application().resourceManager().contentTypeForResourceNamed(filePath);
      if (cachedFile.mimeType == null) {
        throw new RuntimeException("Can't determine resource mime type ('" + filePath + "')");
      }

      try {
        cachedFile.data = new NSData(ERXFileUtilities.bytesFromInputStream(fileUrl.openStream()));
      } catch (Exception e) {
        throw new RuntimeException("Error reading file '" + fileUrl.getPath() + "'", e);
      }

      synchronized (_cache) {
        _cache.setObjectForKey(cachedFile, filePath);
      }
    }

    WOResponse response = new WOResponse();
    response.setHeader(cachedFile.mimeType, "content-type");
    response.setContent(cachedFile.data);

    NSNotificationCenter.defaultCenter()
        .postNotification(WORequestHandler.DidHandleRequestNotification, response);
    return response;
  }
  public WOResponse handleRequest(WORequest request) {
    WOResponse response = null;
    FileInputStream is = null;
    long length = 0;
    String contentType = null;
    String uri = request.uri();
    if (uri.charAt(0) == '/') {
      WOResourceManager rm = application.resourceManager();
      String documentRoot = documentRoot();
      File file = null;
      StringBuffer sb = new StringBuffer(documentRoot.length() + uri.length());
      String wodataKey = request.stringFormValueForKey("wodata");
      if (uri.startsWith("/cgi-bin") && wodataKey != null) {
        uri = wodataKey;
        if (uri.startsWith("file:")) {
          // remove file:/
          uri = uri.substring(5);
        } else {

        }
      } else {
        int index = uri.indexOf("/wodata=");

        if (index >= 0) {
          uri = uri.substring(index + "/wodata=".length());
        } else {
          sb.append(documentRoot);
        }
      }

      if (_useRequestHandlerPath) {
        try {
          WODynamicURL dynamicURL = new WODynamicURL(uri);
          String requestHandlerPath = dynamicURL.requestHandlerPath();
          if (requestHandlerPath == null || requestHandlerPath.length() == 0) {
            sb.append(uri);
          } else {
            sb.append("/");
            sb.append(requestHandlerPath);
          }
        } catch (Exception e) {
          throw new RuntimeException("Failed to parse URL '" + uri + "'.", e);
        }
      } else {
        sb.append(uri);
      }

      String path = sb.toString();
      try {
        path = path.replaceAll("\\?.*", "");
        if (request.userInfo() != null && !request.userInfo().containsKey("HttpServletRequest")) {
          /* PATH_INFO is already decoded by the servlet container */
          path = path.replace('+', ' ');
          path = URLDecoder.decode(path, CharEncoding.UTF_8);
        }
        file = new File(path);
        length = file.length();
        is = new FileInputStream(file);

        contentType = rm.contentTypeForResourceNamed(path);
        log.debug("Reading file '" + file + "' for uri: " + uri);
      } catch (IOException ex) {
        if (!uri.toLowerCase().endsWith("/favicon.ico")) {
          log.info("Unable to get contents of file '" + file + "' for uri: " + uri);
        }
      }
    } else {
      log.error("Can't fetch relative path: " + uri);
    }
    response = _generateResponseForInputStream(is, length, contentType);
    NSNotificationCenter.defaultCenter()
        .postNotification(WORequestHandler.DidHandleRequestNotification, response);
    response._finalizeInContext(null);
    return response;
  }