Exemplo n.º 1
0
/**
 * Class defining 2 new Logging levels, one for STDOUT, one for STDERR, used when multiplexing
 * STDOUT and STDERR into the same rolling log file via the Java Logging APIs.
 */
public class StdOutErrLevel extends Level {

  private StdOutErrLevel(String name, int value) {
    super(name, value);
  }

  /** Level for STDOUT activity. */
  public static Level STDOUT = new StdOutErrLevel("STDOUT", Level.INFO.intValue() + 53);
  /** Level for STDERR activity */
  public static Level STDERR = new StdOutErrLevel("STDERR", Level.INFO.intValue() + 54);

  /**
   * Method to avoid creating duplicate instances when deserializing the object.
   *
   * @return the singleton instance of this <code>Level</code> value in this classloader
   * @throws ObjectStreamException If unable to deserialize
   */
  protected Object readResolve() throws ObjectStreamException {
    if (this.intValue() == INFO.intValue()) {
      return INFO;
    }
    if (this.intValue() == STDERR.intValue()) {
      return STDERR;
    }
    throw new InvalidObjectException("Unknown instance :" + this);
  }
}
    @Override
    public void configureRegistry(IConfigRegistry configRegistry) {
      super.configureRegistry(configRegistry);

      Style errorStyle = new Style();
      errorStyle.setAttributeValue(CellStyleAttributes.IMAGE, ERROR_IMAGE);
      configRegistry.registerConfigAttribute(
          CellConfigAttributes.CELL_STYLE, errorStyle, DisplayMode.NORMAL, Level.SEVERE.toString());

      Style warningStyle = new Style();
      warningStyle.setAttributeValue(CellStyleAttributes.IMAGE, WARNING_IMAGE);
      configRegistry.registerConfigAttribute(
          CellConfigAttributes.CELL_STYLE,
          warningStyle,
          DisplayMode.NORMAL,
          Level.WARNING.toString());

      Style informationStyle = new Style();
      informationStyle.setAttributeValue(CellStyleAttributes.IMAGE, INFORMATION_IMAGE);
      configRegistry.registerConfigAttribute(
          CellConfigAttributes.CELL_STYLE,
          informationStyle,
          DisplayMode.NORMAL,
          Level.INFO.toString());
    }
Exemplo n.º 3
0
/** Class that encapsulates an O/C mapping event */
public class OCMEvent {

  public int level = Level.INFO.intValue();
  // public int 			id;
  public String name;
  public Object sender;
  public Object parameter;

  /** Constructor for OCMEvent. */
  public OCMEvent(String name, Object sender, Object parameter) {
    // this.id = id;
    this.name = name;
    this.sender = sender;
    this.parameter = parameter;
  }

  public String toString() {
    StringBuffer buf = new StringBuffer();
    buf.append("Event Name:").append(name);
    buf.append(" sender:" + sender);
    if (parameter != null) {
      buf.append(" Parameter:");
      if (parameter instanceof CompositeMap) buf.append(((CompositeMap) parameter).toXML());
      else buf.append(parameter);
    }
    return buf.toString();
  }

  public Level getLevel() {
    return LoggingUtil.getLevel(level);
  }
}
Exemplo n.º 4
0
 private String getColor(int logLevel) {
   if (logLevel == Level.OFF.intValue()) {
     return "#000"; // black
   }
   if (logLevel >= Level.SEVERE.intValue()) {
     return "#F00"; // bright red
   }
   if (logLevel >= Level.WARNING.intValue()) {
     return "#E56717"; // dark orange
   }
   if (logLevel >= Level.INFO.intValue()) {
     return "#20b000"; // green
   }
   if (logLevel >= Level.CONFIG.intValue()) {
     return "#2B60DE"; // blue
   }
   if (logLevel >= Level.FINE.intValue()) {
     return "#F0F"; // purple
   }
   if (logLevel >= Level.FINER.intValue()) {
     return "#F0F"; // purple
   }
   if (logLevel >= Level.FINEST.intValue()) {
     return "#F0F"; // purple
   }
   return "#000"; // black
 }
Exemplo n.º 5
0
 JComboBox makeDebugLevelDropdown() {
   String levelName = Base.preferences.get("replicatorg.debuglevel", Level.INFO.getName());
   Level l = Level.parse(levelName);
   if (l == null) {
     l = Level.INFO;
   }
   Vector<Level> levels = new Vector<Level>();
   levels.add(Level.ALL);
   levels.add(Level.FINEST);
   levels.add(Level.FINER);
   levels.add(Level.FINE);
   levels.add(Level.INFO);
   levels.add(Level.WARNING);
   final ComboBoxModel model = new DefaultComboBoxModel(levels);
   model.setSelectedItem(l);
   JComboBox cb = new JComboBox(model);
   cb.addActionListener(
       new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
           Level level = (Level) (model.getSelectedItem());
           Base.preferences.put("replicatorg.debuglevel", level.getName());
           Base.logger.setLevel(level);
         }
       });
   return cb;
 }
Exemplo n.º 6
0
  {
    String levelName = Base.preferences.get("replicatorg.debuglevel", Level.INFO.getName());
    Level l = Level.parse(levelName);
    logger.setLevel(l);

    /*
     * 	TODO: Add log-to-file option to preferences.
    		// Add logfile handler
    	    try {
    	      boolean append = true;
    	      FileHandler fh = new FileHandler("RepG.log", append);
    	      //fh.setFormatter(new XMLFormatter());
    	      fh.setFormatter(new SimpleFormatter());
    	      logger.addHandler(fh);
    	    }
    	    catch (IOException e) {
    	      e.printStackTrace();
    	    }

    		// Configure handlers to use selected level
    	    Handler[] handlers =
    	    logger.getHandlers();
    	    for ( int index = 0; index < handlers.length; index++ ) {
    	    	handlers[index].setLevel( l );
    	    }
    */
  }
Exemplo n.º 7
0
 @Override
 public void publish(LogRecord record) {
   if ((record.getLevel().intValue() > Level.INFO.intValue())
       && thrown == null
       && record.getThrown() != null) {
     thrown = record.getThrown();
   }
 }
  protected int mapLevelToAnt(final Level level) {
    if (Level.CONFIG.equals(level)) return Project.MSG_DEBUG;
    if (Level.FINE.equals(level)) return Project.MSG_VERBOSE;
    if (Level.FINER.equals(level)) return Project.MSG_DEBUG;
    if (Level.FINEST.equals(level)) return Project.MSG_DEBUG;
    if (Level.INFO.equals(level)) return Project.MSG_INFO;
    if (Level.SEVERE.equals(level)) return Project.MSG_ERR;
    if (Level.WARNING.equals(level)) return Project.MSG_WARN;

    return Project.MSG_WARN;
  }
Exemplo n.º 9
0
 public ChatArguments colorizeLevel(Level level) {
   ChatStyle color;
   if (level.intValue() >= Level.SEVERE.intValue()) {
     color = ChatStyle.RED;
   } else if (level.intValue() >= Level.WARNING.intValue()) {
     color = ChatStyle.YELLOW;
   } else if (level.intValue() >= Level.INFO.intValue()) {
     color = ChatStyle.DARK_GREEN;
   } else {
     color = ChatStyle.GRAY;
   }
   return new ChatArguments(color, level, ChatStyle.RESET);
 }
