Example usage for org.apache.commons.io.input TailerListenerAdapter TailerListenerAdapter

List of usage examples for org.apache.commons.io.input TailerListenerAdapter TailerListenerAdapter

Introduction

In this page you can find the example usage for org.apache.commons.io.input TailerListenerAdapter TailerListenerAdapter.

Prototype

TailerListenerAdapter

Source Link

Usage

From source file:com.hellblazer.process.ProcessStartWatcher.java

public ProcessStartWatcher(ManagedProcess process) {

    TailerListener listener = new TailerListenerAdapter() {
        @Override/*from w ww  . j  a v  a  2  s .  co  m*/
        public void handle(String line) {
            lines.add(line);
        }
    };

    tailer = process.tailStdOut(listener);
}

From source file:com.google.cloud.tools.maven.it.verifier.TailingVerifier.java

private void startTailingLog() {
    TailerListener listener = new TailerListenerAdapter() {
        @Override/*from ww w.  j a  va2 s.  c  o  m*/
        public void handle(String line) {
            System.out.println(testName + ": " + line);
        }
    };

    // Tail the log
    File file = new File(getBasedir() + File.separator + getLogFileName());
    try {
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Tailer tailer = new Tailer(file, listener, TAIL_DELAY_MILLIS);
    Thread thread = new Thread(tailer);
    thread.setDaemon(true);
    thread.start();
}

From source file:com.streamsets.datacollector.websockets.LogMessageWebSocket.java

@Override
public void onWebSocketConnect(final Session session) {
    super.onWebSocketConnect(session);

    synchronized (LogMessageWebSocket.class) {
        int maxClients = config.get(MAX_LOGTAIL_CONCURRENT_REQUESTS_KEY,
                MAX_LOGTAIL_CONCURRENT_REQUESTS_DEFAULT);
        if (logTailClients < maxClients) {
            logTailClients++;//from  w w w. j av  a 2 s  .  co m
        } else {
            session.close(StatusCode.NORMAL, "Maximum concurrent connections reached");
            return;
        }
    }

    TailerListener listener = new TailerListenerAdapter() {
        @Override
        public void handle(String line) {
            try {
                Map<String, String> namedGroupToValuesMap = logFileGrok.extractNamedGroups(line);

                if (namedGroupToValuesMap == null) {
                    namedGroupToValuesMap = new HashMap<>();
                    namedGroupToValuesMap.put("exceptionMessagePart", line);
                }

                ObjectMapper objectMapper = ObjectMapperFactory.get();
                String logDataJson = objectMapper.writer().writeValueAsString(namedGroupToValuesMap);
                session.getRemote().sendString(logDataJson);

            } catch (IOException ex) {
                LOG.warn("Error while sending log line through WebSocket message, {}", ex.toString(), ex);
            }
        }

        @Override
        public void fileNotFound() {
            LOG.warn("Log file '{}' does not exist", logFile);
        }

        @Override
        public void handle(Exception ex) {
            LOG.warn("Error while trying to read log file '{}': {}", logFile, ex.toString(), ex);
        }
    };

    //TODO send -20K of logFile to session, separator line, then tailer

    tailer = new Tailer(new File(logFile), listener, 100, true, true);
    Thread thread = new Thread(tailer, "LogMessageWebSocket-tailLog");
    thread.setDaemon(true);
    thread.start();
}

From source file:net.centro.rtb.monitoringcenter.metrics.system.jvm.GarbageCollectorMetricSet.java

GarbageCollectorMetricSet() {
    this.garbageCollectorMXBeans = ManagementFactory.getGarbageCollectorMXBeans();

    this.minorGcTimer = new Timer();
    this.majorGcTimer = new Timer();

    // Determine the location of the gc log file (note that there's not support for rolling gc logs)
    String gcLogFilePath = null;//w ww. jav a2  s  .com
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    List<String> inputArguments = runtimeMXBean.getInputArguments();
    for (String argument : inputArguments) {
        if (argument.startsWith(LOG_GC_JVM_PARAM)) {
            gcLogFilePath = argument.substring(LOG_GC_JVM_PARAM.length());
            break;
        }
    }

    if (gcLogFilePath != null && !gcLogFilePath.trim().isEmpty()) {
        final File gcLogFile = new File(gcLogFilePath);
        if (gcLogFile.exists()) {
            this.fullCollectionsCounter = new AtomicLong();

            this.gcLogTailer = Tailer.create(gcLogFile, new TailerListenerAdapter() {
                @Override
                public void handle(String line) {
                    if (line != null && line.contains(FULL_GC_LOG_STRING)) {
                        fullCollectionsCounter.incrementAndGet();
                    }
                }
            }, GC_LOG_FILE_TAIL_DELAY_IN_MILLIS);
        }
    }

    // Attach a listener to the GarbageCollectorMXBeans
    this.gcEventListener = new NotificationListener() {
        @Override
        public void handleNotification(Notification notification, Object handback) {
            String notificationType = notification.getType();
            if (notificationType.equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
                CompositeData compositeData = CompositeData.class.cast(notification.getUserData());
                GarbageCollectionNotificationInfo gcNotificationInfo = GarbageCollectionNotificationInfo
                        .from(compositeData);

                if (GC_NOTIFICATION_MINOR_GC_ACTION_STRING.equals(gcNotificationInfo.getGcAction())) {
                    minorGcTimer.update(gcNotificationInfo.getGcInfo().getDuration(), TimeUnit.MILLISECONDS);
                } else if (GC_NOTIFICATION_MAJOR_GC_ACTION_STRING.equals(gcNotificationInfo.getGcAction())) {
                    majorGcTimer.update(gcNotificationInfo.getGcInfo().getDuration(), TimeUnit.MILLISECONDS);
                }
            }
        }
    };

    for (final GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMXBeans) {
        if (NotificationEmitter.class.isInstance(garbageCollectorMXBean)) {
            NotificationEmitter emitter = NotificationEmitter.class.cast(garbageCollectorMXBean);
            emitter.addNotificationListener(gcEventListener, null, null);
        }
    }

    // Set up metrics
    Map<String, Metric> metricsByNames = new HashMap<>();

    if (fullCollectionsCounter != null) {
        this.fullCollectionsGauge = new Gauge<Long>() {
            @Override
            public Long getValue() {
                return fullCollectionsCounter.get();
            }
        };
        metricsByNames.put("fullCollections", fullCollectionsGauge);
    }

    metricsByNames.put("majorGcTimer", majorGcTimer);
    metricsByNames.put("minorGcTimer", minorGcTimer);

    List<GarbageCollectorStatus> garbageCollectorStatuses = new ArrayList<>();
    for (final GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMXBeans) {
        final String garbageCollectorName = garbageCollectorMXBean.getName();
        final String garbageCollectorNamespace = MetricNamingUtil.join("collectors",
                MetricNamingUtil.sanitize(garbageCollectorName));

        final Gauge<Long> collectionsGauge;
        if (garbageCollectorMXBean.getCollectionCount() >= 0) {
            collectionsGauge = new Gauge<Long>() {
                @Override
                public Long getValue() {
                    return garbageCollectorMXBean.getCollectionCount();
                }
            };
            metricsByNames.put(MetricNamingUtil.join(garbageCollectorNamespace, "collections"),
                    collectionsGauge);
        } else {
            collectionsGauge = null;
        }

        final Gauge<Long> totalCollectionDurationInMillisGauge;
        if (garbageCollectorMXBean.getCollectionTime() >= 0) {
            totalCollectionDurationInMillisGauge = new Gauge<Long>() {
                @Override
                public Long getValue() {
                    return garbageCollectorMXBean.getCollectionTime();
                }
            };
            metricsByNames.put(
                    MetricNamingUtil.join(garbageCollectorNamespace, "totalCollectionDurationInMillis"),
                    totalCollectionDurationInMillisGauge);
        } else {
            totalCollectionDurationInMillisGauge = null;
        }

        garbageCollectorStatuses.add(new GarbageCollectorStatus() {
            @Override
            public String getName() {
                return garbageCollectorName;
            }

            @Override
            public Gauge<Long> getCollectionsGauge() {
                return collectionsGauge;
            }

            @Override
            public Gauge<Long> getTotalCollectionDurationInMillisGauge() {
                return totalCollectionDurationInMillisGauge;
            }
        });
    }
    this.garbageCollectorStatuses = garbageCollectorStatuses;

    this.metricsByNames = metricsByNames;
}

From source file:com.hellblazer.process.JavaProcessTest.java

public void testTailStdInputOutputStreams() throws Exception {
    final List<String> lines = new CopyOnWriteArrayList<>();
    TailerListener listener = new TailerListenerAdapter() {
        @Override//  w  w  w .j  a v a 2s  .  com
        public void handle(String line) {
            lines.add(line);
        }
    };

    copyTestClassFile();
    JavaProcess process = new JavaProcessImpl(processFactory.create());
    String testLine = "hello";
    process.setArguments(new String[] { "-readln", testLine });
    process.setJavaClass(HelloWorld.class.getCanonicalName());
    process.setDirectory(testDir);
    process.setJavaExecutable(javaBin);

    Tailer tailer = null;
    try {
        launchProcess(process);
        tailer = process.tailStdOut(listener);

        try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(process.getStdIn()))) {
            writer.println(testLine);
            writer.flush();
        }

        assertEquals("Process exited normally", 0, process.waitFor());
        assertTrue("Process not active", !process.isActive());
        Utils.waitForCondition(1000, new Condition() {
            @Override
            public boolean isTrue() {
                return lines.size() > 1;
            }
        });

        assertEquals(2, lines.size());
        assertEquals(testLine, lines.get(1));

        tailer.stop();
    } finally {
        if (tailer != null) {
            tailer.stop();
        }

        process.destroy();
    }
}

