@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());
    }
Beispiel #2
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
 }
Beispiel #3
0
  // this method is called for every log records
  public String format(LogRecord rec) {
    StringBuffer buf = new StringBuffer(1000);
    buf.append("<tr>\n");

    // colorize any levels >= WARNING in red
    if (rec.getLevel().intValue() >= Level.WARNING.intValue()) {
      buf.append("\t<td style=\"color:red\">");
      buf.append("<b>");
      buf.append(rec.getLevel());
      buf.append("</b>");
    } else {
      buf.append("\t<td>");
      buf.append(rec.getLevel());
    }

    buf.append("</td>\n");
    buf.append("\t<td>");
    buf.append(calcDate(rec.getMillis()));
    buf.append("</td>\n");
    buf.append("\t<td>");
    buf.append(formatMessage(rec));
    buf.append("</td>\n");
    buf.append("</tr>\n");

    return buf.toString();
  }
  public void setLogLevel(Level level) {
    if (getLogLevel().equals(level)) return;

    String strLevel;
    if (Level.SEVERE.equals(level)) strLevel = "severe";
    else if (Level.WARNING.equals(level)) strLevel = "warning";
    else strLevel = "info";
    setProperty("LogLevel", strLevel);
  }
  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;
  }
Beispiel #6
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));
     }
   }
 }
Beispiel #7
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);
 }
 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;
   }
 }
  /**
   * Reconfigures the dialog if settings have changed, such as the errorInfo, errorIcon,
   * warningIcon, etc
   */
  protected void reinit() {
    setDetailsVisible(false);
    Action reportAction = pane.getActionMap().get(JXErrorPane.REPORT_ACTION_KEY);
    reportButton.setAction(reportAction);
    reportButton.setVisible(
        reportAction != null && reportAction.isEnabled() && pane.getErrorReporter() != null);
    reportButton.setEnabled(reportButton.isVisible());
    ErrorInfo errorInfo = pane.getErrorInfo();
    if (errorInfo == null) {
      iconLabel.setIcon(pane.getIcon());
      setErrorMessage("");
      closeButton.setText(
          UIManagerExt.getString(CLASS_NAME + ".ok_button_text", closeButton.getLocale()));
      setDetails("");
      // TODO Does this ever happen? It seems like if errorInfo is null and
      // this is called, it would be an IllegalStateException.
    } else {
      // change the "closeButton"'s text to either the default "ok"/"close" text
      // or to the "fatal" text depending on the error level of the incident info
      if (errorInfo.getErrorLevel() == ErrorLevel.FATAL) {
        closeButton.setText(
            UIManagerExt.getString(CLASS_NAME + ".fatal_button_text", closeButton.getLocale()));
      } else {
        closeButton.setText(
            UIManagerExt.getString(CLASS_NAME + ".ok_button_text", closeButton.getLocale()));
      }

      // if the icon for the pane has not been specified by the developer,
      // then set it to the default icon based on the error level
      Icon icon = pane.getIcon();
      if (icon == null || icon instanceof UIResource) {
        if (errorInfo.getErrorLevel().intValue() <= Level.WARNING.intValue()) {
          icon = getDefaultWarningIcon();
        } else {
          icon = getDefaultErrorIcon();
        }
      }
      iconLabel.setIcon(icon);
      setErrorMessage(errorInfo.getBasicErrorMessage());
      String details = errorInfo.getDetailedErrorMessage();
      if (details == null) {
        details = getDetailsAsHTML(errorInfo);
      }
      setDetails(details);
    }
  }
    @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);
      }
    }
  @Override
  public void publish(LogRecord record) {
    if (getFormatter() == null) {
      setFormatter(new MyFormatter());
    }

    try {
      String message = getFormatter().format(record);
      if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
        System.err.write(message.getBytes());
      } else {
        System.out.write(message.getBytes());
      }
    } catch (Exception exception) {
      reportError(null, exception, ErrorManager.FORMAT_FAILURE);
      return;
    }
  }
 public List<VrNotificationEvent> getEvents() {
   List<VrNotificationEvent> evts =
       VrApp.getBean(VrNotificationSession.class).findAll(CorePlugin.SEND_EXTERNAL_MAIL_QUEUE);
   if (errorsOnly) {
     for (Iterator<VrNotificationEvent> i = evts.iterator(); i.hasNext(); ) {
       VrNotificationEvent v = i.next();
       if (v.getLevel().intValue() < Level.WARNING.intValue()) {
         i.remove();
       }
     }
   }
   Collections.sort(
       evts,
       new Comparator<VrNotificationEvent>() {
         @Override
         public int compare(VrNotificationEvent o1, VrNotificationEvent o2) {
           return o2.getCreationTime().compareTo(o1.getCreationTime());
         }
       });
   return evts;
 }
Beispiel #13
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)));
     }
   }
 }
Beispiel #14
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)));
       }
     }
   }
 }
  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());
  }
Beispiel #16
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());
        }
      }
    }
  // This method is called for every log records
  public String format(LogRecord rec) {
    StringBuffer buf = new StringBuffer(1000);
    // Bold any levels >= WARNING
    buf.append("<tr>");
    buf.append("<td>");

    if (rec.getLevel().intValue() >= Level.WARNING.intValue()) {
      buf.append("<b>");
      buf.append(rec.getLevel());
      buf.append("</b>");
    } else {
      buf.append(rec.getLevel());
    }
    buf.append("</td>");
    buf.append("<td>");
    buf.append(calcDate(rec.getMillis()));
    buf.append(' ');
    buf.append(formatMessage(rec));
    buf.append('\n');
    buf.append("<td>");
    buf.append("</tr>\n");
    return buf.toString();
  }
