/** * Signs a single XMLObject. * * @param signature the signature to computer the signature on * @throws SignatureException thrown if there is an error computing the signature */ public static void signObject(Signature signature) throws SignatureException { Logger log = getLogger(); try { XMLSignature xmlSignature = ((SignatureImpl) signature).getXMLSignature(); if (xmlSignature == null) { log.error("Unable to compute signature, Signature XMLObject does not have the XMLSignature " + "created during marshalling."); throw new SignatureException("XMLObject does not have an XMLSignature instance, unable to compute signature"); } log.debug("Computing signature over XMLSignature object"); xmlSignature.sign(SecurityHelper.extractSigningKey(signature.getSigningCredential())); } catch (XMLSecurityException e) { log.error("An error occured computing the digital signature", e); throw new SignatureException("Signature computation error", e); } }
public static List<String> listWithoutPath(List<String> listWithPrefix, String fixedPath, Logger log) { final List<String> listWithoutFixedPath; listWithoutFixedPath= new ArrayList<String>(); for (String resourcePath : listWithPrefix) { if (StringUtils.isNotEmpty(resourcePath)) if (resourcePath.startsWith(fixedPath)) listWithoutFixedPath.add(resourcePath.substring(fixedPath.length())); else log.warn(String.format("Invalid starting path %s, expected to begin with %s", resourcePath, fixedPath)); else log.warn(String.format("Empty path %s", resourcePath)); } return listWithoutFixedPath; }
public static void validateResource(String resourcePath,Logger log) { ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(); try { if (resourceResolver.getResources("classpath*:/GameData" +resourcePath+"*").length==0) log.error("INEXISTENT RESOURCE "+"/GameData" +resourcePath+"*"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private JsonObject getRequestJsonObject(Logger logger, boolean logFailedRequests) { JsonObject chart = new JsonObject(); chart.addProperty("chartId", chartId); try { JsonObject data = getChartData(); if (data == null) { // If the data is null we don't send the chart. return null; } chart.add("data", data); } catch (Throwable t) { if (logFailedRequests) { logger.warn("Failed to get data for custom chart with id {}", chartId, t); } return null; } return chart; }
/** * Parse set_vlan_id actions. * The key and delimiter for the action should be omitted, and only the * data should be presented to this decoder. Data with a leading 0x is permitted. * * @param actionToDecode; The action as a string to decode * @param version; The OF version to create the action for * @param log * @return */ private static OFActionSetVlanVid decode_set_vlan_id(String actionToDecode, OFVersion version, Logger log) { Matcher n = Pattern.compile("((?:0x)?\\d+)").matcher(actionToDecode); if (n.matches()) { if (n.group(1) != null) { try { VlanVid vlanid = VlanVid.ofVlan(get_short(n.group(1))); OFActionSetVlanVid.Builder ab = OFFactories.getFactory(version).actions().buildSetVlanVid(); ab.setVlanVid(vlanid); log.debug("action {}", ab.build()); return ab.build(); } catch (NumberFormatException e) { log.debug("Invalid VLAN in: {} (error ignored)", actionToDecode); return null; } } } else { log.debug("Invalid action: '{}'", actionToDecode); return null; } return null; }
/** * Parse set_tos actions. * The key and delimiter for the action should be omitted, and only the * data should be presented to this decoder. A leading 0x is permitted. * * @param actionToDecode; The action as a string to decode * @param version; The OF version to create the action for * @param log * @return */ private static OFActionSetNwTos decode_set_tos_bits(String actionToDecode, OFVersion version, Logger log) { Matcher n = Pattern.compile("((?:0x)?\\d+)").matcher(actionToDecode); if (n.matches()) { if (n.group(1) != null) { try { byte tosbits = get_byte(n.group(1)); OFActionSetNwTos.Builder ab = OFFactories.getFactory(version).actions().buildSetNwTos(); ab.setNwTos(tosbits); log.debug("action {}", ab.build()); return ab.build(); } catch (NumberFormatException e) { log.debug("Invalid dst-port in: {} (error ignored)", actionToDecode); return null; } } } else { log.debug("Invalid action: '{}'", actionToDecode); return null; } return null; }
public NettyClientHandler(String id, int epoch, String protocol, int affinity, T login, Integer connTimeout, long idleTimeout, Logger log, NettyMetricsSink metrics, NettyClient<T> client, NetworkClientCallback<T> callback) { this.log = log; this.id = id; this.epoch = epoch; this.protocol = protocol; this.affinity = affinity; this.login = login; this.idleTimeout = idleTimeout; this.connTimeout = connTimeout; this.metrics = metrics; this.client = client; this.callback = callback; this.debug = log.isDebugEnabled(); this.trace = log.isTraceEnabled(); hbOnFlush = future -> { hbFlushed = true; if (!future.isSuccess() && future.channel().isOpen()) { future.channel().pipeline().fireExceptionCaught(future.cause()); } }; }
/** * GithubSteps logs the received comment and author and * executes the given steps. * @throws Exception If something goes wrong. */ @Test public void logsAndExecutesSteps() throws Exception { final Command comment = Mockito.mock(Command.class); Mockito.when(comment.json()).thenReturn( Json.createObjectBuilder().add("body", "@comdor run").build() ); Mockito.when(comment.author()).thenReturn("amihaiemil"); final Step toExecute = Mockito.mock(Step.class); final Steps steps = new GithubSteps(toExecute, comment); final Log log = Mockito.mock(Log.class); final Logger slf4j = Mockito.mock(Logger.class); Mockito.when(log.logger()).thenReturn(slf4j); steps.perform(log); Mockito.verify(slf4j).info("Received command: @comdor run"); Mockito.verify(slf4j).info("Author login: amihaiemil"); Mockito.verify(toExecute).perform(comment, log); }
/** * Write out the state the all the history steps. */ public static void logHistorySteps(Logger logger, long piid, OSWfEngine wfEngine) { List<Step> steps = wfEngine.getHistorySteps(piid); WorkflowDescriptor wfDescriptor = wfEngine.getWorkflowDescriptor(wfEngine.getWorkflowName(piid)); if(steps.size() > 0) for (Step step : steps) logger.debug(String.format("History Step: %3d %-20s %s ", // %3s-%3s step.getStepId(), wfDescriptor.getStep(step.getStepId()).getName(), step.getStatus() // dateFormatter.format(step.getStartDate()), // dateFormatter.format(step.getFinishDate()) )); else logger.debug("No available history steps"); }
protected void pluginHealthCheck() { ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); scheduledExecutorService.scheduleWithFixedDelay(new Runnable() { private final Logger CHECKLOGGER = LoggerFactory.getLogger(AbstractPluginManager.class); @Override public void run() { for (Plugin p : context.getPluginMap().values()) { if (p.getStatus().equals(PluginStatus.ERROR)) { CHECKLOGGER.error("HEALTH CHECK - Plugin {} is in error.", p.getName()); p.disable(); } } } }, 0, 1, TimeUnit.SECONDS); }
public static Slf4jDdsLogger createRegisterLogger() throws IOException { // create logger Slf4jDdsLogger slf4jDdsLogger = new Slf4jDdsLogger(); // register logger com.rti.ndds.config.Logger.get_instance().set_output_device(slf4jDdsLogger); com.rti.ndds.config.Logger.get_instance().set_print_format(LogPrintFormat.NDDS_CONFIG_LOG_PRINT_FORMAT_TIMESTAMPED); // set log level if (LOGGER.isTraceEnabled()) { com.rti.ndds.config.Logger.get_instance().set_verbosity(LogVerbosity.NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); } else if (LOGGER.isWarnEnabled()) { com.rti.ndds.config.Logger.get_instance().set_verbosity(LogVerbosity.NDDS_CONFIG_LOG_VERBOSITY_WARNING); } else if (LOGGER.isErrorEnabled()) { com.rti.ndds.config.Logger.get_instance().set_verbosity(LogVerbosity.NDDS_CONFIG_LOG_VERBOSITY_ERROR); } // return logger return slf4jDdsLogger; }
public static void close(ThreadPoolExecutor executor, Logger logger) { executor.shutdown(); // Disable new tasks from being submitted try { // Wait a while for existing tasks to terminate if (!executor.awaitTermination(1, TimeUnit.SECONDS)) { executor.shutdownNow(); // Cancel currently executing tasks // Wait a while for tasks to respond to being cancelled if (!executor.awaitTermination(1, TimeUnit.SECONDS)) { logger.error("Pool did not terminate"); } } } catch (InterruptedException ie) { logger.warn("Executor interrupted while awaiting termination"); // (Re-)Cancel if current thread also interrupted executor.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } }
private void exParamDeal(WObject wObject, PorterOfFun porterOfFun, ParamDealt.FailedReason reason, boolean responseWhenException) { Logger LOGGER = logger(wObject); JResponse jResponse = null; if (LOGGER.isDebugEnabled() || responseWhenException) { jResponse = toJResponse(reason, wObject); LOGGER.debug("{}:{}", wObject.url(), jResponse); } if (responseWhenException) { if (jResponse == null) { jResponse = toJResponse(reason, wObject); } doFinalWrite(wObject, porterOfFun, jResponse); } close(wObject); }
/** * The entry point of application. * * @param args the command line arguments */ public static void main(String[] args) { Logger logger = LoggerFactory.getLogger(GUILabelingTool.class); System.getProperty("java.library.path"); /* Create and display the form */ java.awt.EventQueue.invokeLater(() -> { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // SplashScreen.startSplash() GUILabelingTool gui = new GUILabelingTool(logger); gui.setVisible(true); // for the first run, some special configuration have to be done gui.firstStartInitialization(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { logger.error("Create and display form"); logger.debug("Create and display form {}", ex); } }); }
@Inject public VirtualTool(@ConfigDir(sharedRoot = true) Path path, Logger logger, PluginContainer container) { this.dataDir = Sponge.getGame().getSavesDirectory().resolve(PluginData.id); this.pluginContainer = container; this.logger = new VTLogger(CText.get(CText.Colors.BLUE, 1, "V") + CText.get(CText.Colors.MAGENTA, 0, "T")); this.configdirpath = path.resolve(PluginData.id); this.backpackDir = Paths.get(this.getConfigPath().toString(), "backpacks"); this.configfullpath = Paths.get(this.getConfigPath().toString(), "config.json"); this.settings = new Settings(); }
public void setLsfJobStatus(String lsfJobStatus) { this.lsfJobStatus = lsfJobStatus; if ("PEND".equals(lsfJobStatus)) { setStatus(JobStatus.PENDING); } else if ("RUN".equals(lsfJobStatus)) { setStatus(JobStatus.RUNNING); } else if ("DONE".equals(lsfJobStatus)) { setStatus(JobStatus.DONE); } else if ("EXIT".equals(lsfJobStatus)) { setStatus(JobStatus.EXIT); } else if ("PSUSP".equals(lsfJobStatus)) { setStatus(JobStatus.SUSPENDED); } else if ("USUSP".equals(lsfJobStatus)) { setStatus(JobStatus.SUSPENDED); } else if ("SSUSP".equals(lsfJobStatus)) { setStatus(JobStatus.SUSPENDED); } else if ("UNKWN".equals(lsfJobStatus)) { setStatus(JobStatus.OTHER); } else { setStatus(JobStatus.OTHER); Logger log = LoggerFactory.getLogger(JobStatus.class); log.error("Unknown LSF job status: "+lsfJobStatus); } }
private boolean isProcessRunning(final String pid, final Logger logger) { try { // We use the "ps" command to check if the process is still running. final ProcessBuilder builder = new ProcessBuilder(); builder.command("ps", "-p", pid); final Process proc = builder.start(); // Look for the pid in the output of the 'ps' command. boolean running = false; String line; try (final InputStream in = proc.getInputStream(); final Reader streamReader = new InputStreamReader(in); final BufferedReader reader = new BufferedReader(streamReader)) { while ((line = reader.readLine()) != null) { if (line.trim().startsWith(pid)) { running = true; } } } // If output of the ps command had our PID, the process is running. if (running) { logger.debug("Process with PID {} is running", pid); } else { logger.debug("Process with PID {} is not running", pid); } return running; } catch (final IOException ioe) { System.err.println("Failed to determine if Process " + pid + " is running; assuming that it is not"); return false; } }
public static void doLog(String s, LogLevel logLevel, Logger logger) { switch (logLevel) { case ERROR: { logger.error(s); break; } case WARN: { logger.warn(s); break; } case INFO: { logger.info(s); break; } case DEBUG: { logger.debug(s); break; } case TRACE: { logger.trace(s); break; } default: { logger.error(s); break; } } }
/** * Grants a lock on the identified resource to the calling thread (blocking * until it is available). * * @return true if the lock was obtained. */ public boolean obtainLock(Connection conn, String lockName) throws LockException { lockName = lockName.intern(); Logger log = getLog(); if(log.isDebugEnabled()) { log.debug( "Lock '" + lockName + "' is desired by: " + Thread.currentThread().getName()); } if (!isLockOwner(conn, lockName)) { executeSQL(conn, lockName, expandedSQL); if(log.isDebugEnabled()) { log.debug( "Lock '" + lockName + "' given to: " + Thread.currentThread().getName()); } getThreadLocks().add(lockName); //getThreadLocksObtainer().put(lockName, new // Exception("Obtainer...")); } else if(log.isDebugEnabled()) { log.debug( "Lock '" + lockName + "' Is already owned by: " + Thread.currentThread().getName()); } return true; }
public Patterdale(PatterdaleRuntimeParameters runtimeParameters, Map<String, DBConnectionPool> connectionPools, TypeToProbeMapper typeToProbeMapper, Map<String, Probe> probesByName, Logger logger) { this.runtimeParameters = runtimeParameters; this.connectionPools = connectionPools; this.typeToProbeMapper = typeToProbeMapper; this.probesByName = probesByName; this.logger = logger; }
public Logger getLogger(String name) { Logger logger = loggers.get(name); if (logger != null) { return logger; } logger = loggers.putIfAbsent(name, new OutputEventListenerBackedLogger(name, this, timeProvider)); return logger != null ? logger : loggers.get(name); }
@Ignore("Integration test to test going to cloudwatch") @Test public void test() throws InterruptedException { Logger logger = LoggerFactory.getLogger(getClass()); logger.info("testing stuff"); logger.error("Here's a throw", new RuntimeException(new Exception("test exception here"))); Thread.sleep(1000); logger.info("more stuff"); Thread.sleep(10000000); }
/** * Set logging level to given value. If not explicitly * specified, default level is used from *logger* properties file. * (As of the time writing - simplelogger.properties is used as default.) * <p/> * NOTE: SLF4J is not capable of changing log levels programatically! * We have to change the System/File property of given underlying logger. * * @param logLevel logging level to be logger set to */ public static void setLogLevel(String logLevel) { org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("com.redhat.mqe.jms"); Level level; switch (logLevel.toLowerCase()) { case "all": level = Level.ALL; break; case "trace": level = Level.TRACE; break; case "debug": level = Level.DEBUG; break; case "info": level = Level.INFO; break; case "warn": level = Level.WARN; break; case "error": level = Level.ERROR; break; case "fatal": level = Level.FATAL; break; case "off": level = Level.OFF; break; default: level = Level.INFO; } LogManager.getRootLogger().setLevel(level); logger.setLevel(level); }
public static void main(String[] args) { Logger log=LoggerFactory.getLogger(Test.class); log.info("nihao{},{}",'a','b'); String sql="insert into book values(%s,%s,%s)"; String format = String.format(sql, 1,2,"3"); System.out.println(format); }
static public void logQuorumPacket(Logger log, long mask, char direction, QuorumPacket qp) { if (isTraceEnabled(log, mask)) { logTraceMessage(log, mask, direction + " " + LearnerHandler.packetToString(qp)); } }
public String changeMode(String changingMode) throws IOException, ConsoleException { Logger log = LoggerFactory.getLogger(getClass()); log.debug("mode-change: " + this.currentMode + " to " + changingMode); if (MODE_ENABLE.equals(currentMode) && changingMode.startsWith(MODE_CONFIG)) { sendln("config"); currentMode = changingMode; return translate(receiveToPrompt()); } else if (currentMode.startsWith(MODE_CONFIG) && changingMode.startsWith(MODE_ENABLE)) { sendln("exit"); currentMode = changingMode; return translate(receiveToPrompt()); } else { return ""; } }
private void killProcessTree(final String pid, final Logger logger) throws IOException { logger.debug("Killing Process Tree for PID {}", pid); final List<String> children = getChildProcesses(pid); logger.debug("Children of PID {}: {}", new Object[]{pid, children}); for (final String childPid : children) { killProcessTree(childPid, logger); } Runtime.getRuntime().exec(new String[]{"kill", "-9", pid}); }
private static void gitAddCommitAndPush(Git git, String gitUrl, UserDetails userDetails, File basedir, String message, String branch, String origin, Logger logger) throws GitAPIException { PersonIdent personIdent = userDetails.createPersonIdent(); GitUtils.configureBranch(git, branch, origin, gitUrl); GitUtils.addDummyFileToEmptyFolders(basedir); logger.info("About to git commit and push to: " + gitUrl + " and remote name " + origin); int retryCount = 5; for (int i = retryCount; i > 0; i--) { if (i < retryCount) { try { Thread.sleep(500); } catch (InterruptedException e1) { e1.printStackTrace(); } } try { GitUtils.doAddCommitAndPushFiles(git, userDetails, personIdent, branch, origin, message, true); return; } catch (TransportException e) { if (i <= 1) { throw e; } else { logger.info("Caught a transport exception: " + e + " so retrying"); } } } }
private Logger getNewLogger(String jobID,String fileLogLocation) { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); FileAppender<ILoggingEvent> fileAppender = new FileAppender<>(); fileAppender.setContext(loggerContext); fileAppender.setFile(fileLogLocation); /*SizeBasedTriggeringPolicy<ILoggingEvent> triggeringPolicy = new SizeBasedTriggeringPolicy<ILoggingEvent>(); triggeringPolicy.setMaxFileSize("10MB"); triggeringPolicy.start();*/ PatternLayoutEncoder encoder = new PatternLayoutEncoder(); encoder.setContext(loggerContext); encoder.setPattern("%msg%n"); encoder.start(); fileAppender.setEncoder(encoder); fileAppender.start(); // attach the rolling file appender to the logger of your choice Logger logbackLogger = loggerContext.getLogger(jobID); ((ch.qos.logback.classic.Logger) logbackLogger).addAppender(fileAppender); executionTrackingLoggers.put(jobID, logbackLogger); return logbackLogger; }
@Override public void transform(TransformationContext transformation) throws Exception { Logger logger = transformation.getLogger(getClass()); int i = 0; transformation.getPluginFileAccess().access("some-output-file").append("some transformation result").close(); logger.info("Waiting 500ms until completion"); while (!Thread.currentThread().isInterrupted() && i < 5) { Thread.sleep(100); i++; } if (failDuringExec) { logger.info("Throwing test exception"); throw new InterruptedException("Test Exception"); } }
/** * Initializes the artifact factories for SAML 1 and SAML 2 artifacts. * * @throws ConfigurationException thrown if there is a problem initializing the artifact factory */ protected static void initializeArtifactBuilderFactories() throws ConfigurationException { Logger log = getLogger(); log.debug("Initializing SAML Artifact builder factories"); Configuration.setSAML1ArtifactBuilderFactory(new SAML1ArtifactBuilderFactory()); Configuration.setSAML2ArtifactBuilderFactory(new SAML2ArtifactBuilderFactory()); }
@Test public void test_logging() { Logger logger = LoggerFactory.getLogger(LoggingTest.class); logger.info("info logging"); try { new MyClient().getTheThings(); } catch(Exception e) { logger.error("error logging with stack", e); } }
/** * StarRepo can successfully star a given repository. * @throws Exception If something goes wrong. */ @Test public void starsRepo() throws Exception { final Log log = Mockito.mock(Log.class); final Logger slf4j = Mockito.mock(Logger.class); Mockito.doNothing().when(slf4j).info(Mockito.anyString()); Mockito.doThrow( new IllegalStateException("Unexpected error; test failed") ).when(slf4j).error(Mockito.anyString()); Mockito.when(log.logger()).thenReturn(slf4j); final Github gh = new MkGithub("amihaiemil"); final Repo repo = gh.repos().create( new Repos.RepoCreate("amihaiemil.github.io", false) ); final Command com = Mockito.mock(Command.class); final Issue issue = Mockito.mock(Issue.class); Mockito.when(issue.repo()).thenReturn(repo); Mockito.when(com.issue()).thenReturn(issue); final Step star = new StarRepo(Mockito.mock(Step.class)); MatcherAssert.assertThat( com.issue().repo().stars().starred(), Matchers.is(false) ); star.perform(com, log); MatcherAssert.assertThat( com.issue().repo().stars().starred(), Matchers.is(true) ); }
/** * Valide un bean * * @param bean * @throws CustomException */ public static <T> Boolean validateBean(T bean, Logger logger) { logger.debug(" ***VALIDATION*** : " + bean); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<T>> constraintViolations = validator.validate(bean); if (constraintViolations != null && constraintViolations.size() > 0) { for (ConstraintViolation<?> violation : constraintViolations) { logger.debug(" *** " + violation.getPropertyPath().toString() + " : " + violation.getMessage()); } return false; } return true; }
/** * debug * @param logger * @param message * @param params */ public static void debug(Logger logger, String message, Object... params) { if (logger.isDebugEnabled()) { logger.debug(message, params); } }
public static void dumpChanges(CommandBuilder builder) { Logger log = LoggerFactory.getLogger(CommandUtil.class); StringBuilder sb = new StringBuilder(); for (ChangeUnit unit : builder.getChangeUnits()) { if (sb.length() > 0) { sb.append(", "); } sb.append(unit.simpleToString()); } log.debug("BuildResult: changed:" + builder.getClass().getSimpleName() + "\r\n" + sb.toString()); }
/** * Creates the Logging instance to flush to the given logger. */ public OutpuStreamLogAdapter(final Logger log, final String logPrefix, final boolean flushOnLineBreak) throws IllegalArgumentException { this.logPrefix = logPrefix; this.flushOnLineBreak = flushOnLineBreak; if (log == null) { throw new IllegalArgumentException("Logger or log level must be not null"); } this.log = log; curBufLength = DEFAULT_BUFFER_LENGTH; buf = new byte[curBufLength]; count = 0; }
/** * Redirect JUL from third-party libraries to SLF4J */ private void redirectJULtoSLF4J() { LOGGER.info("Redirecting JUL to SLF4J"); LogManager.getLogManager().reset(); SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); java.util.logging.Logger.getGlobal().setLevel(Level.FINEST); }
/** * {@inheritDoc} * <p>Attempts to find the <strong>real</strong> {@code Logger} instance that * is doing the heavy lifting and routes the request to an instance of * {@link CasDelegatingLogger}. The instance is cached by the logger name.</p> */ @Override public Logger getLogger(final String name) { if (StringUtils.isBlank(name)) { return NOPLogger.NOP_LOGGER; } synchronized (loggerMap) { if (!loggerMap.containsKey(name)) { final Logger logger = getRealLoggerInstance(name); loggerMap.put(name, new CasDelegatingLogger(logger)); } return loggerMap.get(name); } }
protected Logger getLog() { return log; }