Exemplo n.º 10
0
 protected static void Log(Level loglevel, String txt, boolean sendReport) {
   logger.log(loglevel, String.format("[%s] %s", name, txt == null ? "" : txt));
   if (config != null) {
     if (sendReport && loglevel.intValue() > Level.WARNING.intValue() && config.sendErrorReports) {
       sendErrorReport(txt, null);
     }
     if (messenger != null
         && loglevel.intValue() > Level.INFO.intValue()
         && config.sendLogOnError) {
       messenger.sendNotify(String.format("[%s] %s", name, txt == null ? "" : txt));
     }
   }
 }
 private static LogLevel getLogLevel(LogRecord record) {
   int level = record.getLevel().intValue();
   if (level <= Level.CONFIG.intValue()) {
     return LogLevel.DEBUG;
   } else if (level <= Level.INFO.intValue()) {
     return LogLevel.INFO;
   } else if (level <= Level.WARNING.intValue()) {
     return LogLevel.WARN;
   } else if (level <= Level.SEVERE.intValue()) {
     return LogLevel.ERROR;
   } else {
     return LogLevel.FATAL;
   }
 }
Exemplo n.º 12
0
  @Override
  protected final void format0(LogRecord record, TextBuilder tb) {
    tb.append(record.getLevel()).append(" ");

    appendDateSys(record, tb);

    if (record.getLevel().intValue() > Level.INFO.intValue() || record.getThrown() != null)
      tb.append(record.getSourceClassName())
          .append(".")
          .append(record.getSourceMethodName())
          .append("(): ");

    appendMessage(record, tb);
    appendThrown(record, tb);
  }
Exemplo n.º 13
0
  private boolean upgrade5() {
    boolean upgraded = false;

    if (settingVer == 4) {
      scanInterval = 100;
      logLevel = Level.INFO.getName();
      settingVer = 5;
      upgraded = true;
      System.out.println("upgraded!");
    }
    if (settingVer >= 5) {
      upgraded = true;
    }

    return upgraded;
  }
Exemplo n.º 14
0
    @Override
    public void publish(LogRecord record) {
      Level level = record.getLevel();
      Throwable t = record.getThrown();
      AttributeSet attributes = defaultAttributes;

      if (level.intValue() >= Level.WARNING.intValue()) {
        attributes = errorAttributes;
      } else if (level.intValue() < Level.INFO.intValue()) {
        attributes = debugAttributes;
      }

      log(record.getMessage() + "\n", attributes);
      if (t != null) {
        log(getStackTrace(t) + "\n", attributes);
      }
    }
Exemplo n.º 15
0
 protected static void Log(Level loglevel, Exception err, boolean sendReport) {
   logger.log(
       loglevel,
       String.format("[%s] %s", name, err == null ? "? unknown exception ?" : err.getMessage()),
       err);
   if (config != null) {
     if (sendReport && loglevel.intValue() > Level.WARNING.intValue() && config.sendErrorReports) {
       sendErrorReport(null, err);
     }
     if (messenger != null
         && loglevel.intValue() > Level.INFO.intValue()
         && config.sendLogOnError) {
       messenger.sendNotify(
           String.format(
               "[%s] %s%n%s",
               name,
               err == null ? "? unknown exception ?" : err.getMessage(),
               Str.getStackStr(err)));
     }
   }
 }
  private synchronized void append(LogRecord record) {
    Document doc = textArea.getStyledDocument();
    String formatted = formatter.format(record);

    if (record.getLevel().intValue() >= Level.SEVERE.intValue()) {
      StyleConstants.setForeground(attributeSet, COLOR_ERROR);
      StyleConstants.setBold(attributeSet, true);
    } else if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
      StyleConstants.setForeground(attributeSet, COLOR_WARNING);
      StyleConstants.setBold(attributeSet, true);
    } else if (record.getLevel().intValue() >= Level.INFO.intValue()) {
      StyleConstants.setForeground(attributeSet, COLOR_INFO);
      StyleConstants.setBold(attributeSet, false);
    } else {
      StyleConstants.setForeground(attributeSet, COLOR_DEFAULT);
      StyleConstants.setBold(attributeSet, false);
    }

    try {
      doc.insertString(doc.getLength(), formatted, attributeSet);
    } catch (BadLocationException e) {
      // cannot happen
      // rather dump to stderr than logging and having this method called back
      e.printStackTrace();
    }

    if (maxRows >= 0) {
      int removeLength = 0;
      while (lineLengths.size() > maxRows) {
        removeLength += lineLengths.removeFirst();
      }
      try {
        doc.remove(0, removeLength);
      } catch (BadLocationException e) {
        SwingTools.showSimpleErrorMessage("error_during_logging", e);
      }
    }
    textArea.setCaretPosition(textArea.getDocument().getLength());
  }
Exemplo n.º 17
0
    public void publish(LogRecord record) {

      Level level = record.getLevel();
      Throwable throwable = record.getThrown();

      if (Level.SEVERE.equals(level)) {

        if (throwable != null) {
          Log.error(record.getMessage(), throwable);
        } else {
          Log.error(record.getMessage());
        }

      } else if (Level.WARNING.equals(level)) {

        if (throwable != null) {
          Log.warn(record.getMessage(), throwable);
        } else {
          Log.warn(record.getMessage());
        }

      } else if (Level.INFO.equals(level)) {

        if (throwable != null) {
          Log.info(record.getMessage(), throwable);
        } else {
          Log.info(record.getMessage());
        }

      } else {
        // else FINE,FINER,FINEST

        if (throwable != null) {
          Log.debug(record.getMessage(), throwable);
        } else {
          Log.debug(record.getMessage());
        }
      }
    }
Exemplo n.º 18
0
/**
 * A class for making custom levels for logging.
 *
 * @author Ronald Kramp - Finalist IT Group
 * @version $Revision: 1.1 $, $Date: 2005/10/13 21:17:51 $
 */
class CustomLevel extends Level {

  /** a Level for DEBUG */
  public static final Level DEBUG = new CustomLevel("DEBUG", Level.INFO.intValue() - 1);

  /** a Level for ERROR */
  public static final Level ERROR = new CustomLevel("ERROR", Level.SEVERE.intValue() - 1);

  /** a Level for FATAL */
  public static final Level FATAL = new CustomLevel("FATAL", Level.SEVERE.intValue() + 1);

  /**
   * Constrcutor for making a custom level.
   *
   * @param name, the name of the Level
   * @param value, the value for the level
   */
  public CustomLevel(String name, int value) {
    super(name, value);
  }

  /**
   * Parse a levelName to a Level object.
   *
   * @param levelName the name of the Level to parse to a Level obhect
   * @return Level the Level object parsed
   */
  public static Level parse(String levelName) {
    if (levelName.equals("DEBUG")) {
      return DEBUG;
    } else if (levelName.equals("ERROR")) {
      return ERROR;
    } else if (levelName.equals("FATAL")) {
      return FATAL;
    } else {
      return Level.parse(levelName);
    }
  }
}
Exemplo n.º 19
0
 protected static void Log(Level loglevel, String txt, Exception params, boolean sendReport) {
   if (txt == null) {
     Log(loglevel, params);
   } else {
     logger.log(
         loglevel, String.format("[%s] %s", name, txt == null ? "" : txt), (Exception) params);
     if (config != null) {
       if (sendReport
           && loglevel.intValue() > Level.WARNING.intValue()
           && config.sendErrorReports) {
         sendErrorReport(txt, params);
       }
       if (messenger != null
           && loglevel.intValue() > Level.INFO.intValue()
           && config.sendLogOnError) {
         messenger.sendNotify(
             String.format(
                 "[%s] %s%n%s", name, txt, params.getMessage(), Str.getStackStr(params)));
       }
     }
   }
 }
Exemplo n.º 20
0
/** @author Kamnev Georgiy */
public class LocalRepoCommands extends BaseCLIFun {
  // <editor-fold defaultstate="collapsed" desc="log Функции">
  private static final Logger logger = Logger.getLogger(LocalRepoCommands.class.getName());
  private static final Level logLevel = logger.getLevel();
  private static final boolean isLogSevere =
      logLevel == null ? true : logLevel.intValue() <= Level.SEVERE.intValue();