/** @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;
  }
}
/** @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;
  }
}
 private static boolean isLogWarning() {
   Level ll = logLevel();
   return ll == null ? true : ll.intValue() <= Level.WARNING.intValue();
 }
Beispiel #21
0
  /** Does the work for the main method. */
  public static int runMain(String[] args) {
    String usage =
        new StringBuffer()
            .append("\n   Usage:")
            .append("\n      ")
            .append(HubMonitor.class.getName())
            .append("\n           ")
            .append(" [-help]")
            .append(" [+/-verbose]")
            .append("\n           ")
            .append(" [-auto <secs>]")
            .append(" [-nomsg]")
            .append(" [-nogui]")
            .append("\n           ")
            .append(" [-mtype <pattern>]")
            .append("\n")
            .toString();
    List argList = new ArrayList(Arrays.asList(args));
    int verbAdjust = 0;
    boolean gui = true;
    boolean trackMsgs = true;
    int autoSec = 3;
    Subscriptions subs = new Subscriptions();
    for (Iterator it = argList.iterator(); it.hasNext(); ) {
      String arg = (String) it.next();
      if (arg.startsWith("-auto") && it.hasNext()) {
        it.remove();
        String sauto = (String) it.next();
        it.remove();
        autoSec = Integer.parseInt(sauto);
      } else if (arg.equals("-gui")) {
        it.remove();
        gui = true;
      } else if (arg.equals("-nogui")) {
        it.remove();
        gui = false;
      } else if (arg.equals("-msg")) {
        it.remove();
        trackMsgs = true;
      } else if (arg.equals("-nomsg")) {
        it.remove();
        trackMsgs = false;
      } else if (arg.startsWith("-mtype") && it.hasNext()) {
        it.remove();
        String mpat = (String) it.next();
        it.remove();
        subs.addMType(mpat);
      } else if (arg.startsWith("-v")) {
        it.remove();
        verbAdjust--;
      } else if (arg.startsWith("+v")) {
        it.remove();
        verbAdjust++;
      } else if (arg.startsWith("-h")) {
        it.remove();
        System.out.println(usage);
        return 0;
      } else {
        it.remove();
        System.err.println(usage);
        return 1;
      }
    }
    assert argList.isEmpty();

    // Adjust logging in accordance with verboseness flags.
    int logLevel = Level.WARNING.intValue() + 100 * verbAdjust;
    Logger.getLogger("org.astrogrid.samp").setLevel(Level.parse(Integer.toString(logLevel)));

    // Get profile.
    final ClientProfile profile = DefaultClientProfile.getProfile();

    // Create the HubMonitor.
    final HubMonitor monitor = new HubMonitor(profile, trackMsgs, autoSec);

    // Add a handler for extra MTypes if so requested.
    if (!subs.isEmpty()) {
      final Subscriptions extraSubs = subs;
      HubConnector connector = monitor.getHubConnector();
      final Response dummyResponse = new Response();
      dummyResponse.setStatus(Response.WARNING_STATUS);
      dummyResponse.setResult(new HashMap());
      dummyResponse.setErrInfo(new ErrInfo("Message logged, " + "no other action taken"));
      connector.addMessageHandler(
          new MessageHandler() {
            public Map getSubscriptions() {
              return extraSubs;
            }

            public void receiveNotification(
                HubConnection connection, String senderId, Message msg) {}

            public void receiveCall(
                HubConnection connection, String senderId, String msgId, Message msg)
                throws SampException {
              connection.reply(msgId, dummyResponse);
            }
          });
      connector.declareSubscriptions(connector.computeSubscriptions());
    }

    // Start the gui in a new window.
    final boolean isVisible = gui;
    SwingUtilities.invokeLater(
        new Runnable() {
          public void run() {
            JFrame frame = new JFrame("SAMP HubMonitor");
            frame.getContentPane().add(monitor);
            frame.setIconImage(
                new ImageIcon(Metadata.class.getResource("images/eye.gif")).getImage());
            frame.pack();
            frame.setVisible(isVisible);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          }
        });
    return 0;
  }
  /**
   * Format the given message to XML.
   *
   * @param record the log record to be formatted.
   * @return a formatted log record
   */
  public String format(LogRecord record0) {
    if (!(record0 instanceof TopLinkLogRecord)) {
      return super.format(record0);
    } else {
      TopLinkLogRecord record = (TopLinkLogRecord) record0;

      StringBuffer sb = new StringBuffer(500);
      sb.append("<record>\n");

      if (record.shouldPrintDate()) {
        sb.append("  <date>");
        appendISO8601(sb, record.getMillis());
        sb.append("</date>\n");

        sb.append("  <millis>");
        sb.append(record.getMillis());
        sb.append("</millis>\n");
      }

      sb.append("  <sequence>");
      sb.append(record.getSequenceNumber());
      sb.append("</sequence>\n");

      String name = record.getLoggerName();
      if (name != null) {
        sb.append("  <logger>");
        escape(sb, name);
        sb.append("</logger>\n");
      }

      sb.append("  <level>");
      escape(sb, record.getLevel().toString());
      sb.append("</level>\n");

      if (record.getSourceClassName() != null) {
        sb.append("  <class>");
        escape(sb, record.getSourceClassName());
        sb.append("</class>\n");
      }

      if (record.getSourceMethodName() != null) {
        sb.append("  <method>");
        escape(sb, record.getSourceMethodName());
        sb.append("</method>\n");
      }

      if (record.getSessionString() != null) {
        sb.append("  <session>");
        sb.append(record.getSessionString());
        sb.append("</session>\n");
      }

      if (record.getConnection() != null) {
        sb.append("  <connection>");
        sb.append(String.valueOf(System.identityHashCode(record.getConnection())));
        sb.append("</connection>\n");
      }

      if (record.shouldPrintThread()) {
        sb.append("  <thread>");
        sb.append(record.getThreadID());
        sb.append("</thread>\n");
      }

      if (record.getMessage() != null) {
        // Format the message string and its accompanying parameters.
        String message = formatMessage(record);
        sb.append("  <message>");
        escape(sb, message);
        sb.append("</message>");
        sb.append("\n");
      }

      // If the message is being localized, output the key, resource
      // bundle name, and params.
      ResourceBundle bundle = record.getResourceBundle();
      try {
        if ((bundle != null) && (bundle.getString(record.getMessage()) != null)) {
          sb.append("  <key>");
          escape(sb, record.getMessage());
          sb.append("</key>\n");
          sb.append("  <catalog>");
          escape(sb, record.getResourceBundleName());
          sb.append("</catalog>\n");
          Object[] parameters = record.getParameters();
          for (int i = 0; i < parameters.length; i++) {
            sb.append("  <param>");
            try {
              escape(sb, parameters[i].toString());
            } catch (Exception ex) {
              sb.append("???");
            }
            sb.append("</param>\n");
          }
        }
      } catch (Exception ex) {
        // The message is not in the catalog.  Drop through.
      }

      if (record.getThrown() != null) {
        // Report on the state of the throwable.
        Throwable th = record.getThrown();
        sb.append("  <exception>\n");
        sb.append("    <message>");
        escape(sb, th.toString());
        sb.append("</message>\n");

        if ((record.getLevel().intValue() == Level.SEVERE.intValue())
            || ((record.getLevel().intValue() <= Level.WARNING.intValue())
                && record.shouldLogExceptionStackTrace())) {
          StackTraceElement[] trace = th.getStackTrace();
          for (int i = 0; i < trace.length; i++) {
            StackTraceElement frame = trace[i];
            sb.append("    <frame>\n");
            sb.append("      <class>");
            escape(sb, frame.getClassName());
            sb.append("</class>\n");
            sb.append("      <method>");
            escape(sb, frame.getMethodName());
            sb.append("</method>\n");
            // Check for a line number.
            if (frame.getLineNumber() >= 0) {
              sb.append("      <line>");
              sb.append(frame.getLineNumber());
              sb.append("</line>\n");
            }
            sb.append("    </frame>\n");
          }
        }

        sb.append("  </exception>\n");
      }

      sb.append("</record>\n");
      return sb.toString();
    }
  }
  // I don't really care about unchecked warnings in this class.
  @SuppressWarnings("unchecked")
  private static class Flags {
    private static List<GuardLevel> guardLevels = Lists.newArrayList();

    @Option(name = "--help", handler = BooleanOptionHandler.class, usage = "Displays this message")
    private boolean displayHelp = false;

    @Option(
        name = "--print_tree",
        handler = BooleanOptionHandler.class,
        usage = "Prints out the parse tree and exits")
    private boolean printTree = false;

    @Option(
        name = "--print_ast",
        handler = BooleanOptionHandler.class,
        usage = "Prints a dot file describing the internal abstract syntax" + " tree and exits")
    private boolean printAst = false;

    @Option(
        name = "--print_pass_graph",
        handler = BooleanOptionHandler.class,
        usage = "Prints a dot file describing the passes that will get run" + " and exits")
    private boolean printPassGraph = false;

    // Turn on (very slow) extra sanity checks for use when modifying the
    // compiler.
    @Option(
        name = "--jscomp_dev_mode",
        // hidden, no usage
        aliases = {"--dev_mode"})
    private CompilerOptions.DevMode jscompDevMode = CompilerOptions.DevMode.OFF;

    @Option(
        name = "--logging_level",
        usage =
            "The logging level (standard java.util.logging.Level"
                + " values) for Compiler progress. Does not control errors or"
                + " warnings for the JavaScript code under compilation")
    private String loggingLevel = Level.WARNING.getName();

    @Option(
        name = "--externs",
        usage = "The file containing JavaScript externs. You may specify" + " multiple")
    private List<String> externs = Lists.newArrayList();

    @Option(name = "--js", usage = "The JavaScript filename. You may specify multiple")
    private List<String> js = Lists.newArrayList();

    @Option(
        name = "--js_output_file",
        usage = "Primary output filename. If not specified, output is " + "written to stdout")
    private String jsOutputFile = "";

    @Option(
        name = "--module",
        usage =
            "A JavaScript module specification. The format is "
                + "<name>:<num-js-files>[:[<dep>,...][:]]]. Module names must be "
                + "unique. Each dep is the name of a module that this module "
                + "depends on. Modules must be listed in dependency order, and JS "
                + "source files must be listed in the corresponding order. Where "
                + "--module flags occur in relation to --js flags is unimportant. "
                + "Provide the value 'auto' to trigger module creation from CommonJS"
                + "modules.")
    private List<String> module = Lists.newArrayList();

    @Option(
        name = "--variable_map_input_file",
        usage =
            "File containing the serialized version of the variable "
                + "renaming map produced by a previous compilation")
    private String variableMapInputFile = "";

    @Option(
        name = "--property_map_input_file",
        usage =
            "File containing the serialized version of the property "
                + "renaming map produced by a previous compilation")
    private String propertyMapInputFile = "";

    @Option(
        name = "--variable_map_output_file",
        usage =
            "File where the serialized version of the variable "
                + "renaming map produced should be saved")
    private String variableMapOutputFile = "";

    @Option(
        name = "--create_name_map_files",
        handler = BooleanOptionHandler.class,
        usage =
            "If true, variable renaming and property renaming map "
                + "files will be produced as {binary name}_vars_map.out and "
                + "{binary name}_props_map.out. Note that this flag cannot be used "
                + "in conjunction with either variableMapOutputFile or "
                + "property_map_output_file")
    private boolean createNameMapFiles = false;

    @Option(
        name = "--property_map_output_file",
        usage =
            "File where the serialized version of the property "
                + "renaming map produced should be saved")
    private String propertyMapOutputFile = "";

    @Option(
        name = "--third_party",
        handler = BooleanOptionHandler.class,
        usage = "Check source validity but do not enforce Closure style " + "rules and conventions")
    private boolean thirdParty = false;

    @Option(
        name = "--summary_detail_level",
        usage =
            "Controls how detailed the compilation summary is. Values:"
                + " 0 (never print summary), 1 (print summary only if there are "
                + "errors or warnings), 2 (print summary if the 'checkTypes' "
                + "diagnostic  group is enabled, see --jscomp_warning), "
                + "3 (always print summary). The default level is 1")
    private int summaryDetailLevel = 1;

    @Option(
        name = "--output_wrapper",
        usage =
            "Interpolate output into this string at the place denoted"
                + " by the marker token %output%. Use marker token %output|jsstring%"
                + " to do js string escaping on the output.")
    private String outputWrapper = "";

    @Option(
        name = "--module_wrapper",
        usage =
            "An output wrapper for a JavaScript module (optional). "
                + "The format is <name>:<wrapper>. The module name must correspond "
                + "with a module specified using --module. The wrapper must "
                + "contain %s as the code placeholder. The %basename% placeholder can "
                + "also be used to substitute the base name of the module output file.")
    private List<String> moduleWrapper = Lists.newArrayList();

    @Option(
        name = "--module_output_path_prefix",
        usage =
            "Prefix for filenames of compiled JS modules. "
                + "<module-name>.js will be appended to this prefix. Directories "
                + "will be created as needed. Use with --module")
    private String moduleOutputPathPrefix = "./";

    @Option(
        name = "--create_source_map",
        usage =
            "If specified, a source map file mapping the generated "
                + "source files back to the original source file will be "
                + "output to the specified path. The %outname% placeholder will "
                + "expand to the name of the output file that the source map "
                + "corresponds to.")
    private String createSourceMap = "";

    @Option(
        name = "--source_map_format",
        usage =
            "The source map format to produce. "
                + "Options: V1, V2, V3, DEFAULT. DEFAULT produces V2.")
    private SourceMap.Format sourceMapFormat = SourceMap.Format.DEFAULT;

    // Used to define the flag, values are stored by the handler.
    @SuppressWarnings("unused")
    @Option(
        name = "--jscomp_error",
        handler = WarningGuardErrorOptionHandler.class,
        usage =
            "Make the named class of warnings an error. Options:"
                + DiagnosticGroups.DIAGNOSTIC_GROUP_NAMES)
    private List<String> jscompError = Lists.newArrayList();

    // Used to define the flag, values are stored by the handler.
    @SuppressWarnings("unused")
    @Option(
        name = "--jscomp_warning",
        handler = WarningGuardWarningOptionHandler.class,
        usage =
            "Make the named class of warnings a normal warning. "
                + "Options:"
                + DiagnosticGroups.DIAGNOSTIC_GROUP_NAMES)
    private List<String> jscompWarning = Lists.newArrayList();

    // Used to define the flag, values are stored by the handler.
    @SuppressWarnings("unused")
    @Option(
        name = "--jscomp_off",
        handler = WarningGuardOffOptionHandler.class,
        usage =
            "Turn off the named class of warnings. Options:"
                + DiagnosticGroups.DIAGNOSTIC_GROUP_NAMES)
    private List<String> jscompOff = Lists.newArrayList();

    @Option(
        name = "--define",
        aliases = {"--D", "-D"},
        usage =
            "Override the value of a variable annotated @define. "
                + "The format is <name>[=<val>], where <name> is the name of a @define "
                + "variable and <val> is a boolean, number, or a single-quoted string "
                + "that contains no single quotes. If [=<val>] is omitted, "
                + "the variable is marked true")
    private List<String> define = Lists.newArrayList();

    @Option(
        name = "--charset",
        usage =
            "Input and output charset for all files. By default, we "
                + "accept UTF-8 as input and output US_ASCII")
    private String charset = "";

    @Option(
        name = "--compilation_level",
        usage =
            "Specifies the compilation level to use. Options: "
                + "WHITESPACE_ONLY, SIMPLE_OPTIMIZATIONS, ADVANCED_OPTIMIZATIONS")
    private CompilationLevel compilationLevel = CompilationLevel.SIMPLE_OPTIMIZATIONS;

    @Option(
        name = "--use_types_for_optimization",
        usage =
            "Experimental: perform additional optimizations "
                + "based on available information.  Inaccurate type annotations "
                + "may result in incorrect results.")
    private boolean useTypesForOptimization = false;

    @Option(
        name = "--warning_level",
        usage = "Specifies the warning level to use. Options: " + "QUIET, DEFAULT, VERBOSE")
    private WarningLevel warningLevel = WarningLevel.DEFAULT;

    @Option(
        name = "--use_only_custom_externs",
        handler = BooleanOptionHandler.class,
        usage = "Specifies whether the default externs should be excluded")
    private boolean useOnlyCustomExterns = false;

    @Option(
        name = "--debug",
        handler = BooleanOptionHandler.class,
        usage = "Enable debugging options")
    private boolean debug = false;

    @Option(
        name = "--generate_exports",
        handler = BooleanOptionHandler.class,
        usage = "Generates export code for those marked with @export")
    private boolean generateExports = false;

    @Option(
        name = "--formatting",
        usage =
            "Specifies which formatting options, if any, should be "
                + "applied to the output JS. Options: "
                + "PRETTY_PRINT, PRINT_INPUT_DELIMITER, SINGLE_QUOTES")
    private List<FormattingOption> formatting = Lists.newArrayList();

    @Option(
        name = "--process_common_js_modules",
        usage = "Process CommonJS modules to a concatenable form.")
    private boolean processCommonJsModules = false;

    @Option(
        name = "--common_js_module_path_prefix",
        usage = "Path prefix to be removed from CommonJS module names.")
    private String commonJsPathPrefix = ProcessCommonJSModules.DEFAULT_FILENAME_PREFIX;

    @Option(
        name = "--common_js_entry_module",
        usage = "Root of your common JS dependency hierarchy. " + "Your main script.")
    private String commonJsEntryModule;

    @Option(name = "--transform_amd_modules", usage = "Transform AMD to CommonJS modules.")
    private boolean transformAmdModules = false;

    @Option(
        name = "--process_closure_primitives",
        handler = BooleanOptionHandler.class,
        usage =
            "Processes built-ins from the Closure library, such as "
                + "goog.require(), goog.provide(), and goog.exportSymbol()")
    private boolean processClosurePrimitives = true;

    @Option(
        name = "--manage_closure_dependencies",
        handler = BooleanOptionHandler.class,
        usage =
            "Automatically sort dependencies so that a file that "
                + "goog.provides symbol X will always come before a file that "
                + "goog.requires symbol X. If an input provides symbols, and "
                + "those symbols are never required, then that input will not "
                + "be included in the compilation.")
    private boolean manageClosureDependencies = false;

    @Option(
        name = "--only_closure_dependencies",
        handler = BooleanOptionHandler.class,
        usage =
            "Only include files in the transitive dependency of the "
                + "entry points (specified by closure_entry_point). Files that do "
                + "not provide dependencies will be removed. This supersedes"
                + "manage_closure_dependencies")
    private boolean onlyClosureDependencies = false;

    @Option(
        name = "--closure_entry_point",
        usage =
            "Entry points to the program. Must be goog.provide'd "
                + "symbols. Any goog.provide'd symbols that are not a transitive "
                + "dependency of the entry points will be removed. Files without "
                + "goog.provides, and their dependencies, will always be left in. "
                + "If any entry points are specified, then the "
                + "manage_closure_dependencies option will be set to true and "
                + "all files will be sorted in dependency order.")
    private List<String> closureEntryPoint = Lists.newArrayList();

    @Option(
        name = "--process_jquery_primitives",
        handler = BooleanOptionHandler.class,
        usage =
            "Processes built-ins from the Jquery library, such as "
                + "jQuery.fn and jQuery.extend()")
    private boolean processJqueryPrimitives = false;

    @Option(
        name = "--angular_pass",
        handler = BooleanOptionHandler.class,
        usage =
            "Generate $inject properties for AngularJS for functions " + "annotated with @ngInject")
    private boolean angularPass = false;

    @Option(
        name = "--output_manifest",
        usage =
            "Prints out a list of all the files in the compilation. "
                + "If --manage_closure_dependencies is on, this will not include "
                + "files that got dropped because they were not required. "
                + "The %outname% placeholder expands to the JS output file. "
                + "If you're using modularization, using %outname% will create "
                + "a manifest for each module.")
    private String outputManifest = "";

    @Option(
        name = "--output_module_dependencies",
        usage = "Prints out a JSON file of dependencies between modules.")
    private String outputModuleDependencies = "";

    @Option(name = "--accept_const_keyword", usage = "Allows usage of const keyword.")
    private boolean acceptConstKeyword = false;

    @Option(
        name = "--language_in",
        usage =
            "Sets what language spec that input sources conform. "
                + "Options: ECMASCRIPT3 (default), ECMASCRIPT5, ECMASCRIPT5_STRICT")
    private String languageIn = "ECMASCRIPT3";

    @Option(
        name = "--version",
        handler = BooleanOptionHandler.class,
        usage = "Prints the compiler version to stderr.")
    private boolean version = false;

    @Option(
        name = "--translations_file",
        usage = "Source of translated messages. Currently only supports XTB.")
    private String translationsFile = "";

    @Option(
        name = "--translations_project",
        usage =
            "Scopes all translations to the specified project."
                + "When specified, we will use different message ids so that messages "
                + "in different projects can have different translations.")
    private String translationsProject = null;

    @Option(name = "--flagfile", usage = "A file containing additional command-line options.")
    private String flagFile = "";

    @Option(
        name = "--warnings_whitelist_file",
        usage =
            "A file containing warnings to suppress. Each line should be "
                + "of the form\n"
                + "<file-name>:<line-number>?  <warning-description>")
    private String warningsWhitelistFile = "";

    @Option(
        name = "--extra_annotation_name",
        usage = "A whitelist of tag names in JSDoc. You may specify multiple")
    private List<String> extraAnnotationName = Lists.newArrayList();

    @Option(
        name = "--tracer_mode",
        usage =
            "Shows the duration of each compiler pass and the impact to "
                + "the compiled output size. Options: ALL, RAW_SIZE, TIMING_ONLY, OFF")
    private CompilerOptions.TracerMode tracerMode = CompilerOptions.TracerMode.OFF;

    @Argument private List<String> arguments = Lists.newArrayList();

    /**
     * Users may specify JS inputs via the legacy {@code --js} option, as well as via additional
     * arguments to the Closure Compiler. For example, it is convenient to leverage the additional
     * arguments feature when using the Closure Compiler in combination with {@code find} and {@code
     * xargs}:
     *
     * <pre>
     * find MY_JS_SRC_DIR -name '*.js' \
     *     | xargs java -jar compiler.jar --manage_closure_dependencies
     * </pre>
     *
     * The {@code find} command will produce a list of '*.js' source files in the {@code
     * MY_JS_SRC_DIR} directory while {@code xargs} will convert them to a single, space-delimited
     * set of arguments that are appended to the {@code java} command to run the Compiler.
     *
     * <p>Note that it is important to use the {@code --manage_closure_dependencies} option in this
     * case because the order produced by {@code find} is unlikely to be sorted correctly with
     * respect to {@code goog.provide()} and {@code goog.requires()}.
     */
    List<String> getJsFiles() {
      List<String> allJsInputs = Lists.newArrayListWithCapacity(js.size() + arguments.size());
      allJsInputs.addAll(js);
      allJsInputs.addAll(arguments);
      return allJsInputs;
    }

    // Our own option parser to be backwards-compatible.
    // It needs to be public because of the crazy reflection that args4j does.
    public static class BooleanOptionHandler extends OptionHandler<Boolean> {
      private static final Set<String> TRUES = Sets.newHashSet("true", "on", "yes", "1");
      private static final Set<String> FALSES = Sets.newHashSet("false", "off", "no", "0");

      public BooleanOptionHandler(
          CmdLineParser parser, OptionDef option, Setter<? super Boolean> setter) {
        super(parser, option, setter);
      }

      @Override
      public int parseArguments(Parameters params) throws CmdLineException {
        String param = null;
        try {
          param = params.getParameter(0);
        } catch (CmdLineException e) {
          param = null; // to stop linter complaints
        }

        if (param == null) {
          setter.addValue(true);
          return 0;
        } else {
          String lowerParam = param.toLowerCase();
          if (TRUES.contains(lowerParam)) {
            setter.addValue(true);
          } else if (FALSES.contains(lowerParam)) {
            setter.addValue(false);
          } else {
            setter.addValue(true);
            return 0;
          }
          return 1;
        }
      }

      @Override
      public String getDefaultMetaVariable() {
        return null;
      }
    }

    // Our own parser for warning guards that preserves the original order
    // of the flags.
    public static class WarningGuardErrorOptionHandler extends StringOptionHandler {
      public WarningGuardErrorOptionHandler(
          CmdLineParser parser, OptionDef option, Setter<? super String> setter) {
        super(parser, option, new WarningGuardSetter(setter, CheckLevel.ERROR));
      }
    }

    public static class WarningGuardWarningOptionHandler extends StringOptionHandler {
      public WarningGuardWarningOptionHandler(
          CmdLineParser parser, OptionDef option, Setter<? super String> setter) {
        super(parser, option, new WarningGuardSetter(setter, CheckLevel.WARNING));
      }
    }

    public static class WarningGuardOffOptionHandler extends StringOptionHandler {
      public WarningGuardOffOptionHandler(
          CmdLineParser parser, OptionDef option, Setter<? super String> setter) {
        super(parser, option, new WarningGuardSetter(setter, CheckLevel.OFF));
      }
    }

    private static class WarningGuardSetter implements Setter<String> {
      private final Setter<? super String> proxy;
      private final CheckLevel level;

      private WarningGuardSetter(Setter<? super String> proxy, CheckLevel level) {
        this.proxy = proxy;
        this.level = level;
      }

      @Override
      public boolean isMultiValued() {
        return proxy.isMultiValued();
      }

      @Override
      public Class<String> getType() {
        return (Class<String>) proxy.getType();
      }

      @Override
      public void addValue(String value) throws CmdLineException {
        proxy.addValue(value);
        guardLevels.add(new GuardLevel(value, level));
      }

      @Override
      public FieldSetter asFieldSetter() {
        return proxy.asFieldSetter();
      }

      @Override
      public AnnotatedElement asAnnotatedElement() {
        return proxy.asAnnotatedElement();
      }
    }

    public static WarningGuardSpec getWarningGuardSpec() {
      WarningGuardSpec spec = new WarningGuardSpec();
      for (GuardLevel guardLevel : guardLevels) {
        spec.add(guardLevel.level, guardLevel.name);
      }
      return spec;
    }
  }
