Пример #1
0
    /*------------------------------------------------------------------------------------------------*
     *  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();
      }
    }
Пример #2
0
 /**
  * <span class="en"> Returns the SMTP protocol to use for connections. </span>
  *
  * <p><span class="ja"> 接続の為の SMTP プロトコールを設定します。 (smtp or smtps)
  *
  * @param contextString - SMTP プロトコール名 </span>
  */
 public String smtpProtocolForContext(String contextString) {
   String contextSuffix = (contextString == null) ? "" : ("." + contextString);
   return ERXProperties.stringForKeyWithDefault(
       "er.javamail.smtpProtocol" + contextSuffix,
       ERXProperties.stringForKeyWithDefault(
           "er.javamail.smtpProtocol",
           ERXProperties.stringForKeyWithDefault("mail.smtp.protocol", "smtp")));
 }
Пример #3
0
  public Application() {
    super();

    PachySanity.adjustEnvironment();

    if (isFirstTime()) {

      PachySanity.showEnvironment();

    } else {

      if (ERXProperties.booleanForKeyWithDefault("pachy.CreateEnvironment", false)) {
        PachySanity.createEnvironment();
      }

      if (ERXProperties.booleanForKeyWithDefault("pachy.ShowEnvironment", true)) {
        PachySanity.showEnvironment();
      }

      PachySanity.testEnvironment();

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

    er.extensions.ERXExtensions.setAdaptorLogging(
        ERXProperties.booleanForKeyWithDefault("pachy.optionEnableAdaptorLog", false));

    /*------------------------------------------------------------------------------------------------*
     *  ... add the metadata database to the objectStores (why does EOModel not do this?)
     *------------------------------------------------------------------------------------------------*/
    try {
      CXObjectStoreCoordinator.getDefaultCoordinator()
          .addObjectStore(
              "org.pachyderm.assetdb", ERXProperties.stringForKey("dbConnectURLGLOBAL"));
      LOG.info("org.pachyderm.assetdb registered.");
    } catch (Exception x) {
      LOG.error("org.pachyderm.assetdb not registered.", x);
    }

    /*------------------------------------------------------------------------------------------------*
     *  add the English and French locales to the locale array ...
     *------------------------------------------------------------------------------------------------*/
    locales = new NSMutableArray<Locale>();
    locales.addObject(Locale.ENGLISH);
    locales.addObject(Locale.FRENCH);

    /*------------------------------------------------------------------------------------------------*
     *  loading this class, causes "UTRuntimeProvider" to scan for UTI definitions which can take
     *  a long time (~10 seconds on a good day).  Rather than have the first unfortunate user incur
     *  that penalty unpredictably, we get it over with now, before anyone logs in ...
     *------------------------------------------------------------------------------------------------*/
    UTType.loadThisClassNow();
  }
Пример #4
0
  public String javascriptUrl() {
    String uri;

    if (ERXProperties.booleanForKeyWithDefault("er.jquerymobile.javascript.use.odn", true)) {
      uri = ERXProperties.stringForKey("er.jquerymobile.javascript.odn.location");
    } else {
      uri = ERXProperties.stringForKey("er.jquerymobile.javascript.local.location");
    }
    return ERXHyperlinkResource.urlForHyperlinkResource(context(), uri);
  }
Пример #5
0
 /** Constructs a new ERXRouteRequestHandler with the default entity name format. */
 public ERXRouteRequestHandler() {
   this(
       new NameFormat(
           ERXProperties.booleanForKeyWithDefault("ERXRest.pluralEntityNames", true),
           ERXProperties.booleanForKeyWithDefault("ERXRest.pluralEntityNames", true),
           NameFormat.Case.valueOf(
               ERXProperties.stringForKeyWithDefault(
                   "ERXRest.routeCase",
                   ERXProperties.booleanForKeyWithDefault("ERXRest.lowercaseEntityNames", true)
                       ? NameFormat.Case.LowerCamelCase.name()
                       : NameFormat.Case.CamelCase.name()))));
 }
Пример #6
0
  /**
   * <div class="ja"> マシンで設定されているIPリストを取得します。 環境設定については: A10Properties. InIpRangeOperatorを参照
   *
   * @return IP 配列が戻ります </div>
   */
  public static NSArray<String> machineIpList() {

    // この関数は WOApplication がインスタンス化される前に実行されるので、ログ出力は標準ではない
    if (ERXArrayUtilities.arrayIsNullOrEmpty(_machineIpList)) {
      // プロパティー内でどの IP を使用するかどうかを読込みます。
      String machineIp =
          ERXProperties.stringFor2Keys(
              "er.erxtensions.ERXTcpIp.UseThisIp", "wodka.a10.A10TcpIp.UseThisIp");

      try {
        // プロパティーがなければ、自動設定を行う
        if (ERXStringUtilities.stringIsNullOrEmpty(machineIp)) {
          log.debug("MachineIp Automatic Mode");

          // マシンIPを得る
          if (ERXArrayUtilities.arrayIsNullOrEmpty(_machineIpList))
            _machineIpList = _machineIpList();

          // 処理不能 ??
          if (ERXArrayUtilities.arrayIsNullOrEmpty(_machineIpList)) {
            String noIpAndNoNetwork =
                ERXProperties.stringFor2Keys(
                    "er.erxtensions.ERXTcpIp.NoIpAndNoNetwork",
                    "wodka.a10.A10TcpIp.NoIpAndNoNetwork");

            // No IP と No ネットワークも設定されていなければ、ローカル IP を使用する
            if (ERXStringUtilities.stringIsNullOrEmpty(noIpAndNoNetwork))
              noIpAndNoNetwork = LOCAL_IP_ADDRESS;

            // 使用する IP をセットします
            _machineIpList = new NSArray<String>(new String[] {noIpAndNoNetwork});

            log.warn("No IpAddress --- no network! use Address : {}", noIpAndNoNetwork);
          }
        } else {
          // 使用する IP をセットします
          _machineIpList = new NSArray<String>(new String[] {machineIp});
        }
      } catch (Exception e) {
        // ここでの処理失敗は致命的
        log.error("getIpAddress error!!!");

        _machineIpList = new NSArray<String>(new String[] {LOCAL_IP_ADDRESS});
      }

      if (log.isInfoEnabled())
        log.info("MachineIp {} is in use.", ERXArrayUtilities.arrayToLogstring(_machineIpList));
    }

    return _machineIpList;
  }
Пример #7
0
 public StopWatchTimer() {
   Thread timerThread = new Thread(this);
   timerThread.setDaemon(true);
   timerThread.start();
   _maximumRequestWarnTime =
       ERXProperties.longForKeyWithDefault(
           "er.extensions.ERXStatisticsStore.milliSeconds.warn", 2000L);
   _maximumRequestErrorTime =
       ERXProperties.longForKeyWithDefault(
           "er.extensions.ERXStatisticsStore.milliSeconds.error", 10000L);
   _maximumRequestFatalTime =
       ERXProperties.longForKeyWithDefault(
           "er.extensions.ERXStatisticsStore.milliSeconds.fatal", 5 * 60 * 1000L);
 }
Пример #8
0
  public void takeValuesFromRequest(WORequest request, WOContext context) {
    if (context._wasFormSubmitted()) {
      super.takeValuesFromRequest(request, context);

      String apiKey = ERXProperties.stringForKey("er.captcha.akismet.apiKey");
      String url =
          ERXProperties.stringForKeyWithDefault(
              "er.captcha.akismet.url", "http://" + request._serverName());
      Akismet api = new Akismet(apiKey, url);
      if (ERXApplication.isDevelopmentModeSafe()) {
        if (!api.verifyAPIKey()) {
          throw new RuntimeException(
              "The API key you provided is invalid. Please set a valid api key in the property 'er.captcha.akismet.apiKey'.");
        }
      }

      String ipAddress = stringValueForBinding("remoteAddress", request._remoteAddress());
      String userAgent = stringValueForBinding("userAgent", request.headerForKey("user-agent"));
      String referrer = stringValueForBinding("referrer", request.headerForKey("referer"));
      String permalink = stringValueForBinding("permalink");
      String commentType = stringValueForBinding("commentType");
      String author = stringValueForBinding("author");
      String authorEmail = stringValueForBinding("authorEmail");
      String authorURL = stringValueForBinding("authorURL");
      String content = stringValueForBinding("content");
      Map other = null;

      boolean isSpam =
          api.commentCheck(
              ipAddress,
              userAgent,
              referrer,
              permalink,
              commentType,
              author,
              authorEmail,
              authorURL,
              content,
              other);
      if (isSpam) {
        validationFailedWithException(
            new NSValidation.ValidationException("Spam check failed."),
            this,
            ERXSimpleSpamCheck.SPAM_CHECK_KEY);
        setValueForBinding(Boolean.FALSE, "valid");
      } else {
        setValueForBinding(Boolean.TRUE, "valid");
      }
    }
  }
Пример #9
0
  @Override
  public NSArray getRequestHandlerPathForRequest(WORequest request) {
    NSMutableArray<Object> requestHandlerPath = new NSMutableArray<Object>();

    try {
      String path = request._uriDecomposed().requestHandlerPath();

      ERXRoute matchingRoute =
          setupRequestWithRouteForMethodAndPath(request, request.method(), path);
      if (matchingRoute != null) {
        @SuppressWarnings("unchecked")
        NSDictionary<ERXRoute.Key, String> keys =
            (NSDictionary<ERXRoute.Key, String>)
                request.userInfo().objectForKey(ERXRouteRequestHandler.KeysKey);
        String controller = keys.objectForKey(ERXRoute.ControllerKey);
        String actionName = keys.objectForKey(ERXRoute.ActionKey);
        requestHandlerPath.addObject(controller);
        requestHandlerPath.addObject(actionName);
      } else {
        requestHandlerPath.addObject(
            ERXProperties.stringForKeyWithDefault(
                "ERXRest.missingControllerName", "ERXMissingRouteController"));
        requestHandlerPath.addObject("missing");
        // throw new FileNotFoundException("There is no controller for the route '" + path + "'.");
      }

    } catch (Throwable t) {
      throw new RuntimeException("Failed to process the requested route.", t);
    }

    return requestHandlerPath;
  }
Пример #10
0
 /**
  * Sets a System property. This is also active in deployment mode because one might want to change
  * a System property at runtime. Synopsis:<br>
  * pw=<i>aPassword</i>&key=<i>someSystemPropertyKey</i>&value=<i>someSystemPropertyValue</i>
  *
  * @return either null when the password is wrong or a new page showing the System properties
  */
 public WOActionResults systemPropertyAction() {
   if (canPerformActionWithPasswordKey(
       "er.extensions.ERXDirectAction.ChangeSystemPropertyPassword")) {
     String key = request().stringFormValueForKey("key");
     ERXResponse r = new ERXResponse();
     if (ERXStringUtilities.stringIsNullOrEmpty(key)) {
       String user = request().stringFormValueForKey("user");
       Properties props = ERXConfigurationManager.defaultManager().defaultProperties();
       if (user != null) {
         System.setProperty("user.name", user);
         props = ERXConfigurationManager.defaultManager().applyConfiguration(props);
       }
       r.appendContentString(ERXProperties.logString(props));
     } else {
       String value = request().stringFormValueForKey("value");
       value = ERXStringUtilities.stringIsNullOrEmpty(value) ? "" : value;
       java.util.Properties p = System.getProperties();
       p.put(key, value);
       System.setProperties(p);
       ERXLogger.configureLoggingWithSystemProperties();
       for (java.util.Enumeration e = p.keys(); e.hasMoreElements(); ) {
         Object k = e.nextElement();
         if (k.equals(key)) {
           r.appendContentString(
               "<b>'" + k + "=" + p.get(k) + "'     <= you changed this</b><br>");
         } else {
           r.appendContentString("'" + k + "=" + p.get(k) + "'<br>");
         }
       }
       r.appendContentString("</body></html>");
     }
     return r;
   }
   return forbiddenResponse();
 }
Пример #11
0
 public String getMessageOfTheDay() {
   String message =
       (_messageOfTheDay == null)
           ? ERXProperties.stringForKey("decor.messageOfTheDay")
           : _messageOfTheDay;
   return message;
 }
Пример #12
0
 /**
  * <span class="en"> Gets the array of black list email address patterns.
  *
  * @return array of black list email address patterns </span>
  *     <p><span class="ja"> ブラック・リスト・メールアドレス配列パターンを戻します。
  * @return ブラック・リスト・メールアドレス配列パターン </span>
  */
 @SuppressWarnings("unchecked")
 public NSArray<String> blackListEmailAddressPatterns() {
   if (blakListEmailAddressPatterns == null) {
     blakListEmailAddressPatterns =
         ERXProperties.arrayForKeyWithDefault(
             "er.javamail.BlackListEmailAddressPatterns", NSArray.EmptyArray);
   }
   return blakListEmailAddressPatterns;
 }
Пример #13
0
  /**
   * <span class="en"> This method is used to initialize ERJavaMail from System properties. Later,
   * we will implement a way to initialize those properties everytime the propertis are changed. The
   * observer will call this method whenever appropriate. </span>
   *
   * <p><span class="ja"> このメソッドは ERJavaMail をシステム・プロパティより初期化するためにあります。
   * 後でプロパティが変更される度にこのメソッドが実行される処理を追加実装します。 </span>
   */
  public void initializeFrameworkFromSystemProperties() {
    // Centralize mails ?
    boolean centralize = ERXProperties.booleanForKey("er.javamail.centralize");
    setCentralize(centralize);
    log.debug("er.javamail.centralize: " + centralize);

    String adminEmail = System.getProperty("er.javamail.adminEmail");
    if (isValidEmail(adminEmail)) {
      setAdminEmail(adminEmail);
      log.debug("er.javamail.adminEmail: " + _adminEmail);
    } else if (centralize) {
      throw new IllegalArgumentException(
          "When 'er.javamail.centralize' is true (default),"
              + " all outgoing mails will get sent to 'er.javamail.adminEmail'"
              + " instead of the normal TO addresses, but you did not provide a valid email for that property.");
    }

    // JavaMail Debug Enabled ?
    boolean debug = ERXProperties.booleanForKey("er.javamail.debugEnabled");
    setDebugEnabled(debug);
    log.debug("er.javamail.debugEnabled: " + debug);

    // Number of messages that the sender queue can hold at a time
    int queueSize = ERXProperties.intForKey("er.javamail.senderQueue.size");
    if (queueSize >= 1) setSenderQueueSize(queueSize);
    log.debug("er.javamail.senderQueue.size: " + queueSize);

    // Time to wait when sender if overflowed
    int milliswait = ERXProperties.intForKey("er.javamail.milliSecondsWaitIfSenderOverflowed");
    if (milliswait > 1000) setMilliSecondsWaitIfSenderOverflowed(milliswait);
    log.debug("er.javamail.milliSecondsWaitIfSenderOverflowed: " + milliswait);

    // Smtp host
    setupSmtpHostSafely();

    setDefaultSession(newSession());

    if (defaultSession() == null) log.warn("Unable to create default mail session!");

    // Default X-Mailer header
    setDefaultXMailerHeader(System.getProperty("er.javamail.XMailerHeader"));
    log.debug("er.javamail.XMailHeader: " + defaultXMailerHeader());
  }
Пример #14
0
 public void createTables() {
   ec = ERXEC.newEditingContext();
   ec.lock();
   try {
     boolean dropTables = ERXProperties.booleanForKeyWithDefault("dropTables", true);
     createTables(dropTables);
   } finally {
     ec.unlock();
   }
 }
Пример #15
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);
  }
 private String documentRoot() {
   if (_documentRoot == null) {
     _documentRoot = ERXProperties.stringForKey("WODocumentRoot");
     if (_documentRoot == null) {
       NSBundle bundle = NSBundle.bundleForName("JavaWebObjects");
       NSDictionary dict =
           ERXDictionaryUtilities.dictionaryFromPropertyList("WebServerConfig", bundle);
       _documentRoot = (String) dict.objectForKey("DocumentRoot");
     }
   }
   return _documentRoot;
 }