  private static final boolean isLogWarning =
      logLevel == null ? true : logLevel.intValue() <= Level.WARNING.intValue();

  private static final boolean isLogInfo =
      logLevel == null ? true : logLevel.intValue() <= Level.INFO.intValue();

  private static final boolean isLogFine =
      logLevel == null ? true : logLevel.intValue() <= Level.FINE.intValue();

  private static final boolean isLogFiner =
      logLevel == null ? true : logLevel.intValue() <= Level.FINER.intValue();

  private static final boolean isLogFinest =
      logLevel == null ? true : logLevel.intValue() <= Level.FINEST.intValue();

  private static void logFine(String message, Object... args) {
    logger.log(Level.FINE, message, args);
  }

  private static void logFiner(String message, Object... args) {
    logger.log(Level.FINER, message, args);
  }

  private static void logFinest(String message, Object... args) {
    logger.log(Level.FINEST, message, args);
  }

  private static void logInfo(String message, Object... args) {
    logger.log(Level.INFO, message, args);
  }

  private static void logWarning(String message, Object... args) {
    logger.log(Level.WARNING, message, args);
  }

  private static void logSevere(String message, Object... args) {
    logger.log(Level.SEVERE, message, args);
  }

  private static void logException(Throwable ex) {
    logger.log(Level.SEVERE, null, ex);
  }
  // </editor-fold>

  //    public final UpMain upmain;
  //
  //    public LocalRepoCommands( UpMain upmain ){
  //        if( upmain==null )throw new IllegalArgumentException( "upmain==null" );
  //        this.upmain = upmain;
  //    }

  //    public void println(){
  //        upmain.getOutput().println();
  //    }
  //
  //    public void println(Object obj){
  //        upmain.getOutput().println(obj);
  //    }
  //
  //    public BasicTemplate.EasyTemplate template(String template){
  //        return upmain.getOutput().template(template);
  //    }

  @Fun
  @Name(name = "localRepo")
  @Help(shortDesc = "create local repo")
  public LocalUplaunchRepo localRepo(
      @Name(name = "path") @Help(shortDesc = "location of repo") String path) {
    if (path == null) return null;

    File froot = FileSystems.get(path);
    File dir = froot;
    if (dir != null && !dir.isExists()) {
      dir.mkdirs();
    }

    LocalUplaunchRepo luprepo = new LocalUplaunchRepo();
    luprepo.setRoot(froot);

    return luprepo;
  }

  public static final Map<RepoConfig, LocalUplaunchRepo> configRepoMap =
      new WeakHashMap<RepoConfig, LocalUplaunchRepo>();

  // TODO doc it
  @Fun(operator = true)
  @Name(name = "config")
  public RepoConfig getConfig(LocalUplaunchRepo repo) {
    if (repo == null) throw new IllegalArgumentException("repo==null");
    RepoConfig rc = repo.getConfig();
    if (rc != null) {
      configRepoMap.put(rc, repo);
    }
    return rc;
  }