Beispiel #24
0
  // I don't really care about unchecked warnings in this class.
  @SuppressWarnings("unchecked")
  private static class Flags {
    private static final WarningGuardSpec warningGuardSpec = new WarningGuardSpec();

    @Option(name = "--help", handler = BooleanOptionHandler.class, usage = "Displays this message")
    private boolean display_help = false;

    @Option(
        name = "--print_tree",
        handler = BooleanOptionHandler.class,
        usage = "Prints out the parse tree and exits")
    private boolean print_tree = false;

    @Option(
        name = "--print_ast",
        handler = BooleanOptionHandler.class,
        usage = "Prints a dot file describing the internal abstract syntax" + " tree and exits")
    private boolean print_ast = false;

    @Option(
        name = "--print_pass_graph",
        handler = BooleanOptionHandler.class,
        usage = "Prints a dot file describing the passes that will get run" + " and exits")
    private boolean print_pass_graph = false;

    // Turn on (very slow) extra sanity checks for use when modifying the
    // compiler.
    @Option(
        name = "--jscomp_dev_mode",
        // hidden, no usage
        aliases = {"--dev_mode"})
    private CompilerOptions.DevMode jscomp_dev_mode = CompilerOptions.DevMode.OFF;

    @Option(
        name = "--logging_level",
        usage =
            "The logging level (standard java.util.logging.Level"
                + " values) for Compiler progress. Does not control errors or"
                + " warnings for the JavaScript code under compilation")
    private String logging_level = Level.WARNING.getName();

    @Option(
        name = "--externs",
        usage = "The file containing javascript externs. You may specify" + " multiple")
    private List<String> externs = Lists.newArrayList();

    @Option(name = "--js", usage = "The javascript filename. You may specify multiple")
    private List<String> js = Lists.newArrayList();

    @Option(
        name = "--js_output_file",
        usage = "Primary output filename. If not specified, output is " + "written to stdout")
    private String js_output_file = "";

    @Option(
        name = "--module",
        usage =
            "A javascript module specification. The format is "
                + "<name>:<num-js-files>[:[<dep>,...][:]]]. Module names must be "
                + "unique. Each dep is the name of a module that this module "
                + "depends on. Modules must be listed in dependency order, and js "
                + "source files must be listed in the corresponding order. Where "
                + "--module flags occur in relation to --js flags is unimportant")
    private List<String> module = Lists.newArrayList();

    @Option(
        name = "--variable_map_input_file",
        usage =
            "File containing the serialized version of the variable "
                + "renaming map produced by a previous compilation")
    private String variable_map_input_file = "";

    @Option(
        name = "--property_map_input_file",
        usage =
            "File containing the serialized version of the property "
                + "renaming map produced by a previous compilation")
    private String property_map_input_file = "";

    @Option(
        name = "--variable_map_output_file",
        usage =
            "File where the serialized version of the variable "
                + "renaming map produced should be saved")
    private String variable_map_output_file = "";

    @Option(
        name = "--create_name_map_files",
        handler = BooleanOptionHandler.class,
        usage =
            "If true, variable renaming and property renaming map "
                + "files will be produced as {binary name}_vars_map.out and "
                + "{binary name}_props_map.out. Note that this flag cannot be used "
                + "in conjunction with either variable_map_output_file or "
                + "property_map_output_file")
    private boolean create_name_map_files = false;

    @Option(
        name = "--property_map_output_file",
        usage =
            "File where the serialized version of the property "
                + "renaming map produced should be saved")
    private String property_map_output_file = "";

    @Option(
        name = "--third_party",
        handler = BooleanOptionHandler.class,
        usage = "Check source validity but do not enforce Closure style " + "rules and conventions")
    private boolean third_party = false;

    @Option(
        name = "--summary_detail_level",
        usage =
            "Controls how detailed the compilation summary is. Values:"
                + " 0 (never print summary), 1 (print summary only if there are "
                + "errors or warnings), 2 (print summary if type checking is on, "
                + "see --check_types), 3 (always print summary). The default level "
                + "is 1")
    private int summary_detail_level = 1;

    @Option(
        name = "--output_wrapper",
        usage =
            "Interpolate output into this string at the place denoted"
                + " by the marker token %output%. See --output_wrapper_marker")
    private String output_wrapper = "";

    @Option(
        name = "--module_wrapper",
        usage =
            "An output wrapper for a javascript module (optional). "
                + "The format is <name>:<wrapper>. The module name must correspond "
                + "with a module specified using --module. The wrapper must "
                + "contain %s as the code placeholder")
    private List<String> module_wrapper = Lists.newArrayList();

    @Option(
        name = "--module_output_path_prefix",
        usage =
            "Prefix for filenames of compiled js modules. "
                + "<module-name>.js will be appended to this prefix. Directories "
                + "will be created as needed. Use with --module")
    private String module_output_path_prefix = "./";

    @Option(
        name = "--create_source_map",
        usage =
            "If specified, a source map file mapping the generated "
                + "source files back to the original source file will be "
                + "output to the specified path. The %outname% placeholder will "
                + "expand to the name of the output file that the source map "
                + "corresponds to.")
    private String create_source_map = "";

    @Option(
        name = "--jscomp_error",
        handler = WarningGuardErrorOptionHandler.class,
        usage =
            "Make the named class of warnings an error. Options:"
                + DiagnosticGroups.DIAGNOSTIC_GROUP_NAMES)
    private List<String> jscomp_error = Lists.newArrayList();

    @Option(
        name = "--jscomp_warning",
        handler = WarningGuardWarningOptionHandler.class,
        usage =
            "Make the named class of warnings a normal warning. "
                + "Options:"
                + DiagnosticGroups.DIAGNOSTIC_GROUP_NAMES)
    private List<String> jscomp_warning = Lists.newArrayList();

    @Option(
        name = "--jscomp_off",
        handler = WarningGuardOffOptionHandler.class,
        usage =
            "Turn off the named class of warnings. Options:"
                + DiagnosticGroups.DIAGNOSTIC_GROUP_NAMES)
    private List<String> jscomp_off = Lists.newArrayList();

    @Option(
        name = "--define",
        aliases = {"--D", "-D"},
        usage =
            "Override the value of a variable annotated @define. "
                + "The format is <name>[=<val>], where <name> is the name of a @define "
                + "variable and <val> is a boolean, number, or a single-quoted string "
                + "that contains no single quotes. If [=<val>] is omitted, "
                + "the variable is marked true")
    private List<String> define = Lists.newArrayList();

    @Option(
        name = "--charset",
        usage =
            "Input and output charset for all files. By default, we "
                + "accept UTF-8 as input and output US_ASCII")
    private String charset = "";

    @Option(
        name = "--compilation_level",
        usage =
            "Specifies the compilation level to use. Options: "
                + "WHITESPACE_ONLY, SIMPLE_OPTIMIZATIONS, ADVANCED_OPTIMIZATIONS")
    private CompilationLevel compilation_level = CompilationLevel.SIMPLE_OPTIMIZATIONS;

    @Option(
        name = "--warning_level",
        usage = "Specifies the warning level to use. Options: " + "QUIET, DEFAULT, VERBOSE")
    private WarningLevel warning_level = WarningLevel.DEFAULT;

    @Option(
        name = "--use_only_custom_externs",
        handler = BooleanOptionHandler.class,
        usage = "Specifies whether the default externs should be excluded")
    private boolean use_only_custom_externs = false;

    @Option(
        name = "--debug",
        handler = BooleanOptionHandler.class,
        usage = "Enable debugging options")
    private boolean debug = false;

    @Option(
        name = "--generate_exports",
        handler = BooleanOptionHandler.class,
        usage = "Generates export code for those marked with @export")
    private boolean generate_exports = false;

    @Option(
        name = "--formatting",
        usage =
            "Specifies which formatting options, if any, should be "
                + "applied to the output JS. Options: "
                + "PRETTY_PRINT, PRINT_INPUT_DELIMITER")
    private List<FormattingOption> formatting = Lists.newArrayList();

    @Option(
        name = "--process_closure_primitives",
        handler = BooleanOptionHandler.class,
        usage =
            "Processes built-ins from the Closure library, such as "
                + "goog.require(), goog.provide(), and goog.exportSymbol()")
    private boolean process_closure_primitives = true;

    @Option(
        name = "--manage_closure_dependencies",
        handler = BooleanOptionHandler.class,
        usage =
            "Automatically sort dependencies so that a file that "
                + "goog.provides symbol X will always come before a file that "
                + "goog.requires symbol X. If an input provides symbols, and "
                + "those symbols are never required, then that input will not "
                + "be included in the compilation.")
    private boolean manage_closure_dependencies = false;

    @Option(
        name = "--closure_entry_point",
        usage =
            "Entry points to the program. Must be goog.provide'd "
                + "symbols. Any goog.provide'd symbols that are not a transitive "
                + "dependency of the entry points will be removed. Files without "
                + "goog.provides, and their dependencies, will always be left in. "
                + "If any entry points are specified, then the "
                + "manage_closure_dependencies option will be set to true and "
                + "all files will be sorted in dependency order.")
    private List<String> closure_entry_point = Lists.newArrayList();

    @Option(
        name = "--output_manifest",
        usage =
            "Prints out a list of all the files in the compilation. "
                + "If --manage_closure_dependencies is on, this will not include "
                + "files that got dropped because they were not required. "
                + "The %outname% placeholder expands to the js output file. "
                + "If you're using modularization, using %outname% will create "
                + "a manifest for each module.")
    private String output_manifest = "";

    @Option(name = "--accept_const_keyword", usage = "Allows usage of const keyword.")
    private boolean accept_const_keyword = false;

    @Option(
        name = "--language_in",
        usage =
            "Sets what language spec that input sources conform. "
                + "Options: ECMASCRIPT3 (default), ECMASCRIPT5, ECMASCRIPT5_STRICT")
    private String language_in = "ECMASCRIPT3";

    @Option(
        name = "--version",
        handler = BooleanOptionHandler.class,
        usage = "Prints the compiler version to stderr.")
    private boolean version = false;

    @Option(name = "--flagfile", usage = "A file containing additional command-line options.")
    private String flag_file = "";

    // Our own option parser to be backwards-compatible.
    // It needs to be public because of the crazy reflection that args4j does.
    public static class BooleanOptionHandler extends OptionHandler<Boolean> {
      private static final Set<String> TRUES = Sets.newHashSet("true", "on", "yes", "1");
      private static final Set<String> FALSES = Sets.newHashSet("false", "off", "no", "0");

      public BooleanOptionHandler(
          CmdLineParser parser, OptionDef option, Setter<? super Boolean> setter) {
        super(parser, option, setter);
      }

      @Override
      public int parseArguments(Parameters params) throws CmdLineException {
        String param = null;
        try {
          param = params.getParameter(0);
        } catch (CmdLineException e) {
        }

        if (param == null) {
          setter.addValue(true);
          return 0;
        } else {
          String lowerParam = param.toLowerCase();
          if (TRUES.contains(lowerParam)) {
            setter.addValue(true);
          } else if (FALSES.contains(lowerParam)) {
            setter.addValue(false);
          } else {
            setter.addValue(true);
            return 0;
          }
          return 1;
        }
      }

      @Override
      public String getDefaultMetaVariable() {
        return null;
      }
    }

    // Our own parser for warning guards that preserves the original order
    // of the flags.
    public static class WarningGuardErrorOptionHandler extends StringOptionHandler {
      public WarningGuardErrorOptionHandler(
          CmdLineParser parser, OptionDef option, Setter<? super String> setter) {
        super(parser, option, new WarningGuardSetter(setter, CheckLevel.ERROR));
      }
    }

    public static class WarningGuardWarningOptionHandler extends StringOptionHandler {
      public WarningGuardWarningOptionHandler(
          CmdLineParser parser, OptionDef option, Setter<? super String> setter) {
        super(parser, option, new WarningGuardSetter(setter, CheckLevel.WARNING));
      }
    }

    public static class WarningGuardOffOptionHandler extends StringOptionHandler {
      public WarningGuardOffOptionHandler(
          CmdLineParser parser, OptionDef option, Setter<? super String> setter) {
        super(parser, option, new WarningGuardSetter(setter, CheckLevel.OFF));
      }
    }

    private static class WarningGuardSetter implements Setter {
      private final Setter proxy;
      private final CheckLevel level;

      private WarningGuardSetter(Setter proxy, CheckLevel level) {
        this.proxy = proxy;
        this.level = level;
      }

      @Override
      public boolean isMultiValued() {
        return proxy.isMultiValued();
      }

      @Override
      public Class getType() {
        return proxy.getType();
      }

      @Override
      public void addValue(Object value) throws CmdLineException {
        proxy.addValue((String) value);
        warningGuardSpec.add(level, (String) value);
      }
    }
  }
