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 }
// 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 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); }
protected static void Log(Level loglevel, String txt, boolean sendReport) { logger.log(loglevel, String.format("[%s] %s", name, txt == null ? "" : txt)); if (config != null) { if (sendReport && loglevel.intValue() > Level.WARNING.intValue() && config.sendErrorReports) { sendErrorReport(txt, null); } if (messenger != null && loglevel.intValue() > Level.INFO.intValue() && config.sendLogOnError) { messenger.sendNotify(String.format("[%s] %s", name, txt == null ? "" : txt)); } } }
private static LogLevel getLogLevel(LogRecord record) { int level = record.getLevel().intValue(); if (level <= Level.CONFIG.intValue()) { return LogLevel.DEBUG; } else if (level <= Level.INFO.intValue()) { return LogLevel.INFO; } else if (level <= Level.WARNING.intValue()) { return LogLevel.WARN; } else if (level <= Level.SEVERE.intValue()) { return LogLevel.ERROR; } else { return LogLevel.FATAL; } }
/** * 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; }
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))); } } }
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()); }
// 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(); }
/** 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; }
private static boolean isLogWarning() { Level ll = logLevel(); return ll == null ? true : ll.intValue() <= Level.WARNING.intValue(); }
/** * 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; } }
/** * 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(); } }
/** @author Kamnev Georgiy ([email protected]) */ public class FileVar { // <editor-fold defaultstate="collapsed" desc="log Функции"> private static final Logger logger = Logger.getLogger(FileVar.class.getName()); private static final Level logLevel = logger.getLevel(); private static final boolean isLogSevere = logLevel == null ? true : logLevel.intValue() <= Level.SEVERE.intValue(); private static final boolean isLogWarning = logLevel == null ? true : logLevel.intValue() <= Level.WARNING.intValue(); private static final boolean isLogInfo = logLevel == null ? true : logLevel.intValue() <= Level.INFO.intValue(); private static final boolean isLogFine = logLevel == null ? true : logLevel.intValue() <= Level.FINE.intValue(); private static final boolean isLogFiner = logLevel == null ? true : logLevel.intValue() <= Level.FINER.intValue(); private static final boolean isLogFinest = logLevel == null ? true : logLevel.intValue() <= Level.FINEST.intValue(); private static void logFine(String message, Object... args) { logger.log(Level.FINE, message, args); } private static void logFiner(String message, Object... args) { logger.log(Level.FINER, message, args); } private static void logFinest(String message, Object... args) { logger.log(Level.FINEST, message, args); } private static void logInfo(String message, Object... args) { logger.log(Level.INFO, message, args); } private static void logWarning(String message, Object... args) { logger.log(Level.WARNING, message, args); } private static void logSevere(String message, Object... args) { logger.log(Level.SEVERE, message, args); } private static void logException(Throwable ex) { logger.log(Level.SEVERE, null, ex); } // </editor-fold> private final File file; public FileVar(File file) { if (file == null) throw new IllegalArgumentException("file==null"); this.file = file; } public File getFile() { return file; } public FileSystem getFileSystem() { return file.getFileSystem(); } public FileVar getParent() { File f = file.getParent(); if (f != null) return new FileVar(f); return null; } public FileVar getChild(String name) { File f = file.getChild(name); if (f != null) return new FileVar(f); return null; } public FileVar getCanonical() { File f = file.getCanonical(); if (f != null) return new FileVar(f); return null; } public FileVar getAbsolute() { File f = file.getAbsolute(); if (f != null) return new FileVar(f); return null; } public boolean isDirectory() { return file.isDirectory(); } public boolean isFile() { return file.isFile(); } public boolean isExists() { return file.isExists(); } public DateVar getModifyDate() { // return file.getModifyDate(); return new DateVar(file.getModifyDate()); } public long getLength() { return file.getLength(); } public String getSizeRound() { return new ByteSize(file.getLength()).toStringRoundMin(2); } public boolean isReadable() { return file.isReadable(); } public boolean isWritable() { return file.isWritable(); } public boolean isExecutable() { return file.isExecutable(); } public String getName() { return file.getName(); } public String getPath() { return file.getPath(); } public boolean isAbsolute() { return file.isAbsolute(); } public boolean isRoot() { return file.isRoot(); } }
public class Jul2Slf4jHandler extends Handler { private static final String FQCN = java.util.logging.Logger.class.getName(); private static final String UNKNOWN_LOGGER_NAME = "unknown.jul.logger"; private static final int TRACE_LEVEL_THRESHOLD = Level.FINEST.intValue(); private static final int DEBUG_LEVEL_THRESHOLD = Level.FINE.intValue(); private static final int INFO_LEVEL_THRESHOLD = Level.INFO.intValue(); private static final int WARN_LEVEL_THRESHOLD = Level.WARNING.intValue(); @Nullable private final ILoggerFactory _loggerFactory; public Jul2Slf4jHandler() { this(null); } public Jul2Slf4jHandler(@Nullable ILoggerFactory loggerFactory) { _loggerFactory = loggerFactory; } @Override public void close() {} @Override public void flush() {} @Nullable protected Logger getSLF4JLogger(@Nonnull LogRecord record) { final String name = record.getLoggerName(); return logger(name != null ? name : UNKNOWN_LOGGER_NAME); } protected void callLocationAwareLogger(LocationAwareLogger lal, LogRecord record) { final int julLevelValue = record.getLevel().intValue(); final int slf4jLevel; if (julLevelValue <= TRACE_LEVEL_THRESHOLD) { slf4jLevel = LocationAwareLogger.TRACE_INT; } else if (julLevelValue <= DEBUG_LEVEL_THRESHOLD) { slf4jLevel = LocationAwareLogger.DEBUG_INT; } else if (julLevelValue <= INFO_LEVEL_THRESHOLD) { slf4jLevel = LocationAwareLogger.INFO_INT; } else if (julLevelValue <= WARN_LEVEL_THRESHOLD) { slf4jLevel = LocationAwareLogger.WARN_INT; } else { slf4jLevel = LocationAwareLogger.ERROR_INT; } final String i18nMessage = getMessageI18N(record); lal.log(null, FQCN, slf4jLevel, i18nMessage, null, record.getThrown()); } protected void callPlainSLF4JLogger(@Nonnull Logger slf4jLogger, LogRecord record) { final String i18nMessage = getMessageI18N(record); final int julLevelValue = record.getLevel().intValue(); if (julLevelValue <= TRACE_LEVEL_THRESHOLD) { slf4jLogger.trace(i18nMessage, record.getThrown()); } else if (julLevelValue <= DEBUG_LEVEL_THRESHOLD) { slf4jLogger.debug(i18nMessage, record.getThrown()); } else if (julLevelValue <= INFO_LEVEL_THRESHOLD) { slf4jLogger.info(i18nMessage, record.getThrown()); } else if (julLevelValue <= WARN_LEVEL_THRESHOLD) { slf4jLogger.warn(i18nMessage, record.getThrown()); } else { slf4jLogger.error(i18nMessage, record.getThrown()); } } @Nullable protected String getMessageI18N(@Nonnull LogRecord record) { String message = record.getMessage(); if (message != null) { final ResourceBundle bundle = record.getResourceBundle(); if (bundle != null) { try { message = bundle.getString(message); } catch (final MissingResourceException ignored) { } } final Object[] params = record.getParameters(); if (params != null && params.length > 0) { message = MessageFormat.format(message, params); } } return message; } @Override public void publish(@Nullable LogRecord record) { if (record != null) { final Logger slf4jLogger = getSLF4JLogger(record); if (slf4jLogger instanceof LocationAwareLogger) { callLocationAwareLogger((LocationAwareLogger) slf4jLogger, record); } else { callPlainSLF4JLogger(slf4jLogger, record); } } } @Nonnull protected Logger logger(@Nonnull String name) { return _loggerFactory != null ? _loggerFactory.getLogger(name) : LoggerFactory.getLogger(name); } }
/** @author [email protected] */ public class EditorConfigParser { // <editor-fold defaultstate="collapsed" desc="log Функции"> private static final Logger logger = Logger.getLogger(EditorConfigParser.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(EditorConfigParser.class.getName(), method, params); } private static void logExiting(String method) { logger.exiting(EditorConfigParser.class.getName(), method); } private static void logExiting(String method, Object result) { logger.exiting(EditorConfigParser.class.getName(), method, result); } // </editor-fold> // pu }
/** @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[] {}; } }
/** @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(); } } }
/** @author Kamnev Georgiy ([email protected]) */ public class ComponentCheckChangesBegin extends HttpBegin { // <editor-fold defaultstate="collapsed" desc="log Функции"> private static final Logger logger = Logger.getLogger(ComponentCheckChangesBegin.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 ComponentCheckChangesBegin(HttpRepo repo) { super(repo); } public ComponentCheckChangesBegin(HttpRepo repo, HttpRequest request) { super(repo, request); } public ComponentCheckChangesBegin( HttpRepo repo, HttpRequest request, HttpResponse response, ComponentID cid) { super(repo, request, response); this.cid = cid; } private ComponentID cid; public ComponentID getCid() { return cid; } }
/** @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; } }; } }
/** @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; } }
/** @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; } }