Пример #17
0
 /**
  * Sets the default EOEntity class to com.webobjects.eoaccess.ERXEntity. You can provide your own
  * via the property <code>er.extensions.ERXModel.defaultEOEntityClassName</code> however your
  * class must be in the same package unless you plan on re-implementing eof itself.
  *
  * @see com.webobjects.eoaccess.EOModel#_addEntityWithPropertyList(java.lang.Object)
  */
 @Override
 public Object _addEntityWithPropertyList(Object propertyList)
     throws InstantiationException, IllegalAccessException {
   NSMutableDictionary<String, Object> list =
       ((NSDictionary<String, Object>) propertyList).mutableClone();
   if (list.objectForKey("entityClass") == null) {
     String eoEntityClassName =
         ERXProperties.stringForKey("er.extensions.ERXModel.defaultEOEntityClassName");
     if (eoEntityClassName == null) {
       eoEntityClassName = ERXEntity.class.getName();
     }
     list.setObjectForKey(eoEntityClassName, "entityClass");
   }
   return super._addEntityWithPropertyList(list);
 }
  /** Class initialization */
  public static synchronized void init() {
    // Find out if the user has set properties different than the defaults
    // EntityNameSeparator
    String entityNameSep =
        System.getProperty("er.extensions.ERXEOEncodingUtilities.EntityNameSeparator");
    if ((entityNameSep != null)
        && (entityNameSep.length() > 0)
        && !entityNameSep.equals(AttributeValueSeparator)) setEntityNameSeparator(entityNameSep);

    // Specify separator in link ?
    setSpecifySeparatorInURL(
        ERXProperties.booleanForKeyWithDefault(
            "er.extensions.ERXEOEncodingUtilities.SpecifySeparatorInURL", true));
    initialized = true;
  }
