I'm trying to set up a freemarker template to show the results of a SQL query. I'm running into an issue where Intellij is reporting that the template cannot be found:
DEBUG [2018-02-27 18:52:31,623] freemarker.cache: Couldn't find template in cache for "com/example/www/resources/template.ftl"("en_US", ISO-8859-1, parsed); will try to load it.
DEBUG [2018-02-27 18:52:31,624] freemarker.cache: TemplateLoader.findTemplateSource("com/example/www/resources/template_en_US.ftl"): Not found
DEBUG [2018-02-27 18:52:31,626] freemarker.cache: TemplateLoader.findTemplateSource("com/example/www/resources/template_en.ftl"): Not found
DEBUG [2018-02-27 18:52:31,627] freemarker.cache: TemplateLoader.findTemplateSource("com/example/www/resources/template.ftl"): Not found
DEBUG [2018-02-27 18:52:31,661] org.eclipse.jetty.server.handler.gzip.GzipHttpOutputInterceptor: org.eclipse.jetty.server.handler.gzip.GzipHttpOutputInterceptor#f62788 exclude by status 404
DEBUG [2018-02-27 18:52:31,662] org.eclipse.jetty.server.HttpChannel: sendResponse info=null content=HeapByteBuffer#d1e062[p=0,l=248,c=32768,r=248]={<<<<html>\n<head>\n<me.../body>\n</html>\n>>>\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00...\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00} complete=true committing=true callback=Blocker#4fab4a{null}
DEBUG [2018-02-27 18:52:31,662] org.eclipse.jetty.server.HttpChannel: COMMIT for /address/3 on HttpChannelOverHttp#a67c6b{r=1,c=true,a=DISPATCHED,uri=//localhost:8080/address/3}
404 Not Found HTTP/1.1
Date: Tue, 27 Feb 2018 18:52:31 GMT
Cache-Control: must-revalidate,no-cache,no-store
Content-Type: text/html;charset=iso-8859-1
This happened when my main method in my app class was set up like so:
public class AppApplication extends Application<AppConfiguration> {
public static void main(final String[] args) throws Exception {
new AppApplication().run(args);
}
Under this setup, navigating to the URL that returns an address database returns a 404 error in my browser and the above logs in debug mode.
Additional research into using Freemarker in Dropwizard led me to setting up a Configuration instance in the main method of the app to look for the template with setDirectoryForTemplateLoading, to point to the path, and to use getTemplate to return the template file itself:
public class AppApplication extends Application<AppConfiguration> {
public static void main(final String[] args) throws Exception {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_27);
cfg.setDirectoryForTemplateLoading(new File("C:\\IdeaProjects\\App\\src\\main\\resources"));
cfg.getTemplate("template.ftl");
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
cfg.setLogTemplateExceptions(false);
cfg.setWrapUncheckedExceptions(true);
new AppApplication().run(args);
}
However, going to the URL returns the same error. The only discernible difference in this case is that the info for the error is printed at the top of the console as the server starts:
14:09:24.891 [main] DEBUG freemarker.cache - Couldn't find template in cache for "template.ftl"("en_US", UTF-8, parsed); will try to load it.
14:09:24.907 [main] DEBUG freemarker.cache - TemplateLoader.findTemplateSource("template_en_US.ftl"): Not found
14:09:24.907 [main] DEBUG freemarker.cache - TemplateLoader.findTemplateSource("template_en.ftl"): Not found
14:09:24.907 [main] DEBUG freemarker.cache - TemplateLoader.findTemplateSource("template.ftl"): Found
14:09:24.922 [main] DEBUG freemarker.cache - Loading template for "template.ftl"("en_US", UTF-8, parsed) from "C:\\IdeaProjects\\App\\src\\main\\resources\\template.ftl"
At the end, it shows that is it loading the template from the resource folder; However, trying to run the getter methods I've defined returns the same error later on in the console. Can anyone give me some insight on this? I don't think its an issue with my code, but rather that the .ftl file isn't regestering to Intellij.
Edit: Here is my View Bundle, under initialize.:
bootstrap.addBundle(new ViewBundle<AppConfiguration>() {
public Map<String, Map<String, String>> getViewConfiguration(AppConfiguration configuration) {
return configuration.getViewRendererConfiguration();
}
});
Related
When writing the logs of a war into payara server logs, it was not able to determine/identify the Logger name.
When I see it on the admin console, the Logger value us blank, and it is printing Log Level as SEVERE even it is just an INFO level log.
Following is the entry in payara server
Log Entry Detail
Timestamp : Mar 25, 2022 12:37:03.439
Log Level : SEVERE
Logger :
Name-Value Pairs : {levelValue=1000, timeMillis=1648211823439}
Record Number : 679
Message ID :
Complete Message : [http-thread-pool::http-listener-1(18)] INFO com.test.LogTest - com.test.LogTest
Sample code looks like the following
public class LogTest {
static Logger logger = LoggerFactory.getLogger(LogTest.class);
public static void main(String[] args) {
logger.info(logger.getName());
logger.debug("debug");
logger.info("info");
}
}
In my local I was able to get the following output
[main] INFO com.test.LogTest - com.test.LogTest
[main] DEBUG com.test.LogTest - debug
[main] INFO com.test.LogTest - info
I am using SimpleLogger (slf4j) as the logging library
Please help me on how to set the Logger value in the payara server logs, for the logs that I am logging
I'm trying to connect to S3 bucket and download files but the code throws exception:
In My code I have
ProfileCredentialsProvider pcp = new ProfileCredentialsProvider("assumed_role");
bucketName = "dev-data-extract-service-bucket";
s3Client = AmazonS3ClientBuilder.standard().withCredentials(pcp).withRegion(Regions.US_EAST_1.toString()).build();
I get NullPointerException exception on calling the following line:
fullObject = s3Client.getObject(new GetObjectRequest(bucketName, "TR09_20190205.detail"));
The reason is that host value in Endpoint is null
this is from AmazonS3Client class
private boolean isStandardEndpoint(URI endpoint) {
return endpoint.getHost().endsWith("s3.amazonaws.com");
}
And following is the stack trace
[main] DEBUG com.amazonaws.AmazonWebServiceClient - Internal logging
successfully configured to commons logger: true 15:43:45.183 [main]
DEBUG com.amazonaws.metrics.AwsSdkMetrics - Admin mbean registered
under com.amazonaws.management:type=AwsSdkMetrics 15:43:45.952 [main]
DEBUG com.amazonaws.monitoring.CsmConfigurationProviderChain - Unable
to load configuration from
com.amazonaws.monitoring.EnvironmentVariableCsmConfigurationProvider#169e6180:
Unable to load Client Side Monitoring configurations from environment
variables! 15:43:45.952 [main] DEBUG
com.amazonaws.monitoring.CsmConfigurationProviderChain - Unable to
load configuration from
com.amazonaws.monitoring.SystemPropertyCsmConfigurationProvider#35aea049:
Unable to load Client Side Monitoring configurations from system
properties variables! 15:43:45.952 [java-sdk-http-connection-reaper]
DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager -
Closing connections idle longer than 60000 MILLISECONDS 15:43:45.952
[main] DEBUG com.amazonaws.monitoring.CsmConfigurationProviderChain -
Unable to load configuration from
com.amazonaws.monitoring.ProfileCsmConfigurationProvider#611889f4:
Unable to load config file Exception in thread "main"
java.lang.NullPointerException at
com.amazonaws.services.s3.AmazonS3Client.isStandardEndpoint(AmazonS3Client.java:3772)
at
com.amazonaws.services.s3.AmazonS3Client.noExplicitRegionProvided(AmazonS3Client.java:3767)
at
com.amazonaws.services.s3.AmazonS3Client.bucketRegionShouldBeCached(AmazonS3Client.java:4505)
at
com.amazonaws.services.s3.AmazonS3Client.shouldPerformHeadRequestToFindRegion(AmazonS3Client.java:4501)
at
com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4426)
at
com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4390)
at
com.amazonaws.services.s3.AmazonS3Client.getAcl(AmazonS3Client.java:3573)
at
com.amazonaws.services.s3.AmazonS3Client.getBucketAcl(AmazonS3Client.java:1186)
at
com.amazonaws.services.s3.AmazonS3Client.getBucketAcl(AmazonS3Client.java:1176)
at
com.amazonaws.services.s3.AmazonS3Client.doesBucketExistV2(AmazonS3Client.java:1312)
at .AWSHelper.downloadFromS3Bucket(AWSHelper.java:32) at
.AWSHelper.main(AWSHelper.java:59)
I think your issue stems from way you are setting the region. I think the region is resolving to null and that this is causing your endpoint to be null.
Instead of:
s3Client = AmazonS3ClientBuilder.standard().withCredentials(pcp).withRegion(Regions.US_EAST_1.toString()).build();
Try:
s3Client = AmazonS3ClientBuilder.standard().withCredentials(pcp).withRegion(Regions.US_EAST_1).build();
The Regions class does not override the toString() method so it will not return the region name, which is what would be required for your code to work as it is.
I am trying to add a logger to one of my programs, mainly to replace the System.out.println(), and it seems to give me some problems.
This is my first time using a logger, so I am a noob at it.
I had a look at a multitude of links over the past days but still haven't managed to make my logger catch an exception; here are some of the links I looked at (some of them are 5 years old and might need updates):
oracle simple formatter
slf4j - interface logger
slf4j - simple logger
slf4j - faq
slf4j - message formatter
stackoverflow 1
stackoverflow 2
I am using:
slf4j-api-1.7.22.jar
slf4j-simple-1.7.22.jar
jdk1.8.0_71
IntelliJ 2016.3.2
The simpleLogger.properties is placed directly in the resources package, this file is loaded before the logger is created, the file is loaded correctly as I can modify the date-time as I need it to be (and other settings work as well).
Part of the Main class:
...
private Logger LOG; //field
...
public static void main(String[] args) {
launch(args);
}
...
#Override
public void start(Stage primaryStage) {
/*Create logger*/
createLogger();
LOG.info("Stage start.");
...
}
...
private void createLogger() {
try {
Properties properties = new Properties();
properties.load(LOGGER_PROPERTIES); //path to prop file
} catch (IOException e) {
e.printStackTrace();
}
LOG = LoggerFactory.getLogger(Main.class);
LOG.info("Logger initialised.");
LOG.trace("test trace"); //not working
LOG.debug("test debug"); //not working
LOG.info("test info");
LOG.warn("test warning");
LOG.error("test error");
}
The simpleLogger.properties file:
org.slf4j.simpleLogger.logFile=System.out
# org.slf4j.simpleLogger.defaultLogLevel=
# org.slf4j.simpleLogger.log.a.b.c=
org.slf4j.simpleLogger.showDateTime=true
org.slf4j.simpleLogger.dateTimeFormat=HH:mm:ss:SSS
org.slf4j.simpleLogger.showThreadName=false
org.slf4j.simpleLogger.showLogName=false
org.slf4j.simpleLogger.showShortLogName=true
org.slf4j.simpleLogger.levelInBrackets=true
# org.slf4j.simpleLogger.warnLevelString=
# THE FORMAT TRIED
#org.slf4j.simpleLogger.SimpleFormatter.format = [%1$tc] %4$s: %2$s - %5$s %6$s%n
#java.util.logging.SimpleFormatter.format = [%1$tc] %4$s: %2$s - %5$s %6$s%n
#java.util.logging.SimpleFormatter.format="%1$tc %2$s%n%4$s: %5$s%6$s%n"
#org.slf4j.simpleLogger.format=[%1$tc] %4$s: %2$s - %5$s %6$s%n %7$s
#org.slf4j.helpers.MessageFormatter.format = [%1$tc] %4$s: %2$s - %5$s %6$s%n %7$s
#java.util.logging.SimpleFormatter.format="%1$tc %2$s%n%4$s: %5$s%6$s%n"
Part of the class where I am attempting to create an exception:
LOG.info("Creating window - More info: loading.. .fxml");
try {
BP_INFO = FXMLLoader.load(getClass().getResource("/fxml/ImageInf_.fxml")); //HERE change back to ImageInfo.fxml
LOG.info("Creating window - More info: loaded .fxml successfully.");
} catch (IOException e) {
// HERE not showing anything below
System.out.println("CATCH - From Sys out");
LOG.error("CATCH - EXCEPTION", (Throwable) e);
LOG.error("Creating window - More info: Exception");
LOG.error("Creating window - More info: Exception", e);
LOG.error("Creating window - More info: Exception {}", e);
LOG.error("Creating window - More info: Exception {} {} {}", Level.INFO, e.getMessage(), e);
// e.printStackTrace();
}
Console output:
12:17:08:995 [INFO] Main - Logger initialised.
12:17:08:996 [INFO] Main - test info
12:17:08:997 [WARN] Main - test warning
12:17:08:997 [ERROR] Main - test error
12:17:08:997 [INFO] Main - Stage start.
...
12:17:27:140 [INFO] View - Creating window - More info: loading.. .fxml
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
...
Problem 1:
As you can see trace and debug are not working. I have tried all the properties in the prop. file and some more as well but so far did not manage to catch any exception or apply a specific format.
Problem 2:
As you can see, the exception is also not logged at all.
Additional info: I have reset IntelliJ settings, I have been cleaning the win %temp% folder various times, I have been cleaning caches and restarted Intellij various times; all this in an attempt if the prop. file was not read correctly or kept somewhere in a cache.
Any help is much appreciated. Please respond in a simplistic way.
We may use Slf4j within a JavaFX project by using only these dependencies:
slf4j-api-1.7.22.jar
slf4j-simple-1.7.22.jar
Here's an example Application class:
...
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Todo extends Application {
private static final Logger log = LoggerFactory.getLogger(Todo.class);
...
public static void main(String[] args) {
log.info("launching...");
log.warn("launching...");
log.error("launching...");
log.debug("launching...");
log.trace("launching...");
launch(args);
}
}
Slf4j simple already has default settings that may be fine for various scenarios. That not being the case, the logger may be configured by adding simplelogger.properties to the classpath, which will be automatically picked up by Slf4j on application startup. The javadoc for the SimpleLogger class nicely enlists all the properties that may be configured.
The contents of a simplelogger.properties file that modifies the log level only:
org.slf4j.simpleLogger.defaultLogLevel=trace
And here is the output when running with the log level set to trace:
[main] INFO todo.Todo - launching...
[main] WARN todo.Todo - launching...
[main] ERROR todo.Todo - launching...
[main] DEBUG todo.Todo - launching...
[main] TRACE todo.Todo - launching...
Problem #1 (trace and debug level is not logged)
From the doc of SimpleLogger:
org.slf4j.simpleLogger.defaultLogLevel - Default log level for all
instances of SimpleLogger. Must be one of ("trace", "debug", "info",
"warn", "error" or "off"). If not specified, defaults to "info".
Because the defult level is info, and trace and debug levels are "under" info, they will be filtered out by the logger and will not reach the appender.
So if you add the following line in the properties file:
org.slf4j.simpleLogger.defaultLogLevel = trace
you should see also messages with trace and debug level.
Problem #2 (the error trace is not logged properly)
You are catching IOExceptions, but an InvocationTargetException is actually thrown (which one is not catched), therefore the execution will never enter your catch block. What you see on the console is an unhandled runtime exception printed.
As described here, there could be per user configuration of Maven logging for one installation.
I copied default simplelogger.properties to $M2_HOME/conf/logging and added:
org.slf4j.simpleLogger.log.com.example=trace
and it logs fine.
This is not maybe the best solution, but the one I've found fitting my needs. You can log DEBUG but not TRACE as I remember I've read somewhere.
Using scala and spark, i try to build simple apps. To avoid too many logs, i have setLevel Log to Level.ERROR, but it seems all log still appear. Here're my codes :
import org.apache.log4j.{BasicConfigurator, Level, Logger}
import org.apache.spark.{SparkConf, SparkContext}
/**
* Created by hduser on 16/08/16.
*/
object ALS_Test {
def main(command : Array[String]): Unit =
{
Logger.getRootLogger
Logger.getLogger(this.getClass).setLevel(Level.ERROR)
Logger.getLogger("org.spark_project").setLevel(Level.ERROR)
BasicConfigurator.configure()
val sparkConf = new SparkConf().setAppName("AppName").setMaster("local[4]")
val sc = new SparkContext(sparkConf)
println("test 123")
}
}
The Output when running still have many confused logs :
0 [main] INFO org.apache.spark.SparkContext - Running Spark version 2.0.0
163 [main] DEBUG org.apache.hadoop.metrics2.lib.MutableMetricsFactory - field org.apache.hadoop.metrics2.lib.MutableRate org.apache.hadoop.security.UserGroupInformation$UgiMetrics.loginSuccess with annotation #org.apache.hadoop.metrics2.annotation.Metric(always=false, about=, sampleName=Ops, type=DEFAULT, value=[Rate of successful kerberos logins and latency (milliseconds)], valueName=Time)
175 [main] DEBUG org.apache.hadoop.metrics2.lib.MutableMetricsFactory - field org.apache.hadoop.metrics2.lib.MutableRate org.apache.hadoop.security.UserGroupInformation$UgiMetrics.loginFailure with annotation #org.apache.hadoop.metrics2.annotation.Metric(always=false, about=, sampleName=Ops, type=DEFAULT, value=[Rate of failed kerberos logins and latency (milliseconds)], valueName=Time)
176 [main] DEBUG org.apache.hadoop.metrics2.lib.MutableMetricsFactory - field org.apache.hadoop.metrics2.lib.MutableRate org.apache.hadoop.security.UserGroupInformation$UgiMetrics.getGroups with annotation #org.apache.hadoop.metrics2.annotation.Metric(always=false, about=, sampleName=Ops, type=DEFAULT, value=[GetGroups], valueName=Time)
177 [main] DEBUG org.apache.hadoop.metrics2.impl.MetricsSystemImpl - UgiMetrics, User and group related metrics
555 [main] DEBUG org.apache.hadoop.util.Shell - Failed to detect a valid hadoop home directory
java.io.IOException: HADOOP_HOME or hadoop.home.dir are not set.
I'm trying to implement HTML5 routing with Spring-boot and Angular 1.5, following this article.
At some point I need to redirect all the angular routes to the base path with a controller like this:
#Controller
public class UrlController {
// Match everything without a suffix (so not a static resource)
#RequestMapping(value = "/{path:[^\\.]*}"))
public String redirect(HttpServletRequest request) {
// Forward to home page so that route is preserved.
return "forward:/";
}
}
While the regular expression matches most of the URLS, like dashboard, search etc:
2016-08-05 16:39:58 DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping:306 - Looking up handler method for path /dashboard
2016-08-05 16:39:58 DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping:313 - Returning handler method UrlController.redirect(javax.servlet.http.HttpServletRequest,java.lang.String)]
2016-08-05 16:39:58 DEBUG o.s.b.f.s.DefaultListableBeanFactory:251 - Returning cached instance of singleton bean 'urlController'
2016-08-05 16:39:58 DEBUG o.s.w.s.DispatcherServlet:947 - Last-Modified value for [/dashboard] is: -1
2016-08-05 16:39:58 DEBUG c.a.a.w.i.LoggingInterceptor:22 - Start processing url request: https://localhost:8443/dashboard
redirecting to home page from url https://localhost:8443/dashboard
2016-08-05 16:39:58 DEBUG c.a.a.w.i.LoggingInterceptor:35 - Finished processing url request: https://localhost:8443/dashboard, duration: 0[ms]
Others are ignored and not matched at all, like https://localhost:8443/faults/64539352
2016-08-05 17:00:05 DEBUG o.s.w.s.DispatcherServlet:861 - DispatcherServlet with name 'dispatcherServlet' processing GET request for [/faults/64539352]
2016-08-05 17:00:05 DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping:306 - Looking up handler method for path /faults/64539352
2016-08-05 17:00:05 DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping:316 - Did not find handler method for [/faults/64539352]
The regular expression seems to be fine if you test it in regexplanet
, but it does not match what I want if I put it in the #RequestMapping.
Does anybody know how to make it work, or even better how to do it without regular expressions?
The problem and solution is described here. The solution consist in the implementation of a OncePerRequestFilter where you can match the full URI against whatever you want.
You can use a correct PathMatcher to do the job: {path:(?:(?!api|.).)*}/**
More info here