  // TODO doc it
  @Fun(operator = true)
  @Name(name = "print")
  public void print(RepoConfig config) {
    if (config == null) throw new IllegalArgumentException("config==null");

    String title = "";

    LocalUplaunchRepo urepo = configRepoMap.get(config);
    if (urepo != null) {
      String repoName = RepositoriesCommands.repoNameMap.get(urepo);
      if (repoName != null) {
        title = template("repo ${repoName} config\n").bind("repoName", repoName).eval();
      } else {
        title = "repo config\n";
      }
    }

    println(title);

    try {
      BeanInfo bi = Introspector.getBeanInfo(config.getClass());
      for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
        if (pd.getPropertyType() == null) continue;

        Method m = pd.getReadMethod();
        if (m == null) continue;

        try {
          Object val = m.invoke(config);
          template("${property:40} = ${value}")
              .bind("property", pd.getName())
              .bind("value", val)
              .println();
        } catch (IllegalAccessException ex) {
          Logger.getLogger(LocalRepoCommands.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalArgumentException ex) {
          Logger.getLogger(LocalRepoCommands.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvocationTargetException ex) {
          Logger.getLogger(LocalRepoCommands.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
    } catch (IntrospectionException ex) {
      Logger.getLogger(LocalRepoCommands.class.getName()).log(Level.SEVERE, null, ex);
    }

    //        template(
    //            "${title}"
    //                + "checkDepsOnInstall         = ${conf.checkDepsOnInstall}\n"
    //                + "checkDepsOnUnInstall       = ${conf.checkDepsOnUnInstall}\n"
    //                + "useFileLock                = ${conf.useFileLock}\n"
    //                + "updateIndex                = ${conf.updateIndex}\n"
    //                + "checkExistsComponentDir    = ${conf.checkExistsComponentDir}\n"
    //                + "emptyDirAsComponent        = ${conf.emptyDirAsComponent}\n"
    //                + "deleteEmptyDirsOnUnInstall = ${conf.deleteEmptyDirsOnUnInstall}\n"
    //                + "checkConfigChanges         = ${conf.checkConfigChanges}\n"
    //                + "refreshConfigOnChangeRoot  = ${conf.refreshConfigOnChangeRoot}\n"
    //        )
    //            .align()
    //            .bind("conf", config)
    //            .bind("title", title)
    //            .println();
  }

  public static class ConfigSet {
    public RepoConfig config;
    public String property;

    public ConfigSet(RepoConfig config, String property) {
      this.config = config;
      this.property = property;
    }
  }

  @Fun(operator = true)
  @Name(name = "set")
  public ConfigSet configSet_set(RepoConfig config, String property) {
    if (config == null) throw new IllegalArgumentException("config==null");
    if (property == null) throw new IllegalArgumentException("property==null");
    return new ConfigSet(config, property);
  }

  @Fun(operator = true)
  @Name(name = "=")
  public LocalUplaunchRepo configSet_apply(ConfigSet confSet, String value) {
    if (confSet == null) throw new IllegalArgumentException("confSet==null");
    if (value == null) throw new IllegalArgumentException("value==null");

    RepoConfig conf = confSet.config;
    String prop = confSet.property;

    TypeCastGraph tcast = new ExtendedCastGraph();

    try {
      BeanInfo bi = Introspector.getBeanInfo(conf.getClass());
      for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
        if (pd.getPropertyType() == null) continue;
        if (!pd.getName().equals(prop)) continue;

        Method m = pd.getWriteMethod();
        if (m == null) continue;

        Class t = pd.getPropertyType();
        Object val = tcast.cast(value, t);

        m.invoke(conf, val);
      }
    } catch (IntrospectionException ex) {
      Logger.getLogger(LocalRepoCommands.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      Logger.getLogger(LocalRepoCommands.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalArgumentException ex) {
      Logger.getLogger(LocalRepoCommands.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvocationTargetException ex) {
      Logger.getLogger(LocalRepoCommands.class.getName()).log(Level.SEVERE, null, ex);
    }

    return configRepoMap.get(conf);
  }

  // TODO doc it
  @Fun(operator = true)
  @Name(name = "refreshConfigOnChangeRoot")
  public LocalUplaunchRepo configSet_refreshConfigOnChangeRoot(RepoConfig config, boolean val) {
    if (config == null) throw new IllegalArgumentException("config==null");

    config.setRefreshConfigOnChangeRoot(val);

    LocalUplaunchRepo repo = configRepoMap.get(config);
    return repo;
  }

  // TODO doc it
  @Fun(operator = true)
  @Name(name = "checkConfigChanges")
  public LocalUplaunchRepo configSet_checkConfigChanges(RepoConfig config, boolean val) {
    if (config == null) throw new IllegalArgumentException("config==null");

    config.setCheckConfigChanges(val);

    LocalUplaunchRepo repo = configRepoMap.get(config);
    return repo;
  }

  // TODO doc it
  @Fun(operator = true)
  @Name(name = "deleteEmptyDirsOnUnInstall")
  public LocalUplaunchRepo configSet_deleteEmptyDirsOnUnInstall(RepoConfig config, boolean val) {
    if (config == null) throw new IllegalArgumentException("config==null");

    config.setDeleteEmptyDirsOnUnInstall(val);

    LocalUplaunchRepo repo = configRepoMap.get(config);
    return repo;
  }

  // TODO doc it
  @Fun(operator = true)
  @Name(name = "emptyDirAsComponent")
  public LocalUplaunchRepo configSet_emptyDirAsComponent(RepoConfig config, boolean val) {
    if (config == null) throw new IllegalArgumentException("config==null");

    config.setEmptyDirAsComponent(val);

    LocalUplaunchRepo repo = configRepoMap.get(config);
    return repo;
  }

  // TODO doc it
  @Fun(operator = true)
  @Name(name = "checkExistsComponentDir")
  public LocalUplaunchRepo configSet_checkExistsComponentDir(RepoConfig config, boolean val) {
    if (config == null) throw new IllegalArgumentException("config==null");

    config.setCheckExistsComponentDir(val);

    LocalUplaunchRepo repo = configRepoMap.get(config);
    return repo;
  }

  // TODO doc it
  @Fun(operator = true)
  @Name(name = "checkDepsOnInstall")
  public LocalUplaunchRepo configSetCDepsOnInst(RepoConfig config, boolean val) {
    if (config == null) throw new IllegalArgumentException("config==null");

    config.setCheckDepsOnInstall(val);

    LocalUplaunchRepo repo = configRepoMap.get(config);
    return repo;
  }

  // TODO doc it
  @Fun(operator = true)
  @Name(name = "checkDepsOnUnInstall")
  public LocalUplaunchRepo configSetCDepsOnUnInst(RepoConfig config, boolean val) {
    if (config == null) throw new IllegalArgumentException("config==null");

    config.setCheckDepsOnUnInstall(val);

    LocalUplaunchRepo repo = configRepoMap.get(config);
    return repo;
  }

  // TODO doc it
  @Fun(operator = true)
  @Name(name = "deps")
  public LocalUplaunchRepo configSetCDeps(RepoConfig config, boolean val) {
    if (config == null) throw new IllegalArgumentException("config==null");

    config.setCheckDepsOnUnInstall(val);
    config.setCheckDepsOnInstall(val);

    LocalUplaunchRepo repo = configRepoMap.get(config);
    return repo;
  }

  // TODO doc it
  @Fun(operator = true)
  @Name(name = "updateIndex")
  public LocalUplaunchRepo configSet_updateIndex(RepoConfig config, boolean val) {
    if (config == null) throw new IllegalArgumentException("config==null");

    config.setUpdateIndex(val);

    LocalUplaunchRepo repo = configRepoMap.get(config);
    return repo;
  }

  // TODO doc it
  @Fun(operator = true)
  @Name(name = "useFileLock")
  public LocalUplaunchRepo configSet_useFileLock(RepoConfig config, boolean val) {
    if (config == null) throw new IllegalArgumentException("config==null");

    config.setUseFileLock(val);

    LocalUplaunchRepo repo = configRepoMap.get(config);
    return repo;
  }

  // TODO doc it
  @Fun(operator = true)
  @Name(name = "commit")
  public LocalUplaunchRepo configCommit(RepoConfig config) {
    if (config == null) throw new IllegalArgumentException("config==null");

    config.commit();

    LocalUplaunchRepo repo = configRepoMap.get(config);
    return repo;
  }
}
Exemplo n.º 21
0
/** @author Kamnev Georgiy ([email protected]) */
public class FileVar {
  // <editor-fold defaultstate="collapsed" desc="log Функции">
  private static final Logger logger = Logger.getLogger(FileVar.class.getName());
  private static final Level logLevel = logger.getLevel();
  private static final boolean isLogSevere =
      logLevel == null ? true : logLevel.intValue() <= Level.SEVERE.intValue();

  private static final boolean isLogWarning =
      logLevel == null ? true : logLevel.intValue() <= Level.WARNING.intValue();

  private static final boolean isLogInfo =
      logLevel == null ? true : logLevel.intValue() <= Level.INFO.intValue();

  private static final boolean isLogFine =
      logLevel == null ? true : logLevel.intValue() <= Level.FINE.intValue();

  private static final boolean isLogFiner =
      logLevel == null ? true : logLevel.intValue() <= Level.FINER.intValue();

  private static final boolean isLogFinest =
      logLevel == null ? true : logLevel.intValue() <= Level.FINEST.intValue();

  private static void logFine(String message, Object... args) {
    logger.log(Level.FINE, message, args);
  }

  private static void logFiner(String message, Object... args) {
    logger.log(Level.FINER, message, args);
  }

  private static void logFinest(String message, Object... args) {
    logger.log(Level.FINEST, message, args);
  }

  private static void logInfo(String message, Object... args) {
    logger.log(Level.INFO, message, args);
  }

  private static void logWarning(String message, Object... args) {
    logger.log(Level.WARNING, message, args);
  }

  private static void logSevere(String message, Object... args) {
    logger.log(Level.SEVERE, message, args);
  }

  private static void logException(Throwable ex) {
    logger.log(Level.SEVERE, null, ex);
  }
  // </editor-fold>

  private final File file;

  public FileVar(File file) {
    if (file == null) throw new IllegalArgumentException("file==null");
    this.file = file;
  }

  public File getFile() {
    return file;
  }

  public FileSystem getFileSystem() {
    return file.getFileSystem();
  }

  public FileVar getParent() {
    File f = file.getParent();
    if (f != null) return new FileVar(f);
    return null;
  }

  public FileVar getChild(String name) {
    File f = file.getChild(name);
    if (f != null) return new FileVar(f);
    return null;
  }

  public FileVar getCanonical() {
    File f = file.getCanonical();
    if (f != null) return new FileVar(f);
    return null;
  }

  public FileVar getAbsolute() {
    File f = file.getAbsolute();
    if (f != null) return new FileVar(f);
    return null;
  }

  public boolean isDirectory() {
    return file.isDirectory();
  }

  public boolean isFile() {
    return file.isFile();
  }

  public boolean isExists() {
    return file.isExists();
  }

  public DateVar getModifyDate() {
    //        return file.getModifyDate();
    return new DateVar(file.getModifyDate());
  }

  public long getLength() {
    return file.getLength();
  }

  public String getSizeRound() {
    return new ByteSize(file.getLength()).toStringRoundMin(2);
  }

  public boolean isReadable() {
    return file.isReadable();
  }

  public boolean isWritable() {
    return file.isWritable();
  }

  public boolean isExecutable() {
    return file.isExecutable();
  }

  public String getName() {
    return file.getName();
  }

  public String getPath() {
    return file.getPath();
  }

  public boolean isAbsolute() {
    return file.isAbsolute();
  }

  public boolean isRoot() {
    return file.isRoot();
  }
}
Exemplo n.º 22
0
 @Override
 public void publish(LogRecord record) {
   String message = getFormatter().format(record);
   if (record.getLevel().intValue() > Level.INFO.intValue()) console.error(message);
   else console.write(message);
 }
Exemplo n.º 23
0
 private static boolean isLogInfo() {
   Level ll = logLevel();
   return ll == null ? true : ll.intValue() <= Level.INFO.intValue();
 }
Exemplo n.º 24
0
/**
 * ******************** A POJO for the provider specific configuration of a cloud driver.
 *
 * @author barakme
 * @since 2.0.0
 */
@CloudifyDSLEntity(
    name = "provider",
    clazz = CloudProvider.class,
    allowInternalNode = true,
    allowRootNode = false,
    parent = "cloud")
public class CloudProvider {

  private String provider;
  private String localDirectory;
  private String remoteDirectory;
  private String cloudifyUrl;

  // location of zip file where additional cloudify files are places.
  // They will be copied on top of the cloudify distribution.
  private String cloudifyOverridesUrl;

  private String machineNamePrefix;

  private boolean dedicatedManagementMachines = true;

  private List<String> managementOnlyFiles;

  private String sshLoggingLevel = Level.INFO.toString();

  private List<String> zones = Arrays.asList("agent");

  private String managementGroup;
  private int numberOfManagementMachines;
  private int reservedMemoryCapacityPerMachineInMB;

  public String getProvider() {
    return provider;
  }

  public void setProvider(final String provider) {
    this.provider = provider;
  }

  public String getLocalDirectory() {
    return localDirectory;
  }

  public void setLocalDirectory(final String localDirectory) {
    this.localDirectory = localDirectory;
  }

  /**
   * ****
   *
   * @deprecated use CloudTemplate.getRemoteDirectory instead.
   * @return .
   */
  public String getRemoteDirectory() {
    return remoteDirectory;
  }

  /**
   * ****
   *
   * @param remoteDirectory .
   * @deprecated use CloudTemplate.setRemoteDirectory instead.
   */
  public void setRemoteDirectory(final String remoteDirectory) {
    this.remoteDirectory = remoteDirectory;
  }

  public String getCloudifyUrl() {
    return cloudifyUrl;
  }

  public void setCloudifyUrl(final String cloudifyUrl) {
    this.cloudifyUrl = cloudifyUrl;
  }

  public String getMachineNamePrefix() {
    return machineNamePrefix;
  }

  public void setMachineNamePrefix(final String machineNamePrefix) {
    this.machineNamePrefix = machineNamePrefix;
  }

  public boolean isDedicatedManagementMachines() {
    return dedicatedManagementMachines;
  }

  public void setDedicatedManagementMachines(final boolean dedicatedManagementMachines) {
    this.dedicatedManagementMachines = dedicatedManagementMachines;
  }

  public List<String> getManagementOnlyFiles() {
    return managementOnlyFiles;
  }

  public void setManagementOnlyFiles(final List<String> managementOnlyFiles) {
    this.managementOnlyFiles = managementOnlyFiles;
  }

  public String getSshLoggingLevel() {
    return sshLoggingLevel;
  }

  public void setSshLoggingLevel(final String sshLoggingLevel) {
    this.sshLoggingLevel = sshLoggingLevel;
  }

  public List<String> getZones() {
    return zones;
  }

  public void setZones(final List<String> zones) {
    this.zones = zones;
  }

  // TODO - move to configuration
  public String getManagementGroup() {
    return managementGroup;
  }

  public void setManagementGroup(final String managementGroup) {
    this.managementGroup = managementGroup;
  }

  // TODO - move to configuration
  public int getNumberOfManagementMachines() {
    return numberOfManagementMachines;
  }

  public void setNumberOfManagementMachines(final int numberOfManagementMachines) {
    this.numberOfManagementMachines = numberOfManagementMachines;
  }

  public int getReservedMemoryCapacityPerMachineInMB() {
    return reservedMemoryCapacityPerMachineInMB;
  }

  public void setReservedMemoryCapacityPerMachineInMB(
      final int reservedMemoryCapacityPerMachineInMB) {
    this.reservedMemoryCapacityPerMachineInMB = reservedMemoryCapacityPerMachineInMB;
  }

  @Override
  public String toString() {
    return "CloudProvider [provider="
        + provider
        + ", localDirectory="
        + localDirectory
        + ", remoteDirectory="
        + remoteDirectory
        + ", cloudifyUrl="
        + cloudifyUrl
        + ", machineNamePrefix="
        + machineNamePrefix
        + ", dedicatedManagementMachines="
        + dedicatedManagementMachines
        + ", managementOnlyFiles="
        + managementOnlyFiles
        + ",  sshLoggingLevel="
        + sshLoggingLevel
        + ", zones="
        + zones
        + ", managementGroup="
        + managementGroup
        + ", numberOfManagementMachines="
        + numberOfManagementMachines
        + ", reservedMemoryCapacityPerMachineInMB="
        + reservedMemoryCapacityPerMachineInMB
        + "]";
  }

  public String getCloudifyOverridesUrl() {
    return cloudifyOverridesUrl;
  }

  public void setCloudifyOverridesUrl(final String cloudifyOverridesUrl) {
    this.cloudifyOverridesUrl = cloudifyOverridesUrl;
  }
}
Exemplo n.º 25
0
public class Jul2Slf4jHandler extends Handler {

  private static final String FQCN = java.util.logging.Logger.class.getName();
  private static final String UNKNOWN_LOGGER_NAME = "unknown.jul.logger";

  private static final int TRACE_LEVEL_THRESHOLD = Level.FINEST.intValue();
  private static final int DEBUG_LEVEL_THRESHOLD = Level.FINE.intValue();
  private static final int INFO_LEVEL_THRESHOLD = Level.INFO.intValue();
  private static final int WARN_LEVEL_THRESHOLD = Level.WARNING.intValue();

  @Nullable private final ILoggerFactory _loggerFactory;

  public Jul2Slf4jHandler() {
    this(null);
  }

  public Jul2Slf4jHandler(@Nullable ILoggerFactory loggerFactory) {
    _loggerFactory = loggerFactory;
  }

  @Override
  public void close() {}

  @Override
  public void flush() {}

  @Nullable
  protected Logger getSLF4JLogger(@Nonnull LogRecord record) {
    final String name = record.getLoggerName();
    return logger(name != null ? name : UNKNOWN_LOGGER_NAME);
  }

  protected void callLocationAwareLogger(LocationAwareLogger lal, LogRecord record) {
    final int julLevelValue = record.getLevel().intValue();
    final int slf4jLevel;
    if (julLevelValue <= TRACE_LEVEL_THRESHOLD) {
      slf4jLevel = LocationAwareLogger.TRACE_INT;
    } else if (julLevelValue <= DEBUG_LEVEL_THRESHOLD) {
      slf4jLevel = LocationAwareLogger.DEBUG_INT;
    } else if (julLevelValue <= INFO_LEVEL_THRESHOLD) {
      slf4jLevel = LocationAwareLogger.INFO_INT;
    } else if (julLevelValue <= WARN_LEVEL_THRESHOLD) {
      slf4jLevel = LocationAwareLogger.WARN_INT;
    } else {
      slf4jLevel = LocationAwareLogger.ERROR_INT;
    }
    final String i18nMessage = getMessageI18N(record);
    lal.log(null, FQCN, slf4jLevel, i18nMessage, null, record.getThrown());
  }

  protected void callPlainSLF4JLogger(@Nonnull Logger slf4jLogger, LogRecord record) {
    final String i18nMessage = getMessageI18N(record);
    final int julLevelValue = record.getLevel().intValue();
    if (julLevelValue <= TRACE_LEVEL_THRESHOLD) {
      slf4jLogger.trace(i18nMessage, record.getThrown());
    } else if (julLevelValue <= DEBUG_LEVEL_THRESHOLD) {
      slf4jLogger.debug(i18nMessage, record.getThrown());
    } else if (julLevelValue <= INFO_LEVEL_THRESHOLD) {
      slf4jLogger.info(i18nMessage, record.getThrown());
    } else if (julLevelValue <= WARN_LEVEL_THRESHOLD) {
      slf4jLogger.warn(i18nMessage, record.getThrown());
    } else {
      slf4jLogger.error(i18nMessage, record.getThrown());
    }
  }

  @Nullable
  protected String getMessageI18N(@Nonnull LogRecord record) {
    String message = record.getMessage();
    if (message != null) {
      final ResourceBundle bundle = record.getResourceBundle();
      if (bundle != null) {
        try {
          message = bundle.getString(message);
        } catch (final MissingResourceException ignored) {
        }
      }
      final Object[] params = record.getParameters();
      if (params != null && params.length > 0) {
        message = MessageFormat.format(message, params);
      }
    }
    return message;
  }

  @Override
  public void publish(@Nullable LogRecord record) {
    if (record != null) {
      final Logger slf4jLogger = getSLF4JLogger(record);
      if (slf4jLogger instanceof LocationAwareLogger) {
        callLocationAwareLogger((LocationAwareLogger) slf4jLogger, record);
      } else {
        callPlainSLF4JLogger(slf4jLogger, record);
      }
    }
  }

  @Nonnull
  protected Logger logger(@Nonnull String name) {
    return _loggerFactory != null ? _loggerFactory.getLogger(name) : LoggerFactory.getLogger(name);
  }
}
Exemplo n.º 26
0
/** @author Kamnev Georgiy ([email protected]) */
public class ReadedCachedIndex extends HttpRepoEvent {
  // <editor-fold defaultstate="collapsed" desc="log Функции">
  private static final Logger logger = Logger.getLogger(ReadedCachedIndex.class.getName());
  private static final Level logLevel = logger.getLevel();

  private static final boolean isLogSevere =
      logLevel == null ? true : logLevel.intValue() <= Level.SEVERE.intValue();

  private static final boolean isLogWarning =
      logLevel == null ? true : logLevel.intValue() <= Level.WARNING.intValue();

  private static final boolean isLogInfo =
      logLevel == null ? true : logLevel.intValue() <= Level.INFO.intValue();

  private static final boolean isLogFine =
      logLevel == null ? true : logLevel.intValue() <= Level.FINE.intValue();

  private static final boolean isLogFiner =
      logLevel == null ? true : logLevel.intValue() <= Level.FINER.intValue();

  private static final boolean isLogFinest =
      logLevel == null ? true : logLevel.intValue() <= Level.FINEST.intValue();

  private static void logFine(String message, Object... args) {
    logger.log(Level.FINE, message, args);
  }

  private static void logFiner(String message, Object... args) {
    logger.log(Level.FINER, message, args);
  }

  private static void logFinest(String message, Object... args) {
    logger.log(Level.FINEST, message, args);
  }

  private static void logInfo(String message, Object... args) {
    logger.log(Level.INFO, message, args);
  }

  private static void logWarning(String message, Object... args) {
    logger.log(Level.WARNING, message, args);
  }

  private static void logSevere(String message, Object... args) {
    logger.log(Level.SEVERE, message, args);
  }

  private static void logException(Throwable ex) {
    logger.log(Level.SEVERE, null, ex);
  }
  // </editor-fold>

  private HttpRepo.CachedRepoIndex cachedRepoIndex;
  private RepoIndex index;

  public ReadedCachedIndex(
      HttpRepo repo, HttpRepo.CachedRepoIndex cachedRepoIndex, RepoIndex index) {
    super(repo);
    this.cachedRepoIndex = cachedRepoIndex;
    this.index = index;
  }

  public HttpRepo.CachedRepoIndex getCachedRepoIndex() {
    return cachedRepoIndex;
  }

  public RepoIndex getIndex() {
    return index;
  }
}
Exemplo n.º 27
0
/** @author Kamnev Georgiy ([email protected]) */
public class AddArgument implements Argument {
  // <editor-fold defaultstate="collapsed" desc="log Функции">
  private static final Logger logger = Logger.getLogger(AddArgument.class.getName());
  private static final Level logLevel = logger.getLevel();
  private static final boolean isLogSevere =
      logLevel == null ? true : logLevel.intValue() <= Level.SEVERE.intValue();

  private static final boolean isLogWarning =
      logLevel == null ? true : logLevel.intValue() <= Level.WARNING.intValue();

  private static final boolean isLogInfo =
      logLevel == null ? true : logLevel.intValue() <= Level.INFO.intValue();

  private static final boolean isLogFine =
      logLevel == null ? true : logLevel.intValue() <= Level.FINE.intValue();

  private static final boolean isLogFiner =
      logLevel == null ? true : logLevel.intValue() <= Level.FINER.intValue();

  private static final boolean isLogFinest =
      logLevel == null ? true : logLevel.intValue() <= Level.FINEST.intValue();

  private static void logFine(String message, Object... args) {
    logger.log(Level.FINE, message, args);
  }

  private static void logFiner(String message, Object... args) {
    logger.log(Level.FINER, message, args);
  }

  private static void logFinest(String message, Object... args) {
    logger.log(Level.FINEST, message, args);
  }

  private static void logInfo(String message, Object... args) {
    logger.log(Level.INFO, message, args);
  }

  private static void logWarning(String message, Object... args) {
    logger.log(Level.WARNING, message, args);
  }

  private static void logSevere(String message, Object... args) {
    logger.log(Level.SEVERE, message, args);
  }

  private static void logException(Throwable ex) {
    logger.log(Level.SEVERE, null, ex);
  }
  // </editor-fold>

  public AddArgument() {}

  public AddArgument(String value) {
    this.value = value;
  }

  public AddArgument(int index, String value) {
    this.value = value;
    this.index = index;
  }

  private final Lock lock = new ReentrantLock();

  private String value;

  public String getValue() {
    try {
      lock.lock();
      return value;
    } finally {
      lock.unlock();
    }
  }

  public void setValue(String value) {
    try {
      lock.lock();
      this.value = value;
    } finally {
      lock.unlock();
    }
  }

  private int index = -1;

  public int getIndex() {
    try {
      lock.lock();
      return index;
    } finally {
      lock.unlock();
    }
  }

  public void setIndex(int index) {
    try {
      lock.lock();
      this.index = index;
    } finally {
      lock.unlock();
    }
  }

  @Override
  public List<String> build(List<String> args) {
    try {
      lock.lock();
      List<String> res = new ArrayList<String>();
      if (args != null) {
        res.addAll(args);
      }

      if (value != null && res != null) {
        if (index >= 0) {
          if (index >= res.size()) {
            res.add(value);
          } else {
            res.add(index, value);
          }
        } else {
          res.add(value);
        }
      }
      return res;
    } finally {
      lock.unlock();
    }
  }
}
Exemplo n.º 28
0
/** @author [email protected] */
public abstract class UnaryAst extends Ast {
  // <editor-fold defaultstate="collapsed" desc="log Функции">
  private static final Logger logger = Logger.getLogger(UnaryAst.class.getName());
  private static final Level logLevel = logger.getLevel();

  private static final boolean isLogSevere =
      logLevel == null ? true : logLevel.intValue() <= Level.SEVERE.intValue();

  private static final boolean isLogWarning =
      logLevel == null ? true : logLevel.intValue() <= Level.WARNING.intValue();

  private static final boolean isLogInfo =
      logLevel == null ? true : logLevel.intValue() <= Level.INFO.intValue();

  private static final boolean isLogFine =
      logLevel == null ? true : logLevel.intValue() <= Level.FINE.intValue();

  private static final boolean isLogFiner =
      logLevel == null ? true : logLevel.intValue() <= Level.FINER.intValue();

  private static final boolean isLogFinest =
      logLevel == null ? true : logLevel.intValue() <= Level.FINEST.intValue();

  private static void logFine(String message, Object... args) {
    logger.log(Level.FINE, message, args);
  }

  private static void logFiner(String message, Object... args) {
    logger.log(Level.FINER, message, args);
  }

  private static void logFinest(String message, Object... args) {
    logger.log(Level.FINEST, message, args);
  }

  private static void logInfo(String message, Object... args) {
    logger.log(Level.INFO, message, args);
  }

  private static void logWarning(String message, Object... args) {
    logger.log(Level.WARNING, message, args);
  }

  private static void logSevere(String message, Object... args) {
    logger.log(Level.SEVERE, message, args);
  }

  private static void logException(Throwable ex) {
    logger.log(Level.SEVERE, null, ex);
  }

  private static void logEntering(String method, Object... params) {
    logger.entering(UnaryAst.class.getName(), method, params);
  }

  private static void logExiting(String method) {
    logger.exiting(UnaryAst.class.getName(), method);
  }

  private static void logExiting(String method, Object result) {
    logger.exiting(UnaryAst.class.getName(), method, result);
  }
  // </editor-fold>

  protected Ast leaf;

  public synchronized Ast getLeaf() {
    return leaf;
  }

  public synchronized void setLeaf(Ast leaf) {
    this.leaf = leaf;
  }

  @Override
  public synchronized Ast[] getChildren() {
    if (leaf != null) return new Ast[] {leaf};
    return new Ast[] {};
  }
}
Exemplo n.º 29
0
/** @author Kamnev Georgiy ([email protected]) */
public class FunctionSetHelper {
  // <editor-fold defaultstate="collapsed" desc="log Функции">
  private static final Logger logger = Logger.getLogger(FunctionSetHelper.class.getName());
  private static final Level logLevel = logger.getLevel();

  private static final boolean isLogSevere =
      logLevel == null ? true : logLevel.intValue() <= Level.SEVERE.intValue();

  private static final boolean isLogWarning =
      logLevel == null ? true : logLevel.intValue() <= Level.WARNING.intValue();

  private static final boolean isLogInfo =
      logLevel == null ? true : logLevel.intValue() <= Level.INFO.intValue();

  private static final boolean isLogFine =
      logLevel == null ? true : logLevel.intValue() <= Level.FINE.intValue();

  private static final boolean isLogFiner =
      logLevel == null ? true : logLevel.intValue() <= Level.FINER.intValue();

  private static final boolean isLogFinest =
      logLevel == null ? true : logLevel.intValue() <= Level.FINEST.intValue();

  private static void logFine(String message, Object... args) {
    logger.log(Level.FINE, message, args);
  }

  private static void logFiner(String message, Object... args) {
    logger.log(Level.FINER, message, args);
  }

  private static void logFinest(String message, Object... args) {
    logger.log(Level.FINEST, message, args);
  }

  private static void logInfo(String message, Object... args) {
    logger.log(Level.INFO, message, args);
  }

  private static void logWarning(String message, Object... args) {
    logger.log(Level.WARNING, message, args);
  }

  private static void logSevere(String message, Object... args) {
    logger.log(Level.SEVERE, message, args);
  }

  private static void logException(Throwable ex) {
    logger.log(Level.SEVERE, null, ex);
  }
  // </editor-fold>

  private Iterable<Function> funitr;
  private FunctionSet fset;
  private Memory mem;

  public FunctionSetHelper(final Memory mem) {
    if (mem == null) throw new IllegalArgumentException("mem==null");
    this.mem = mem;
    this.funitr =
        new Iterable<Function>() {
          @Override
          public Iterator<Function> iterator() {
            List<Function> l = new ArrayList<Function>();
            for (Object o : mem.values()) {
              if (o instanceof Function) {
                l.add((Function) o);
              } else if (o instanceof FunctionSet) {
                for (Function f : ((FunctionSet) o).getFunctions()) {
                  l.add(f);
                }
              }
            }
            return l.iterator();
          }
        };
  }

  public FunctionSetHelper(Iterable<Function> funitr) {
    if (funitr == null) throw new IllegalArgumentException("funitr==null");
    this.funitr = funitr;
  }

  public FunctionSetHelper(Map<String, Set<Function>> map) {
    if (map == null) throw new IllegalArgumentException("map==null");
    final Map<String, Set<Function>> mp = map;
    this.funitr =
        new Iterable<Function>() {
          @Override
          public Iterator<Function> iterator() {
            List<Function> lfun = new ArrayList<Function>();
            for (Map.Entry<String, Set<Function>> en : mp.entrySet()) {
              lfun.addAll(en.getValue());
            }
            return lfun.iterator();
          }
        };
  }

  public FunctionSetHelper(FunctionSet fset) {
    this.fset = fset;
  }

  public Function first() {
    for (Function f : functions()) {
      return f;
    }
    return null;
  }

  // <editor-fold defaultstate="collapsed" desc="print()">
  public FunctionSetHelper print() {
    OutputStreamWriter w = new OutputStreamWriter(System.out);
    print(w);
    try {
      w.flush();
    } catch (IOException ex) {
      Logger.getLogger(FunctionSetHelper.class.getName()).log(Level.SEVERE, null, ex);
    }

    return this;
  }

  public FunctionSetHelper print(Writer w) {
    if (w == null) throw new IllegalArgumentException("w==null");

    SourceDump sdump = new SourceDump();
    int i = -1;
    for (Function f : functions()) {
      try {
        i++;
        //                String decl = f==null ? "null" : sdump.getDeclareOf(f);

        w.write(Integer.toString(i));
        w.write(". ");
        //                w.write(decl);
        w.write("\n");
      } catch (IOException ex) {
        Logger.getLogger(FunctionSetHelper.class.getName()).log(Level.SEVERE, null, ex);
      }
    }

    return this;
  }
  // </editor-fold>

  // <editor-fold defaultstate="collapsed" desc="functions()">
  public Iterable<Function> functions() {
    if (fset != null) return fset.getFunctions();
    if (funitr != null) return funitr;
    return Iterators.empty();
  }
  // </editor-fold>

  // <editor-fold defaultstate="collapsed" desc="filter">
  public Iterable<Function> filter(Iterable<Function> src, Predicate<Function> f) {
    if (src == null) throw new IllegalArgumentException("src==null");
    if (f == null) throw new IllegalArgumentException("f==null");
    return Iterators.predicate(src, f);
  }
  // </editor-fold>

  // <editor-fold defaultstate="collapsed" desc="argumentsCount">
  public Predicate<Function> argumentsCountFilter(final Predicate<Integer> countPred) {
    if (countPred == null) throw new IllegalArgumentException("countPred==null");
    return new Predicate<Function>() {
      @Override
      public boolean validate(Function t) {
        if (t == null) return false;
        return countPred.validate(t.getParameters().length);
      }
    };
  }

  public Predicate<Function> argumentsCountFilter(final int count) {
    return argumentsCountFilter(
        new Predicate<Integer>() {
          @Override
          public boolean validate(Integer t) {
            return count == t;
          }
        });
  }

  public FunctionSetHelper argumentsCount(int count) {
    return new FunctionSetHelper(filter(functions(), argumentsCountFilter(count)));
  }
  // </editor-fold>

  // <editor-fold defaultstate="collapsed" desc="assignFromFilter()">
  public Predicate<Class> assignFromFilter(final Class type) {
    if (type == null) throw new IllegalArgumentException("type==null");
    return new Predicate<Class>() {
      @Override
      public boolean validate(Class t) {
        if (t == null) return false;
        return t.isAssignableFrom(type);
      }
    };
  }

  public Predicate<Class> assignFromFilter2(final Class type) {
    if (type == null) throw new IllegalArgumentException("type==null");
    return new Predicate<Class>() {
      @Override
      public boolean validate(Class t) {
        if (t == null) return false;
        return type.isAssignableFrom(t);
      }
    };
  }
  // </editor-fold>

  // <editor-fold defaultstate="collapsed" desc="functionArguments()">
  public Predicate<Function> functionArgumentsFilter(final Predicate<Class>... argTypes) {
    if (argTypes == null) throw new IllegalArgumentException("argTypes==null");
    for (int ai = 0; ai < argTypes.length; ai++) {
      if (argTypes[ai] == null) throw new IllegalArgumentException("argTypes[" + ai + "]==null");
    }

    return new Predicate<Function>() {
      @Override
      public boolean validate(Function f) {
        if (f == null) return false;
        Class[] params = f.getParameters();
        if (params.length != argTypes.length) return false;
        for (int i = 0; i < params.length; i++) {
          boolean m = argTypes[i].validate(params[i]);
          if (!m) return false;
        }
        return true;
      }
    };
  }

  public FunctionSetHelper functionArguments(final Predicate<Class>... argTypes) {
    return new FunctionSetHelper(filter(functions(), functionArgumentsFilter(argTypes)));
  }
  // </editor-fold>

  // <editor-fold defaultstate="collapsed" desc="functionArgument()">
  public Predicate<Function> functionArgumentFilter(
      final int argumentIndex, final Predicate<Class> argType) {
    if (argType == null) throw new IllegalArgumentException("argType==null");
    return new Predicate<Function>() {
      @Override
      public boolean validate(Function f) {
        if (f == null) return false;
        Class[] params = f.getParameters();
        if (argumentIndex >= params.length || argumentIndex < 0) return false;
        return argType.validate(params[argumentIndex]);
      }
    };
  }

  public FunctionSetHelper functionArgument(
      final int argumentIndex, final Predicate<Class> argType) {
    return new FunctionSetHelper(
        filter(functions(), functionArgumentFilter(argumentIndex, argType)));
  }
  // </editor-fold>

  // <editor-fold defaultstate="collapsed" desc="named()">
  public FunctionSetHelper named(final String name) {
    if (name == null) throw new IllegalArgumentException("name==null");
    if (mem == null) return new FunctionSetHelper(Iterators.<Function>empty());

    Object o = mem.get(name);
    if (o instanceof Function) {
      FunctionSetHelper fs = new FunctionSetHelper(Iterators.<Function>single((Function) o));
      fs.mem = mem;
      return fs;
    }

    if (o instanceof FunctionSet) {
      FunctionSetHelper fs = new FunctionSetHelper(((FunctionSet) o).getFunctions());
      fs.mem = mem;
      return fs;
    }

    return new FunctionSetHelper(Iterators.<Function>empty());
  }
  // </editor-fold>

  // <editor-fold defaultstate="collapsed" desc="operators()">
  public Predicate<Function> operatorFilter() {
    return new Predicate<Function>() {
      @Override
      public boolean validate(Function f) {
        if (f == null) return false;
        if (f instanceof IsOperator) {
          return ((IsOperator) f).isOperator();
        }
        return false;
      }
    };
  }

  public FunctionSetHelper operators() {
    return new FunctionSetHelper(filter(functions(), operatorFilter()));
  }
  // </editor-fold>

  // <editor-fold defaultstate="collapsed" desc="count()">
  public int count() {
    Iterable<Function> itrf = functions();
    long c = Iterators.count(itrf);

    return new Long(c).intValue();
  }
  // </editor-fold>

  public Predicate<Function> in(final Iterable<Function> src) {
    if (src == null) throw new IllegalArgumentException("src==null");
    return new Predicate<Function>() {
      @Override
      public boolean validate(Function f) {
        if (f == null) return false;
        return Iterators.in(f, src);
      }
    };
  }

  public Predicate<Function> not(final Predicate<Function> src) {
    if (src == null) throw new IllegalArgumentException("src==null");
    return new Predicate<Function>() {
      @Override
      public boolean validate(Function f) {
        if (f == null) return false;
        return !src.validate(f);
      }
    };
  }

  public Predicate<Function> and(final Predicate<Function>... src) {
    if (src == null) throw new IllegalArgumentException("src==null");
    return new Predicate<Function>() {
      @Override
      public boolean validate(Function f) {
        if (src == null) return false;
        if (src.length == 0) return false;
        for (Predicate<Function> p : src) {
          if (!p.validate(f)) return false;
        }
        return true;
      }
    };
  }

  public Predicate<Function> or(final Predicate<Function>... src) {
    if (src == null) throw new IllegalArgumentException("src==null");
    return new Predicate<Function>() {
      @Override
      public boolean validate(Function f) {
        if (src == null) return false;
        if (src.length == 0) return false;
        for (Predicate<Function> p : src) {
          if (p.validate(f)) return true;
        }
        return false;
      }
    };
  }
}
Exemplo n.º 30
0
public class ReportPreferencePage extends FieldEditorPreferencePage
    implements IWorkbenchPreferencePage {

  private String[][] logLvlValues =
      new String[][] {
        new String[] {Messages.getString("ReportLogLevel.0"), Level.INFO.toString()},
        new String[] {Messages.getString("ReportLogLevel.1"), Level.WARNING.toString()},
        new String[] {Messages.getString("ReportLogLevel.2"), Level.FINEST.toString()},
        new String[] {Messages.getString("ReportLogLevel.3"), Level.SEVERE.toString()},
        new String[] {Messages.getString("ReportLogLevel.4"), Level.ALL.toString()}
      };
  private DirectoryFieldEditor localTemplateEditor;

  public ReportPreferencePage() {
    super(GRID);
    setDescription(Messages.getString("ReportPreferencePage.0")); // $NON-NLS-1$
  }

  /* (non-Javadoc)
   * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
   */
  @Override
  public void init(IWorkbench arg0) {
    setPreferenceStore(Activator.getDefault().getPreferenceStore());
  }

  /* (non-Javadoc)
   * @see org.eclipse.jface.preference.FieldEditorPreferencePage#createFieldEditors()
   */
  @Override
  protected void createFieldEditors() {

    BooleanFieldEditor reportLoggingEditor =
        new BooleanFieldEditor(
            PreferenceConstants.REPORT_LOGGING_ENABLED,
            Messages.getString("ReportPreferencePage.1"),
            getFieldEditorParent());
    addField(reportLoggingEditor);

    ComboFieldEditor logLvlFieldEditor =
        new ComboFieldEditor(
            PreferenceConstants.REPORT_LOGGING_LVL,
            Messages.getString("ReportPreferencePage.2"),
            logLvlValues,
            getFieldEditorParent());
    addField(logLvlFieldEditor);

    DirectoryFieldEditor logFileNameEditor =
        new DirectoryFieldEditor(
            PreferenceConstants.REPORT_LOG_FILE,
            Messages.getString("ReportPreferencePage.3"),
            getFieldEditorParent());
    addField(logFileNameEditor);

    localTemplateEditor =
        new DirectoryFieldEditor(
            PreferenceConstants.REPORT_LOCAL_TEMPLATE_DIRECTORY,
            Messages.getString("ReportPreferencePage.8"),
            getFieldEditorParent());
    addField(localTemplateEditor);

    BooleanFieldEditor useCacheEditor =
        new BooleanFieldEditor(
            PreferenceConstants.REPORT_USE_CACHE,
            Messages.getString("ReportPreferencePage.7"),
            getFieldEditorParent());
    addField(useCacheEditor);
  }

  @Override
  public void propertyChange(PropertyChangeEvent event) {
    super.propertyChange(event);
    if (event.getProperty().equals(FieldEditor.VALUE)) {
      checkState();
    }

    if (event.getSource() == localTemplateEditor) {
      Activator.getDefault()
          .getIReportTemplateDirectoryService()
          .setDirectory((String) event.getNewValue());
    }
  }

  @Override
  protected void checkState() {
    super.checkState();
    if (!isValid()) {
      return;
    }
  }
}