Пример #19
0
  /**
   * <div class="ja"> ネットワークインアーフェースからIP一覧を得る
   *
   * @return 動作マシンのネットワーク設定が所有しているIPアドレス配列
   * @exception Exception </div>
   */
  private static NSArray<String> _machineIpList() throws Exception {
    // ワーク用
    NSMutableArray<String> workArray = new NSMutableArray<String>();

    // 全ネットワーク・インタフェース
    Enumeration<NetworkInterface> enNi = NetworkInterface.getNetworkInterfaces();
    while (enNi.hasMoreElements()) {
      NetworkInterface ni = enNi.nextElement();

      // 全 InetAddress
      Enumeration<InetAddress> enIp = ni.getInetAddresses();
      while (enIp.hasMoreElements()) {
        String ip = enIp.nextElement().getHostAddress();

        // IP アドレスとプロパティー内に保存されている優先順を合体する
        if ((ip.indexOf(":") < 0) && (!ip.equals(LOCAL_IP_ADDRESS))) {

          String ipPri =
              ERXProperties.stringFor2Keys(
                  "er.erxtensions.ERXTcpIp.IpPriority" + ip, "wodka.a10.A10TcpIp.IpPriority" + ip);
          if (ERXStringUtilities.stringIsNullOrEmpty(ipPri)) {
            ipPri = "9999";
          } else {
            ipPri = ERXStringUtilities.trimZeroInFrontOfNumbers(ipPri);

            while (ipPri.length() < 4) {
              ipPri = "0" + ipPri;
            }
          }

          workArray.addObject(ipPri + UNDER_BAR + ip);
        }
      }
    }

    // 優先順位順に並べ、IPのみ抜き出してArrayListにする
    workArray.sortUsingComparator(NSComparator.AscendingStringComparator);

    // 戻す配列の準備
    NSMutableArray<String> resultArray = new NSMutableArray<String>(workArray.count());

    for (String obj : workArray) {
      resultArray.addObject(obj.substring(5));
    }

    return resultArray.immutableClone();
  }