Beispiel #25
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();
    }
  }
}
Beispiel #26
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[] {};
  }
}
/**
 * Entry point class for the OpenCL4Java Object-oriented wrappers around the OpenCL API.<br>
 *
 * @author Olivier Chafik
 */
public class JavaCL {

  static final boolean debug =
      "true".equals(System.getProperty("javacl.debug"))
          || "1".equals(System.getenv("JAVACL_DEBUG"));
  static final boolean verbose =
      debug
          || "true".equals(System.getProperty("javacl.verbose"))
          || "1".equals(System.getenv("JAVACL_VERBOSE"));
  static final int minLogLevel = Level.WARNING.intValue();

  static final String JAVACL_DEBUG_COMPILER_FLAGS_PROP = "JAVACL_DEBUG_COMPILER_FLAGS";
  static List<String> DEBUG_COMPILER_FLAGS;

  static boolean shouldLog(Level level) {
    return verbose || level.intValue() >= minLogLevel;
  }

  static boolean log(Level level, String message, Throwable ex) {
    if (!shouldLog(level)) return true;
    Logger.getLogger(JavaCL.class.getSimpleName()).log(level, message, ex);
    return true;
  }

  static boolean log(Level level, String message) {
    log(level, message, null);
    return true;
  }

  private static int getPlatformIDs(
      int count, Pointer<cl_platform_id> out, Pointer<Integer> pCount) {
    try {
      return CL.clIcdGetPlatformIDsKHR(count, out, pCount);
    } catch (Throwable th) {
      return CL.clGetPlatformIDs(count, out, pCount);
    }
  }