From source file:org.apache.directory.studio.ldapservers.LdapServersUtils.java

/**
 * Starts the console printer thread.//from  w  ww.j av a 2  s.  com
 *
 * @param server
 *      the server
 * @param serverLogsFile
 *       the server logs file
 */
public static void startConsolePrinterThread(LdapServer server, File serverLogsFile) {
    MessageConsole messageConsole = ConsolesManager.getDefault().getMessageConsole(server);
    MessageConsoleStream messageStream = messageConsole.newMessageStream();

    /*
     * DIRSTUDIO-1148: Tail the log file and update the console.
     * Tail from end only to avoid overwhelming the system in case the log file is large.
     */
    TailerListener l = new TailerListenerAdapter() {
        public void handle(String line) {
            messageStream.println(line);
        };
    };
    Tailer tailer = Tailer.create(serverLogsFile, l, 1000L, true);

    // Storing the tailer as a custom object in the LDAP Server for later use
    server.putCustomObject(CONSOLE_PRINTER_CUSTOM_OBJECT, tailer);
}

From source file:org.ngrinder.operation.cotroller.LogMonitorController.java

/**
 * Initialize the {@link Tailer}./*from www  . ja va 2 s.  c  o  m*/
 */
private synchronized void initTailer() {
    File logFile = getLogFile();
    if (tailer != null) {
        tailer.stop();
    }
    tailer = Tailer.create(logFile, new TailerListenerAdapter() {
        /**
         * Handles a line from a Tailer.
         *
         * @param line
         *            the line.
         */
        public void handle(String line) {
            synchronized (this) {
                if (stringBuffer.length() + line.length() > 5000) {
                    count++;
                    modification = 0;
                    stringBuffer = new StringBuffer();
                }
                modification++;
                if (stringBuffer.length() > 0) {
                    stringBuffer.append("<br>");
                }
                stringBuffer.append(line.replace("\n", "<br>"));
            }
        }
    }, 1000, true);
}

From source file:org.onehippo.cms7.launcher.LoggingPanel.java

private void startPolling() {
    final TailerListener listener = new TailerListenerAdapter() {
        @Override/*from  w w w .ja  v a 2  s . co  m*/
        public void handle(final String line) {
            try {
                loggingDocument.insertString(0, System.lineSeparator(), null);
                loggingDocument.insertString(0, line, null);
            } catch (BadLocationException e) {
                throw new RuntimeException(e);
            }
        }
    };
    final File catalinaLogFile = getCatalinaLogFile();
    final Executor logFilePollingExecutor = Executors.newSingleThreadExecutor();
    logFilePollingExecutor.execute(Tailer.create(catalinaLogFile, listener, 100L));
}