Пример #20
0
  /**
   * <span class="en"> Predicate used to validate email well-formness.
   *
   * @return true if the email is valid
   * @param email the email String value to validate
   * @return a <code>boolean</code> value </span>
   *     <p><span class="ja"> メールが正しいかどうかを検証します。
   * @param email - 検証するメール値
   * @return メールが有効であれば true が戻ります。 </span>
   */
  public synchronized boolean isValidEmail(String email) {
    if (_pattern == null) {
      String patternString = ERXProperties.stringForKey("er.javamail.emailPattern");
      if (patternString == null || patternString.trim().length() == 0) {
        patternString = EMAIL_VALIDATION_PATTERN;
      }

      try {
        _pattern = Pattern.compile(patternString);
      } catch (PatternSyntaxException e) {
        throw new RuntimeException(
            "The compilation of the email pattern '" + patternString + "' failed.", e);
      }
    }
    if (email != null) {
      return _pattern.matcher(email).matches();
    }
    return false;
  }
Пример #21
0
 /**
  * Checks if the action can be executed.
  *
  * @param passwordKey the password to test
  * @return <code>true</code> if action is allowed to be invoked
  */
 protected boolean canPerformActionWithPasswordKey(String passwordKey) {
   if (ERXApplication.isDevelopmentModeSafe()) {
     return true;
   }
   String password = ERXProperties.decryptedStringForKey(passwordKey);
   if (password == null || password.length() == 0) {
     log.error("Attempt to use action when key is not set: " + passwordKey);
     return false;
   }
   String requestPassword = request().stringFormValueForKey("pw");
   if (requestPassword == null) {
     requestPassword = (String) context().session().objectForKey("ERXDirectAction." + passwordKey);
   } else {
     context().session().setObjectForKey(requestPassword, "ERXDirectAction." + passwordKey);
   }
   if (requestPassword == null || requestPassword.length() == 0) {
     return false;
   }
   return password.equals(requestPassword);
 }