  @org.bridj.ann.Library("OpenCLProbe")
  @org.bridj.ann.Convention(org.bridj.ann.Convention.Style.StdCall)
  public static class OpenCLProbeLibrary {
    static {
      BridJ.setNativeLibraryActualName("OpenCLProbe", "OpenCL");
      BridJ.register();
    }

    @org.bridj.ann.Optional
    public static synchronized native int clGetPlatformIDs(
        int cl_uint1,
        Pointer<OpenCLLibrary.cl_platform_id> cl_platform_idPtr1,
        Pointer<Integer> cl_uintPtr1);

    @org.bridj.ann.Optional
    public static synchronized native int clIcdGetPlatformIDsKHR(
        int cl_uint1,
        Pointer<OpenCLLibrary.cl_platform_id> cl_platform_idPtr1,
        Pointer<Integer> cl_uintPtr1);

    public boolean isValid() {
      Pointer<Integer> pCount = allocateInt();
      int err;
      try {
        err = clIcdGetPlatformIDsKHR(0, null, pCount);
      } catch (Throwable th) {
        try {
          err = clGetPlatformIDs(0, null, pCount);
        } catch (Throwable th2) {
          return false;
        }
      }
      return err == OpenCLLibrary.CL_SUCCESS && pCount.get() > 0;
    }
  }

