org.apache.logging.log4j.Logger Java Examples
The following examples show how to use
org.apache.logging.log4j.Logger.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PlottingUtils.java From gatk with BSD 3-Clause "New" or "Revised" License | 6 votes |
static Map<String, Integer> getContigLengthMap(final SAMSequenceDictionary sequenceDictionary, final int minContigLength, final Logger logger) { Utils.nonNull(sequenceDictionary); ParamUtils.isPositiveOrZero(minContigLength, "Minimum contig length must be non-negative."); Utils.nonNull(logger); Utils.validateArg(sequenceDictionary.getSequences().stream().map(SAMSequenceRecord::getSequenceName).noneMatch(n -> n.contains(CONTIG_DELIMITER)), String.format("Contig names cannot contain \"%s\".", CONTIG_DELIMITER)); final Map<String, Integer> contigLengthMap = sequenceDictionary.getSequences().stream() .filter(s -> s.getSequenceLength() >= minContigLength) .collect(Collectors.toMap(SAMSequenceRecord::getSequenceName, SAMSequenceRecord::getSequenceLength, (c, l) -> { throw new IllegalArgumentException(String.format("Duplicate contig in sequence dictionary: %s", c)); }, LinkedHashMap::new)); Utils.validateArg(contigLengthMap.size() > 0, "There must be at least one contig above the threshold length in the sequence dictionary."); logger.info("Contigs above length threshold: " + contigLengthMap.toString()); return contigLengthMap; }
Example #2
Source File: LogFeederUtil.java From ambari-logsearch with Apache License 2.0 | 6 votes |
public static boolean logErrorMessageByInterval(String key, String message, Throwable e, Logger callerLogger, Level level) { LogHistory log = logHistoryList.get(key); if (log == null) { log = new LogHistory(); logHistoryList.put(key, log); } if ((System.currentTimeMillis() - log.lastLogTime) > 30 * 1000) { log.lastLogTime = System.currentTimeMillis(); if (log.counter > 0) { message += ". Messages suppressed before: " + log.counter; } log.counter = 0; callerLogger.log(level, message, e); return true; } else { log.counter++; return false; } }
Example #3
Source File: RollingFilePropertiesTest.java From logging-log4j2 with Apache License 2.0 | 6 votes |
@Test public void testPropertiesConfiguration() { final Configuration config = context.getConfiguration(); assertNotNull("No configuration created", config); assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED); final Map<String, Appender> appenders = config.getAppenders(); assertNotNull(appenders); assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 3); final Map<String, LoggerConfig> loggers = config.getLoggers(); assertNotNull(loggers); assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2); final Filter filter = config.getFilter(); assertNotNull("No Filter", filter); assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter); final Logger logger = LogManager.getLogger(getClass()); logger.info("Welcome to Log4j!"); }
Example #4
Source File: HDF5PCACoveragePoNCreationUtils.java From gatk-protected with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Calculate the number of eigensamples given the user preferences and the * result of the log-normals SVD. * * @param requestedNumberOfEigensamples the user requested eigenvalues (empty means the user didn't specify any in particular). * @param numberOfCountColumns number of count columns in the original input. * @param logNormalizedSVD SVD results on the log-normalized counts. * @return always greater than 0. */ @VisibleForTesting static int determineNumberOfEigensamples(final OptionalInt requestedNumberOfEigensamples, final int numberOfCountColumns, final SVD logNormalizedSVD, final Logger logger) { final int numberOfEigensamples; if (requestedNumberOfEigensamples.isPresent()) { if (requestedNumberOfEigensamples.getAsInt() > numberOfCountColumns) { logger.warn(String.format("The number of requested eigensamples (%d) is larger than the available number of read count columns after filtering (%d), thus we will have to use the latter.", requestedNumberOfEigensamples.getAsInt(), numberOfCountColumns)); } numberOfEigensamples = Math.min(requestedNumberOfEigensamples.getAsInt(), numberOfCountColumns); } else { final double[] singularValues = logNormalizedSVD.getSingularValues(); final double mean = MathUtils.mean(singularValues, 0, singularValues.length); final double eigenvalueCutoff = mean * JOLLIFES_RULE_MEAN_FACTOR; // Jollife's less strict version of Kaiser' Rule. numberOfEigensamples = (int) DoubleStream.of(singularValues).filter(v -> v > eigenvalueCutoff).count(); logger.info(String.format("Jollife's rule produced %d eigensamples out of %d possibles for the reduced PoN", numberOfEigensamples, numberOfCountColumns)); } return numberOfEigensamples; }
Example #5
Source File: AsyncLoggerThreadContextTest.java From logging-log4j2 with Apache License 2.0 | 6 votes |
@Test public void testAsyncLogWritesToLog() throws Exception { final File file = new File("target", "AsyncLoggerTest.log"); // System.out.println(f.getAbsolutePath()); file.delete(); ThreadContext.push("stackvalue"); ThreadContext.put("KEY", "mapvalue"); final Logger log = LogManager.getLogger("com.foo.Bar"); final String msg = "Async logger msg"; log.info(msg, new InternalError("this is not a real error")); CoreLoggerContexts.stopLoggerContext(false, file); // stop async thread final BufferedReader reader = new BufferedReader(new FileReader(file)); final String line1 = reader.readLine(); reader.close(); file.delete(); assertNotNull("line1", line1); assertTrue("line1 correct", line1.contains(msg)); assertTrue("ThreadContext.map", line1.contains("mapvalue")); assertTrue("ThreadContext.stack", line1.contains("stackvalue")); }
Example #6
Source File: BesuCommand.java From besu with Apache License 2.0 | 6 votes |
@VisibleForTesting protected BesuCommand( final Logger logger, final Supplier<RlpBlockImporter> rlpBlockImporter, final Function<BesuController, JsonBlockImporter> jsonBlockImporterFactory, final Function<Blockchain, RlpBlockExporter> rlpBlockExporterFactory, final RunnerBuilder runnerBuilder, final BesuController.Builder controllerBuilderFactory, final BesuPluginContextImpl besuPluginContext, final Map<String, String> environment, final StorageServiceImpl storageService, final SecurityModuleServiceImpl securityModuleService) { this.logger = logger; this.rlpBlockImporter = rlpBlockImporter; this.rlpBlockExporterFactory = rlpBlockExporterFactory; this.jsonBlockImporterFactory = jsonBlockImporterFactory; this.runnerBuilder = runnerBuilder; this.controllerBuilderFactory = controllerBuilderFactory; this.besuPluginContext = besuPluginContext; this.environment = environment; this.storageService = storageService; this.securityModuleService = securityModuleService; }
Example #7
Source File: HttpSender.java From iaf with Apache License 2.0 | 6 votes |
public static void streamResponseBody(InputStream is, String contentType, String contentDisposition, HttpServletResponse response, Logger log, String logPrefix, String redirectLocation) throws IOException { if (StringUtils.isNotEmpty(contentType)) { response.setHeader("Content-Type", contentType); } if (StringUtils.isNotEmpty(contentDisposition)) { response.setHeader("Content-Disposition", contentDisposition); } if (StringUtils.isNotEmpty(redirectLocation)) { response.sendRedirect(redirectLocation); } if (is != null) { try (OutputStream outputStream = response.getOutputStream()) { Misc.streamToStream(is, outputStream); log.debug(logPrefix + "copied response body input stream [" + is + "] to output stream [" + outputStream + "]"); } } }
Example #8
Source File: Scope.java From meghanada-server with GNU General Public License v3.0 | 6 votes |
public void dumpFieldAccess(final Logger logger) { for (final FieldAccess fa : this.fieldAccesses) { if (fa.returnType == null) { logger.warn("missing returnType {}", fa); } else { logger.trace("# {}", fa); } } for (final MethodCall mc : this.methodCalls) { if (mc.returnType == null) { logger.warn("missing returnType {}", mc); } else { logger.trace("# {}", mc); } } }
Example #9
Source File: PlottingUtils.java From gatk with BSD 3-Clause "New" or "Revised" License | 6 votes |
static <T extends Locatable> void validateContigs(final Map<String, Integer> contigLengthMap, final AbstractSampleLocatableCollection<T> locatableCollection, final File file, final Logger logger) { Utils.nonNull(contigLengthMap); Utils.nonNull(logger); if (locatableCollection == null) { Utils.validateArg(file == null, "File can only be null if collection is also null."); return; } final Set<String> contigNames = contigLengthMap.keySet(); final Set<String> fileContigNames = locatableCollection.getRecords().stream().map(T::getContig).collect(Collectors.toSet()); if (!contigNames.containsAll(fileContigNames)) { logger.warn(String.format("Contigs present in the file %s are missing from the sequence dictionary and will not be plotted.", file)); } final Map<String, Integer> fileContigMaxPositionMap = locatableCollection.getIntervals().stream().filter(i -> contigNames.contains(i.getContig())) .collect(Collectors.toMap(SimpleInterval::getContig, SimpleInterval::getEnd, Integer::max)); fileContigMaxPositionMap.forEach((c, integer) -> Utils.validateArg(integer <= contigLengthMap.get(c), String.format("Position present in the file %s exceeds contig length in the sequence dictionary.", file))); }
Example #10
Source File: SvDiscoverFromLocalAssemblyContigAlignmentsSpark.java From gatk with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * First parse the input alignments, then classify the assembly contigs based on their alignment signatures, * and return the contigs that are classified together for downstream inference. */ public static AssemblyContigsClassifiedByAlignmentSignatures preprocess(final SvDiscoveryInputMetaData svDiscoveryInputMetaData, final JavaRDD<GATKRead> assemblyRawAlignments) { final Broadcast<SAMFileHeader> headerBroadcast = svDiscoveryInputMetaData.getSampleSpecificData().getHeaderBroadcast(); final Broadcast<Set<String>> canonicalChromosomesBroadcast = svDiscoveryInputMetaData.getReferenceData().getCanonicalChromosomesBroadcast(); final Logger toolLogger = svDiscoveryInputMetaData.getToolLogger(); final JavaRDD<AssemblyContigWithFineTunedAlignments> contigsWithChimericAlignmentsReconstructed = AssemblyContigAlignmentsConfigPicker .createOptimalCoverageAlignmentSetsForContigs(assemblyRawAlignments, headerBroadcast.getValue(), canonicalChromosomesBroadcast.getValue(), 0.0, toolLogger) .cache(); toolLogger.info( contigsWithChimericAlignmentsReconstructed.count() + " contigs with chimeric alignments potentially giving SV signals."); return new AssemblyContigsClassifiedByAlignmentSignatures(contigsWithChimericAlignmentsReconstructed); }
Example #11
Source File: AbstractScriptFilterTest.java From logging-log4j2 with Apache License 2.0 | 6 votes |
@Test public void testJavascriptFilter() throws Exception { final Logger logger = LogManager.getLogger("TestJavaScriptFilter"); logger.traceEntry(); logger.info("This should not be logged"); ThreadContext.put("UserId", "JohnDoe"); logger.info("This should be logged"); ThreadContext.clearMap(); final ListAppender app = getContext().getListAppender("List"); final List<String> messages = app.getMessages(); try { assertNotNull("No Messages", messages); assertTrue("Incorrect number of messages. Expected 2, Actual " + messages.size(), messages.size() == 2); } finally { app.clear(); } }
Example #12
Source File: LogFactory.java From chronus with Apache License 2.0 | 6 votes |
/** * 获取Logger * * @param logger * @param clazz * @return */ public Logger createLogger(Logger logger, Class clazz) { String clKey = String.join("#", logger.getName(), clazz.getName()); Logger rl = loggerMap.get(clKey); if (rl != null) { return rl; } lock.lock(); try { if (!LogManager.exists(clKey)) { start(logger, clKey); loggerMap.put(clKey, LogManager.getLogger(clKey)); } } finally { lock.unlock(); } return loggerMap.get(clKey); }
Example #13
Source File: ThrowableProxyTest.java From logging-log4j2 with Apache License 2.0 | 6 votes |
/** * Attempts to instantiate a class that cannot initialize and then logs the stack trace of the Error. The logger * must not fail when using {@link ThrowableProxy} to inspect the frames of the stack trace. */ @Test public void testLogStackTraceWithClassThatCannotInitialize() { try { // Try to create the object, which will always fail during class initialization final AlwaysThrowsError error = new AlwaysThrowsError(); // If the error was not triggered then fail fail("Test did not throw expected error: " + error); } catch (final Throwable e) { // Print the stack trace to System.out for informational purposes // System.err.println("### Here's the stack trace that we'll log with log4j ###"); // e.printStackTrace(); // System.err.println("### End stack trace ###"); final Logger logger = LogManager.getLogger(getClass()); // This is the critical portion of the test. The log message must be printed without // throwing a java.lang.Error when introspecting the AlwaysThrowError class in the // stack trace. logger.error(e.getMessage(), e); logger.error(e); } }
Example #14
Source File: MemoryCircuitBreaker.java From crate with Apache License 2.0 | 6 votes |
/** * Create a circuit breaker that will break if the number of estimated * bytes grows above the limit. All estimations will be multiplied by * the given overheadConstant. Uses the given oldBreaker to initialize * the starting offset. * @param limit circuit breaker limit * @param overheadConstant constant multiplier for byte estimations * @param oldBreaker the previous circuit breaker to inherit the used value from (starting offset) */ public MemoryCircuitBreaker(ByteSizeValue limit, double overheadConstant, MemoryCircuitBreaker oldBreaker, Logger logger) { this.memoryBytesLimit = limit.getBytes(); this.overheadConstant = overheadConstant; if (oldBreaker == null) { this.used = new AtomicLong(0); this.trippedCount = new AtomicLong(0); } else { this.used = oldBreaker.used; this.trippedCount = oldBreaker.trippedCount; } this.logger = logger; if (logger.isTraceEnabled()) { logger.trace("Creating MemoryCircuitBreaker with a limit of {} bytes ({}) and a overhead constant of {}", this.memoryBytesLimit, limit, this.overheadConstant); } }
Example #15
Source File: FindBreakpointEvidenceSpark.java From gatk with BSD 3-Clause "New" or "Revised" License | 6 votes |
public static ReadMetadata buildMetadata( final FindBreakpointEvidenceSparkArgumentCollection params, final SAMFileHeader header, final JavaRDD<GATKRead> unfilteredReads, final SVReadFilter filter, final Logger logger ) { Utils.validate(header.getSortOrder() == SAMFileHeader.SortOrder.coordinate, "The reads must be coordinate sorted."); final Set<Integer> crossContigsToIgnoreSet; if ( params.crossContigsToIgnoreFile == null ) crossContigsToIgnoreSet = Collections.emptySet(); else crossContigsToIgnoreSet = readCrossContigsToIgnoreFile(params.crossContigsToIgnoreFile, header.getSequenceDictionary()); final ReadMetadata readMetadata = new ReadMetadata(crossContigsToIgnoreSet, header, params.maxTrackedFragmentLength, unfilteredReads, filter, logger); if ( params.metadataFile != null ) { ReadMetadata.writeMetadata(readMetadata, params.metadataFile); } return readMetadata; }
Example #16
Source File: ChatComponentParser.java From Angelia-core with GNU General Public License v3.0 | 6 votes |
private static ClickEvent parseClickEvent(JSONObject json, Logger logger) { String key = json.optString("action", null); if (key == null) { logger.warn("Received invalid click event with no action, ignoring it: " + json.toString()); return null; } String value = json.optString("value", null); if (value == null) { logger.warn("Received invalid click event with no value, ignoring it: " + json.toString()); return null; } switch (key.toLowerCase()) { case "open_url": return new ClickEvent(ClickEvent.Action.OPEN_URL, value); case "run_command": return new ClickEvent(ClickEvent.Action.RUN_COMMAND, value); case "suggest_command": return new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, value); case "change_page": return new ClickEvent(ClickEvent.Action.CHANGE_PAGE, value); default: logger.warn("Unknown key " + key + " for click event, ignoring it: " + json.toString()); return null; } }
Example #17
Source File: SvDiscoverFromLocalAssemblyContigAlignmentsSpark.java From gatk with BSD 3-Clause "New" or "Revised" License | 5 votes |
private static List<VariantContext> extractSimpleVariants(final JavaRDD<AssemblyContigWithFineTunedAlignments> contigsWithSimpleChimera, final SvDiscoveryInputMetaData svDiscoveryInputMetaData, final String outputPrefixWithSampleName) { final List<VariantContext> simpleVariants = SimpleNovelAdjacencyInterpreter.makeInterpretation(contigsWithSimpleChimera, svDiscoveryInputMetaData); final Logger logger = svDiscoveryInputMetaData.getDiscoverStageArgs().runInDebugMode ? svDiscoveryInputMetaData.getToolLogger() : null; SVVCFWriter.writeVCF(simpleVariants, outputPrefixWithSampleName + SIMPLE_CHIMERA_VCF_FILE_NAME, svDiscoveryInputMetaData.getReferenceData().getReferenceSequenceDictionaryBroadcast().getValue(), svDiscoveryInputMetaData.getDefaultToolVCFHeaderLines(), logger); return simpleVariants; }
Example #18
Source File: Store.java From crate with Apache License 2.0 | 5 votes |
/** * Returns <code>true</code> iff the given location contains an index an the index * can be successfully opened. This includes reading the segment infos and possible * corruption markers. */ public static boolean canOpenIndex(Logger logger, Path indexLocation, ShardId shardId, NodeEnvironment.ShardLocker shardLocker) throws IOException { try { tryOpenIndex(indexLocation, shardId, shardLocker, logger); } catch (Exception ex) { logger.trace(() -> new ParameterizedMessage("Can't open index for path [{}]", indexLocation), ex); return false; } return true; }
Example #19
Source File: LoggerTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
private static void checkMessageFactory(final MessageFactory messageFactory, final Logger testLogger) { if (messageFactory == null) { assertEquals(AbstractLogger.DEFAULT_MESSAGE_FACTORY_CLASS, testLogger.getMessageFactory().getClass()); } else { MessageFactory actual = testLogger.getMessageFactory(); assertEquals(messageFactory, actual); } }
Example #20
Source File: StructuralVariationDiscoveryPipelineSpark.java From gatk with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Uses the input EvidenceTargetLinks to * <ul> * <li> * either annotate the variants called from assembly discovery with split read and read pair evidence, or * </li> * <li> * to call new imprecise variants if the number of pieces of evidence exceeds a given threshold. * </li> * </ul> * */ private static List<VariantContext> processEvidenceTargetLinks(List<VariantContext> assemblyBasedVariants, final SvDiscoveryInputMetaData svDiscoveryInputMetaData) { final List<VariantContext> annotatedVariants; if (svDiscoveryInputMetaData.getSampleSpecificData().getEvidenceTargetLinks() != null) { final PairedStrandedIntervalTree<EvidenceTargetLink> evidenceTargetLinks = svDiscoveryInputMetaData.getSampleSpecificData().getEvidenceTargetLinks(); final ReadMetadata readMetadata = svDiscoveryInputMetaData.getSampleSpecificData().getReadMetadata(); final ReferenceMultiSparkSource reference = svDiscoveryInputMetaData.getReferenceData().getReferenceBroadcast().getValue(); final DiscoverVariantsFromContigAlignmentsSparkArgumentCollection discoverStageArgs = svDiscoveryInputMetaData.getDiscoverStageArgs(); final Logger toolLogger = svDiscoveryInputMetaData.getToolLogger(); // annotate with evidence links annotatedVariants = AnnotatedVariantProducer. annotateBreakpointBasedCallsWithImpreciseEvidenceLinks(assemblyBasedVariants, evidenceTargetLinks, readMetadata, reference, discoverStageArgs, toolLogger); // then also imprecise deletion final List<VariantContext> impreciseVariants = ImpreciseVariantDetector. callImpreciseDeletionFromEvidenceLinks(evidenceTargetLinks, readMetadata, reference, discoverStageArgs.impreciseVariantEvidenceThreshold, discoverStageArgs.maxCallableImpreciseVariantDeletionSize, toolLogger); annotatedVariants.addAll(impreciseVariants); } else { annotatedVariants = assemblyBasedVariants; } return annotatedVariants; }
Example #21
Source File: FileAppenderWithLocationBenchmark.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Setup public void setUp() throws Exception { System.setProperty("log4j.configurationFile", "log4j2-perfloc.xml"); System.setProperty("log4j.configuration", "log4j12-perfloc.xml"); System.setProperty("logback.configurationFile", "logback-perfloc.xml"); deleteLogFiles(); log4j2Logger = LogManager.getLogger(FileAppenderWithLocationBenchmark.class); log4j2RandomLogger = LogManager.getLogger("TestRandom"); slf4jLogger = LoggerFactory.getLogger(FileAppenderWithLocationBenchmark.class); log4j1Logger = org.apache.log4j.Logger.getLogger(FileAppenderWithLocationBenchmark.class); }
Example #22
Source File: XMLConfigLogIntegrationTest.java From tutorials with MIT License | 5 votes |
@Test public void givenXMLConfigurationPlugin_whenSimpleLog_ThenLogsCorrectly() throws Exception { Logger logger = LogManager.getLogger(this.getClass()); LoggerContext ctx = (LoggerContext) LogManager.getContext(); logger.debug("Debug log message"); logger.info("Info log message"); logger.error("Error log message"); }
Example #23
Source File: LoggingExtension.java From tutorials with MIT License | 5 votes |
@Override public void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception { Logger logger = LogManager.getLogger(testInstance.getClass()); testInstance.getClass() .getMethod("setLogger", Logger.class) .invoke(testInstance, logger); }
Example #24
Source File: PluginsService.java From crate with Apache License 2.0 | 5 votes |
private static void logPluginInfo(final List<PluginInfo> pluginInfos, final String type, final Logger logger) { assert pluginInfos != null; if (pluginInfos.isEmpty()) { logger.info("no " + type + "s loaded"); } else { for (final String name : pluginInfos.stream().map(PluginInfo::getName).sorted().collect(Collectors.toList())) { logger.info("loaded " + type + " [" + name + "]"); } } }
Example #25
Source File: QueueFullAsyncLoggerConfigLoggingFromToStringTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Test(timeout = 5000) public void testLoggingFromToStringCausesOutOfOrderMessages() throws InterruptedException { //TRACE = true; final Logger logger = LogManager.getLogger(this.getClass()); blockingAppender.countDownLatch = new CountDownLatch(1); unlocker = new Unlocker(new CountDownLatch(129)); // count slightly different from "pure" async loggers unlocker.start(); asyncLoggerConfigRecursiveTest(logger, unlocker, blockingAppender, this); }
Example #26
Source File: JdbcAppenderMapMessageDataSourceTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Test public void testDataSourceConfig() throws Exception { try (final Connection connection = jdbcRule.getConnectionSource().getConnection()) { final Error exception = new Error("Final error massage is fatal!"); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final PrintWriter writer = new PrintWriter(outputStream); exception.printStackTrace(writer); writer.close(); final Logger logger = LogManager.getLogger(this.getClass().getName() + ".testDataSourceConfig"); MapMessage mapMessage = new MapMessage(); mapMessage.with("Id", 1); mapMessage.with("ColumnA", "ValueA"); mapMessage.with("ColumnB", "ValueB"); logger.info(mapMessage); try (final Statement statement = connection.createStatement(); final ResultSet resultSet = statement .executeQuery("SELECT Id, ColumnA, ColumnB FROM dsLogEntry ORDER BY Id")) { assertTrue("There should be at least one row.", resultSet.next()); Assert.assertEquals(1, resultSet.getInt("Id")); assertFalse("There should not be two rows.", resultSet.next()); } } }
Example #27
Source File: RootThrowableTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Test public void testException() { final Logger logger = context.getLogger("LoggerTest"); final Throwable cause = new NullPointerException("null pointer"); final Throwable parent = new IllegalArgumentException("IllegalArgument", cause); logger.error("Exception", parent); final List<String> msgs = app.getMessages(); assertNotNull(msgs); assertEquals("Incorrect number of messages. Should be 1 is " + msgs.size(), 1, msgs.size()); assertTrue("No suppressed lines", msgs.get(0).contains("suppressed")); app.clear(); }
Example #28
Source File: ExceptionsHelper.java From crate with Apache License 2.0 | 5 votes |
/** * Unwrap the specified throwable looking for any suppressed errors or errors as a root cause of the specified throwable. * * @param cause the root throwable * @return an optional error if one is found suppressed or a root cause in the tree rooted at the specified throwable */ public static Optional<Error> maybeError(final Throwable cause, final Logger logger) { // early terminate if the cause is already an error if (cause instanceof Error) { return Optional.of((Error) cause); } final Queue<Throwable> queue = new LinkedList<>(); queue.add(cause); int iterations = 0; while (queue.isEmpty() == false) { iterations++; // this is a guard against deeply nested or circular chains of exceptions if (iterations > MAX_ITERATIONS) { logger.warn("giving up looking for fatal errors", cause); break; } final Throwable current = queue.remove(); if (current instanceof Error) { return Optional.of((Error) current); } Collections.addAll(queue, current.getSuppressed()); if (current.getCause() != null) { queue.add(current.getCause()); } } return Optional.empty(); }
Example #29
Source File: TexturePackLoader.java From Angelia-core with GNU General Public License v3.0 | 5 votes |
public void load(Logger logger, File f) throws ResourcePackParseException { if (!f.isDirectory()) { throw new ResourcePackParseException("Given path was not an existing directory"); } File assets = new File(f, "assets"); if (!assets.isDirectory()) { throw new ResourcePackParseException("assets/ folder not found"); } File minecraft = new File(assets, "minecraft"); if (!minecraft.isDirectory()) { throw new ResourcePackParseException("assets/minecraft/ folder not found"); } File blockStates = new File(minecraft, "blockstates"); if (!blockStates.isDirectory()) { throw new ResourcePackParseException("assets/minecraft/blockstates/ folder not found"); } File models = new File(minecraft, "models"); if (!models.isDirectory()) { throw new ResourcePackParseException("assets/minecraft/models/ folder not found"); } File textures = new File(minecraft, "textures"); if (!textures.isDirectory()) { throw new ResourcePackParseException("assets/minecraft/textures/ folder not found"); } // Map<String, BufferedImage> textureMap = loadTextures("", textures, logger); // Map<String, JSONObject> blockStateMap = loadJSONFolder("", blockStates, // logger); modelMap = loadJSONFolder("", models, logger); modelMap = resolveModelDependencies(modelMap, logger); }
Example #30
Source File: AwsEc2ServiceImpl.java From crate with Apache License 2.0 | 5 votes |
static ClientConfiguration buildConfiguration(Logger logger, Ec2ClientSettings clientSettings) { final ClientConfiguration clientConfiguration = new ClientConfiguration(); // the response metadata cache is only there for diagnostics purposes, // but can force objects from every response to the old generation. clientConfiguration.setResponseMetadataCacheSize(0); clientConfiguration.setProtocol(clientSettings.protocol); if (Strings.hasText(clientSettings.proxyHost)) { // TODO: remove this leniency, these settings should exist together and be validated clientConfiguration.setProxyHost(clientSettings.proxyHost); clientConfiguration.setProxyPort(clientSettings.proxyPort); clientConfiguration.setProxyUsername(clientSettings.proxyUsername); clientConfiguration.setProxyPassword(clientSettings.proxyPassword); } // Increase the number of retries in case of 5xx API responses final Random rand = Randomness.get(); final RetryPolicy retryPolicy = new RetryPolicy( RetryPolicy.RetryCondition.NO_RETRY_CONDITION, (originalRequest, exception, retriesAttempted) -> { // with 10 retries the max delay time is 320s/320000ms (10 * 2^5 * 1 * 1000) logger.warn("EC2 API request failed, retry again. Reason was:", exception); return 1000L * (long) (10d * Math.pow(2, retriesAttempted / 2.0d) * (1.0d + rand.nextDouble())); }, 10, false); clientConfiguration.setRetryPolicy(retryPolicy); clientConfiguration.setSocketTimeout(clientSettings.readTimeoutMillis); return clientConfiguration; }