Пример #22
0
    /*------------------------------------------------------------------------------------------------*
     *  A L L   N O T I F I C A T I O N S                                 [ N O T I F I C A T I O N ]
     *------------------------------------------------------------------------------------------------*/
    public void allNotifications(NSNotification notification) {
      if (!ERXProperties.booleanForKey("pachy.logAllNotifications")) return;
      if (notification.name().equalsIgnoreCase("EOEditingContextDidCreate")) {
        EOEditingContext eo = (EOEditingContext) notification.object();
        EOObjectStore eos = eo.rootObjectStore();
        LOG.info("[-NOTIFY-] {} rootCoordinator={}", notification.name(), eos);
        NSArray<EOCooperatingObjectStore> storeArray =
            ((EOObjectStoreCoordinator) eos).cooperatingObjectStores();
        if (storeArray.count() > 0) {
          for (EOCooperatingObjectStore store : storeArray) {
            LOG.info("[OBSERVER] rootCoordinator contains={}", store);
          }
        } else LOG.info("[OBSERVER] rootCoordinator contains no cooperatingObjectStores");

      } else {
        LOG.info(
            "[-NOTIFY-] "
                + notification.name()
                + ((notification.name().equalsIgnoreCase("EOEntityLoadedNotification")
                        || (notification.name().equalsIgnoreCase("EOModelAddedNotification")))
                    ? ""
                    : " [" + notification.object() + "]"));
      }
    }