  static final OpenCLLibrary CL;

  static {
    {
      OpenCLProbeLibrary probe = new OpenCLProbeLibrary();
      try {
        if (!probe.isValid()) {
          String alt;
          if (Platform.is64Bits() && BridJ.getNativeLibraryFile(alt = "atiocl64") != null
              || BridJ.getNativeLibraryFile(alt = "atiocl32") != null
              || BridJ.getNativeLibraryFile(alt = "atiocl") != null) {
            log(
                Level.INFO,
                "Hacking around ATI's weird driver bugs (using atiocl library instead of OpenCL)",
                null);
            BridJ.setNativeLibraryActualName("OpenCL", alt);
          }
        }
      } finally {
        probe = null;
        BridJ.unregister(OpenCLProbeLibrary.class);
      }
    }

    if (debug) {
      String debugArgs = System.getenv(JAVACL_DEBUG_COMPILER_FLAGS_PROP);
      if (debugArgs != null) DEBUG_COMPILER_FLAGS = Arrays.asList(debugArgs.split(" "));
      else if (Platform.isMacOSX()) DEBUG_COMPILER_FLAGS = Arrays.asList("-g");
      else DEBUG_COMPILER_FLAGS = Arrays.asList("-O0", "-g");

      int pid = ProcessUtils.getCurrentProcessId();
      log(
          Level.INFO,
          "Debug mode enabled with compiler flags \""
              + StringUtils.implode(DEBUG_COMPILER_FLAGS, " ")
              + "\" (can be overridden with env. var. JAVACL_DEBUG_COMPILER_FLAGS_PROP)");
      log(
          Level.INFO,
          "You can debug your kernels with GDB using one of the following commands :\n"
              + "\tsudo gdb --tui --pid="
              + pid
              + "\n"
              + "\tsudo ddd --debugger \"gdb --pid="
              + pid
              + "\"\n"
              + "More info here :\n"
              + "\thttp://code.google.com/p/javacl/wiki/DebuggingKernels");
    }
    CL = new OpenCLLibrary();
  }