Пример #23
0
  @SuppressWarnings("unchecked")
  @Override
  public WOResponse handleRequest(WORequest request) {
    WOApplication application = WOApplication.application();
    application.awake();
    try {
      WOContext context = application.createContextForRequest(request);
      WOResponse response = application.createResponseInContext(context);

      Object output;
      try {
        String inputString = request.contentString();
        JSONObject input = new JSONObject(inputString);
        String wosid = request.cookieValueForKey("wosid");
        if (wosid == null) {
          ERXMutableURL url = new ERXMutableURL();
          url.setQueryParameters(request.queryString());
          wosid = url.queryParameter("wosid");
          if (wosid == null && input.has("wosid")) {
            wosid = input.getString("wosid");
          }
        }
        context._setRequestSessionID(wosid);
        WOSession session = null;
        if (context._requestSessionID() != null) {
          session = WOApplication.application().restoreSessionWithID(wosid, context);
        }
        if (session != null) {
          session.awake();
        }
        try {
          JSONComponentCallback componentCallback = null;

          ERXDynamicURL url = new ERXDynamicURL(request._uriDecomposed());
          String requestHandlerPath = url.requestHandlerPath();
          JSONRPCBridge jsonBridge;
          if (requestHandlerPath != null && requestHandlerPath.length() > 0) {
            String componentNameAndInstance = requestHandlerPath;
            String componentInstance;
            String componentName;
            int slashIndex = componentNameAndInstance.indexOf('/');
            if (slashIndex == -1) {
              componentName = componentNameAndInstance;
              componentInstance = null;
            } else {
              componentName = componentNameAndInstance.substring(0, slashIndex);
              componentInstance = componentNameAndInstance.substring(slashIndex + 1);
            }

            if (session == null) {
              session = context.session();
            }

            String bridgesKey =
                (componentInstance == null) ? "_JSONGlobalBridges" : "_JSONInstanceBridges";
            Map<String, JSONRPCBridge> componentBridges =
                (Map<String, JSONRPCBridge>) session.objectForKey(bridgesKey);
            if (componentBridges == null) {
              int limit =
                  ERXProperties.intForKeyWithDefault(
                      (componentInstance == null)
                          ? "er.ajax.json.globalBacktrackCacheSize"
                          : "er.ajax.json.backtrackCacheSize",
                      WOApplication.application().pageCacheSize());
              componentBridges = new LRUMap<String, JSONRPCBridge>(limit);
              session.setObjectForKey(componentBridges, bridgesKey);
            }
            jsonBridge = componentBridges.get(componentNameAndInstance);
            if (jsonBridge == null) {
              Class componentClass = _NSUtilities.classWithName(componentName);
              JSONComponent component;
              if (JSONComponent.class.isAssignableFrom(componentClass)) {
                component =
                    (JSONComponent)
                        _NSUtilities.instantiateObject(
                            componentClass,
                            new Class[] {WOContext.class},
                            new Object[] {context},
                            true,
                            false);
              } else {
                throw new SecurityException(
                    "There is no JSON component named '" + componentName + "'.");
              }
              jsonBridge =
                  createBridgeForComponent(
                      component, componentName, componentInstance, componentBridges);
            }

            componentCallback = new JSONComponentCallback(context);
            jsonBridge.registerCallback(componentCallback, WOContext.class);
          } else {
            jsonBridge = _sharedBridge;
          }

          try {
            output = jsonBridge.call(new Object[] {request, response, context}, input);
          } finally {
            if (componentCallback != null) {
              jsonBridge.unregisterCallback(componentCallback, WOContext.class);
            }
          }

          if (context._session() != null) {
            WOSession contextSession = context._session();
            // If this is a new session, then we have to force it to be a cookie session
            if (wosid == null) {
              boolean storesIDsInCookies = contextSession.storesIDsInCookies();
              try {
                contextSession.setStoresIDsInCookies(true);
                contextSession._appendCookieToResponse(response);
              } finally {
                contextSession.setStoresIDsInCookies(storesIDsInCookies);
              }
            } else {
              contextSession._appendCookieToResponse(response);
            }
          }
          if (output != null) {
            response.appendContentString(output.toString());
          }

          if (response != null) {
            response._finalizeInContext(context);
            response.disableClientCaching();
          }
        } finally {
          try {
            if (session != null) {
              session.sleep();
            }
          } finally {
            if (context._session() != null) {
              WOApplication.application().saveSessionForContext(context);
            }
          }
        }
      } catch (NoSuchElementException e) {
        e.printStackTrace();
        output =
            new JSONRPCResult(
                JSONRPCResult.CODE_ERR_NOMETHOD, null, JSONRPCResult.MSG_ERR_NOMETHOD);
      } catch (JSONException e) {
        e.printStackTrace();
        output = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, JSONRPCResult.MSG_ERR_PARSE);
      } catch (Throwable t) {
        t.printStackTrace();
        output = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, t.getMessage());
      }

      return response;
    } finally {
      application.sleep();
    }
  }
Пример #24
0
 public Boolean isMailEnabled() {
   return ERXProperties.booleanForKeyWithDefault("pachy.optionEnableMailing", false);
 }
Пример #25
0
  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);
      }
    }
  }
 @Override
 public void didFinishInitialization() {
   super.didFinishInitialization();
   if (ERXProperties.booleanForKeyWithDefault("EOFFixtures.loadInitialData", false))
     Fixtures.load();
 }
Пример #27
0
  protected void setupSmtpProperties(Properties properties, String contextString) {
    String contextSuffix = contextString == null ? "" : ("." + contextString);

    // Smtp host
    String smtpProtocol = smtpProtocolForContext(contextString);

    String smtpHost =
        ERXProperties.stringForKeyWithDefault(
            "er.javamail.smtpHost" + contextSuffix,
            ERXProperties.stringForKey("er.javamail.smtpHost"));
    if ((smtpHost == null) || (smtpHost.length() == 0)) {
      // Try to fail back to default java config
      smtpHost = ERXProperties.stringForKey("mail." + smtpProtocol + ".host");

      if ((smtpHost == null) || (smtpHost.length() == 0)) {
        // use the standard WO host
        smtpHost = ERXProperties.stringForKey("WOSMTPHost");
        if ((smtpHost == null) || (smtpHost.length() == 0)) {
          throw new RuntimeException(
              "ERJavaMail: You must specify a SMTP host for outgoing mail with the property 'er.javamail.smtpHost'");
        }
        // ... and then maybe actually do what the docs say this method is supposed to do
        properties.setProperty("mail." + smtpProtocol + ".host", smtpHost);
        properties.setProperty("er.javamail.smtpHost", smtpHost);
      } else {
        properties.setProperty("er.javamail.smtpHost", smtpHost);
      }
    } else {
      properties.setProperty("mail." + smtpProtocol + ".host", smtpHost);
    }
    log.debug("er.javamail.smtpHost: " + smtpHost);

    String port =
        ERXProperties.stringForKeyWithDefault(
            "er.javamail.smtpPort" + contextSuffix,
            ERXProperties.stringForKey("er.javamail.smtpPort"));
    if (port != null && port.length() > 0) {
      properties.setProperty("mail." + smtpProtocol + ".port", port);
      log.debug("ERJavaMail will use smtp port: " + port);
    }

    boolean smtpAuth =
        ERXProperties.booleanForKeyWithDefault(
            "er.javamail.smtpAuth" + contextSuffix,
            ERXProperties.booleanForKey("er.javamail.smtpAuth"));
    log.debug("ERJavaMail will use authenticated SMTP connections.");
    if (smtpAuth) {
      properties.setProperty("mail." + smtpProtocol + ".auth", String.valueOf(smtpAuth));
      String user =
          ERXProperties.stringForKeyWithDefault(
              "er.javamail.smtpUser" + contextSuffix,
              ERXProperties.stringForKey("er.javamail.smtpUser"));
      if (user == null || user.length() == 0) {
        throw new RuntimeException(
            "You specified er.javamail.smtpAuth=true, but you didn't specify an er.javamail.smtpUser to use as the login name.");
      }
      properties.setProperty("mail." + smtpProtocol + ".user", user);
      String password =
          ERXProperties.stringForKeyWithDefault(
              "er.javamail.smtpPassword" + contextSuffix,
              ERXProperties.stringForKey("er.javamail.smtpPassword"));
      if (password == null || password.length() == 0) {
        log.warn(
            "You specified er.javamail.smtpAuth=true, but you didn't set er.javamail.smtpPassword for the "
                + user
                + " mail user.");
      }
      if (password != null) {
        properties.setProperty("mail." + smtpProtocol + ".password", password);
      }
    }
    if ("smtps".equals(smtpProtocol)) {
      properties.setProperty("mail.smtps.socketFactory.fallback", "false");
    }
  }