  /** List the OpenCL implementations that contain at least one GPU device. */
  public static CLPlatform[] listGPUPoweredPlatforms() {
    CLPlatform[] platforms = listPlatforms();
    List<CLPlatform> out = new ArrayList<CLPlatform>(platforms.length);
    for (CLPlatform platform : platforms) {
      if (platform.listGPUDevices(true).length > 0) out.add(platform);
    }
    return out.toArray(new CLPlatform[out.size()]);
  }
  /** Lists all available OpenCL implementations. */
  public static CLPlatform[] listPlatforms() {
    Pointer<Integer> pCount = allocateInt();
    error(getPlatformIDs(0, null, pCount));

    int nPlats = pCount.get();
    if (nPlats == 0) return new CLPlatform[0];

    Pointer<cl_platform_id> ids = allocateTypedPointers(cl_platform_id.class, nPlats);

    error(getPlatformIDs(nPlats, ids, null));
    CLPlatform[] platforms = new CLPlatform[nPlats];

    for (int i = 0; i < nPlats; i++) {
      platforms[i] = new CLPlatform(ids.get(i));
    }
    return platforms;
  }

  /**
   * Creates an OpenCL context formed of the provided devices.<br>
   * It is generally not a good idea to create a context with more than one device, because much
   * data is shared between all the devices in the same context.
   *
   * @param devices devices that are to form the new context
   * @return new OpenCL context
   */
  public static CLContext createContext(
      Map<CLPlatform.ContextProperties, Object> contextProperties, CLDevice... devices) {
    return devices[0].getPlatform().createContext(contextProperties, devices);
  }