Пример #28
0
 // Lazy static initialization
 private static class PROPERTIES {
   static boolean shouldFlattenValueObject =
       ERXProperties.booleanForKeyWithDefault(
           "er.extensions.ERXKeyValueQualifier.Contains.flatten", true);
 }
Пример #29
0
public class APAttribute extends _APAttribute {
  private static Logger LOG = LoggerFactory.getLogger(APAttribute.class);
  private static final long serialVersionUID = 5717313835078646106L;

  private Boolean logInAwake =
      ERXProperties.booleanForKeyWithDefault("pachy.logInAwakeMethods", false);

  /*------------------------------------------------------------------------------------------------*
   *  Overridden by subclasses to perform additional initialization on the receiver upon its being
   *  fetched from the external repository into EOEditingContext. EOCustomObject's implementation
   *  merely sends an awakeObjectFromFetch to the receiver's EOClassDescription.
   *
   *  Subclasses should invoke super's implementation before performing their own initialization.
   *------------------------------------------------------------------------------------------------*/
  @Override
  public void awakeFromFetch(EOEditingContext ec) {
    super.awakeFromFetch(ec);

    if (logInAwake) {
      LOG.info(
          "----->  awakeFromFetch: ({}) EOs: ({}), +({}), ~({}), -({})",
          ec,
          ec.registeredObjects().count(),
          ec.insertedObjects().count(),
          ec.updatedObjects().count(),
          ec.deletedObjects().count());

      @SuppressWarnings("unchecked")
      NSArray<ERXGenericRecord> genericRecords = ec.registeredObjects();
      for (ERXGenericRecord genericRecord : genericRecords)
        LOG.info("        EOs: " + genericRecord);
    }
  }

  /*------------------------------------------------------------------------------------------------*
   * Overridden by subclasses to perform additional initialization on the receiver upon its being
   * inserted into EOEditingContext. This is commonly used to assign default values or record the
   * time of insertion. EOCustomObject's implementation merely sends an awakeObjectFromInsertion
   * to the receiver's EOClassDescription.
   *
   * Subclasses should invoke super's implementation before performing their own initialization.
   *------------------------------------------------------------------------------------------------*/
  @Override
  public void awakeFromInsertion(EOEditingContext ec) {
    super.awakeFromInsertion(ec);

    LOG.info(
        "-----> awakeFromInsert: ({}) EOs: ({}), +({}), ~({}), -({})",
        ec,
        ec.registeredObjects().count(),
        ec.insertedObjects().count(),
        ec.updatedObjects().count(),
        ec.deletedObjects().count());
  }

  public String getStringValue() { // called from a maintenance DirectAction
    LOG.info("getStringValue()");
    return new String(value().bytes());
  }

  /*------------------------------------------------------------------------------------------------*
   * APOLLO_Relationship-PachydermTransformedAssets
   *------------------------------------------------------------------------------------------------*/
  public static APAttribute createAPAttribute(EOEditingContext ec, String id, String key) {
    LOG.info("-----> createAPAttribute");
    //    if (key.equalsIgnoreCase("APOLLO_Relationship-PachydermTransformedAssets")) {
    //      APAttribute eo = (APAttribute) EOUtilities.createAndInsertInstance(ec,
    // _APAttribute.ENTITY_NAME);
    //      eo.setIdentifier(id);
    //      eo.setKey(key);
    //      return eo;
    //    }

    return null;
  }

  public String identifier() {
    String value = super.identifier();
    LOG.info("identifier ==> '" + value + "'");
    return value;
  }

  public void setIdentifier(String value) {
    LOG.info("identifier <== '" + value + "'");
    super.setIdentifier(value);
  }

  public String key() {
    String value = super.key();
    LOG.info("       key ==> '" + value + "'");
    return value;
  }

  public void setKey(String value) {
    LOG.info("       key <== '" + value + "'");
    super.setKey(value);
  }

  public NSData value() {
    NSData value = super.value();
    LOG.info("     value ==> '" + (new String(value.bytes())).replace('\n', ' ') + "'");
    return value;
  }

  public void setValue(NSData value) {
    LOG.info("     value <== '" + (new String(value.bytes())).replace('\n', ' ') + "'");
    super.setValue(value);
  }
}
Пример #30
0
 public boolean _isAdditionalForeignSupportedDevelopmentPlatform() {
   String osName = ERXProperties.stringForKey("os.name");
   return (osName != null && osName.equals("Linux"));
 }