  /**
   * Allows the implementation to release the resources allocated by the OpenCL compiler. <br>
   * This is a hint from the application and does not guarantee that the compiler will not be used
   * in the future or that the compiler will actually be unloaded by the implementation. <br>
   * Calls to Program.build() after unloadCompiler() will reload the compiler, if necessary, to
   * build the appropriate program executable.
   */
  public static void unloadCompiler() {
    error(CL.clUnloadCompiler());
  }

  /**
   * Returns the "best" OpenCL device (currently, the one that has the largest amount of compute
   * units).<br>
   * For more control on what is to be considered a better device, please use the {@link
   * JavaCL#getBestDevice(CLPlatform.DeviceFeature[]) } variant.<br>
   * This is currently equivalent to <code>getBestDevice(MaxComputeUnits)</code>
   */
  public static CLDevice getBestDevice() {
    return getBestDevice(CLPlatform.DeviceFeature.MaxComputeUnits);
  }
  /**
   * Returns the "best" OpenCL device based on the comparison of the provided prioritized device
   * feature.<br>
   * The returned device does not necessarily exhibit the features listed in preferredFeatures, but
   * it has the best ordered composition of them.<br>
   * For instance on a system with a GPU and a CPU device, <code>
   * JavaCL.getBestDevice(CPU, MaxComputeUnits)</code> will return the CPU device, but on another
   * system with two GPUs and no CPU device it will return the GPU that has the most compute units.
   */
  public static CLDevice getBestDevice(CLPlatform.DeviceFeature... preferredFeatures) {
    List<CLDevice> devices = new ArrayList<CLDevice>();
    for (CLPlatform platform : listPlatforms())
      devices.addAll(Arrays.asList(platform.listAllDevices(true)));
    return CLPlatform.getBestDevice(Arrays.asList(preferredFeatures), devices);
  }
  /** Creates an OpenCL context with the "best" device (see {@link JavaCL#getBestDevice() }) */
  public static CLContext createBestContext() {
    return createBestContext(DeviceFeature.MaxComputeUnits);
  }

  /**
   * Creates an OpenCL context with the "best" device based on the comparison of the provided
   * prioritized device feature (see {@link JavaCL#getBestDevice(CLPlatform.DeviceFeature...) })
   */
  public static CLContext createBestContext(CLPlatform.DeviceFeature... preferredFeatures) {
    CLDevice device = getBestDevice(preferredFeatures);
    return device.getPlatform().createContext(null, device);
  }

  /**
   * Creates an OpenCL context able to share entities with the current OpenGL context.
   *
   * @throws RuntimeException if JavaCL is unable to create an OpenGL-shared OpenCL context.
   */
  public static CLContext createContextFromCurrentGL() {
    RuntimeException first = null;
    for (CLPlatform platform : listPlatforms()) {
      try {
        CLContext ctx = platform.createContextFromCurrentGL();
        if (ctx != null) return ctx;
      } catch (RuntimeException ex) {
        if (first == null) first = ex;
      }
    }
    throw new RuntimeException(
        "Failed to create an OpenCL context based on the current OpenGL context", first);
  }

  static File userJavaCLDir = new File(new File(System.getProperty("user.home")), ".javacl");
  static File userCacheDir = new File(userJavaCLDir, "cache");

  static synchronized File createTempFile(String prefix, String suffix, String category) {
    File dir = new File(userJavaCLDir, category);
    dir.mkdirs();
    try {
      return File.createTempFile(prefix, suffix, dir);
    } catch (IOException ex) {
      throw new RuntimeException(
          "Failed to create a temporary directory for category '"
              + category
              + "' in "
              + userJavaCLDir
              + ": "
              + ex.getMessage(),
          ex);
    }
  }

  static synchronized File createTempDirectory(String prefix, String suffix, String category) {
    File file = createTempFile(prefix, suffix, category);
    file.delete();
    file.mkdir();
    return file;
  }
}
/** @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;
      }
    };
  }
}
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;
    }
  }
}
/**
 * Configuration
 *
 * <p>Mail Service Configuration
 */
@XmlRootElement(name = "data-processor")
@XmlAccessorType(XmlAccessType.FIELD)
public class DataProcessorConfig {

  @XmlElement(name = "logFile")
  private String logFile =
      System.getProperty("java.io.tmpdir" + File.separator + "iaDataProcessor.log");

  @XmlElement(name = "logLevel", defaultValue = "WARNING")
  private String logLevel = Level.WARNING.getName();

  @XmlElementWrapper(name = "dataPArsers")
  @XmlElement(name = "dataParser")
  private PluginProperties dataParsers;

  @XmlElementWrapper(name = "fileFilters")
  @XmlElement(name = "fileFilters")
  private List<PluginProperties> filters;

  @XmlElementWrapper(name = "dataProcessors")
  @XmlElement(name = "dataProcessor")
  private List<PluginProperties> dataProcessors;

  @XmlElementWrapper(name = "dataOutput")
  @XmlElement(name = "dataOutput")
  private List<PluginProperties> dataOutput;

  public String getLogFile() {
    return logFile;
  }

  public void setLogFile(String logFile) {
    this.logFile = logFile;
  }

  public String getLogLevel() {
    return logLevel;
  }

  public void setLogLevel(String logLevel) {
    this.logLevel = logLevel;
  }

  public PluginProperties getDataParsers() {

    return dataParsers;
  }

  public void setDataParsers(PluginProperties dataParsers) {
    this.dataParsers = dataParsers;
  }

  public DataProcessorConfig addDataParser(PluginProperties dataParser) {
    getFilters().add(dataParser);
    return this;
  }

  public List<PluginProperties> getDataProcessors() {
    if (dataProcessors == null) {
      dataProcessors = new ArrayList<>();
    }
    return dataProcessors;
  }

  public void setDataProcessors(List<PluginProperties> dataProcessors) {
    this.dataProcessors = dataProcessors;
  }

  public DataProcessorConfig addDataProcessor(PluginProperties dataProcessor) {
    getDataProcessors().add(dataProcessor);
    return this;
  }

  public List<PluginProperties> getFilters() {
    if (filters == null) {
      filters = new ArrayList<>();
    }
    return filters;
  }

  public void setFilters(List<PluginProperties> filters) {
    this.filters = filters;
  }

  public DataProcessorConfig addFilter(PluginProperties filter) {
    getFilters().add(filter);
    return this;
  }

  public List<PluginProperties> getDataOutput() {
    if (dataOutput == null) {
      dataOutput = new ArrayList();
    }
    return dataOutput;
  }

  public void setDataOutput(List<PluginProperties> dataOutput) {
    this.dataOutput = dataOutput;
  }

  public DataProcessorConfig addDataOutput(PluginProperties dataOutput) {
    getFilters().add(dataOutput);
    return this;
  }
}