I'm starting in the play framework with Java and downloaded the project from the official website: https://github.com/playframework/play-java-rest-api-example/tree/2.5.x
I joined the eclipse as it says at: https://www.playframework.com/documentation/2.5.x/IDE
And run the command: sbt run
It worked. However, if I send a post to the given address, I get the message "Unauthorized".
Does anyone know if I have to do anything else?
Thank you very much in advance.
This is workin for me .
#Singleton
public class Filters implements HttpFilters {
private final Environment env;
private final EssentialFilter exampleFilter;
#Inject
public Filters(Environment env, ExampleFilter exampleFilter) {
this.env = env;
this.exampleFilter = exampleFilter;
}
#Override
public EssentialFilter[] filters() {
if (env.mode().equals(Mode.DEV)) {
return new EssentialFilter[] { exampleFilter };
} else {
return new EssentialFilter[] {};
}
}
}
I found out. I have not yet studied Filters, but I left it that way and it worked:
another way is to configure it in the application.conf file, just add the lines
play.filters.disabled +="play.filters.cors.CORSFilter"
Related
Initial situation
I'm currently building an API with Spring using the library PipelinR, which is inspired by the famous NuGet package MediatR. I've created multiple packages within this application to isolate the java classes. The entrypoint of the API is in the package com.example.project.WebApi. The configuration file for the pipeline is also located here.
#Configuration
public class PipelinrConfiguration {
#Bean
Pipeline pipeline(ObjectProvider<Command.Handler> commandHandlers, ObjectProvider<Notification.Handler> notificationHandlers, ObjectProvider<Command.Middleware> middlewares) {
return new Pipelinr()
.with(commandHandlers::stream)
.with(notificationHandlers::stream)
.with(middlewares::orderedStream);
}
}
Anyways all the commands and command handlers are in different packages, like com.example.project.ApplicationService.CreateSomethingCommand.
com.example.project.ApplicationService.CreateSomething/
CreateSomethingCommand.java
CreateSomethingCommandHandler.java
Does anybody knows how I could provide these classes in my PipelinrConfiguration.java file, so that the ObjectProvider is able to find those.
I highly appreciate any kind of help, cheers!
Edit: #001
Yes, the beans are annotated with #Component.
CreateSomethingCommand.java
public class CreateSomethingCommand implements Command<Voidy> {
public String host;
public CreateSomethingCommand() {
}
public CreateSomethingCommand(String host) {
this();
this.host = host;
}
}
CreateSomethingCommandHandler.java
#Component
public class CreateSomethingCommandHandler implements Command.Handler<CreateSomethingCommand, Voidy> {
#Override
public Voidy handle(CreateSomethingCommand command) {
System.out.println("Command recieved by " + command.host);
return null;
}
}
#Configuration
#ComponentScan(basePackages = {"package1”, "package2"})
public class PipelinrConfiguration {
// attention here you have to declare three different beans of type ObjectProvider otherwise it will inject by type
#Bean
Pipeline pipeline(#Qualifier(“bean1”) ObjectProvider<Command.Handler> commandHandlers, #Qualifier(“bean2”) ObjectProvider<Notification.Handler> notificationHandlers, #Qualifier(“bean3”) ObjectProvider<Command.Middleware> middlewares) {
return new Pipelinr()
.with(commandHandlers::stream)
.with(notificationHandlers::stream)
.with(middlewares::orderedStream);
}
}
I have an application with management.server enabled:
management.server.port=8081
When I start application, I have:
10 threads for 8080 HTTP nio connector
10 threads for 8081 HTTP nio connector
But I would like to reduce min-spare only for management (8081) and not for the web application (8080)
Looking at Spring code, it seems it's not possible, can someone confirm ?
EDIT: The approach below is not sufficient as the ManagementWebServerFactoryCustomizer is also a ConfigurableWebServerFactory and will thus be applied to the main server.
Adding logic to check againgst the management port is not helping as the management context has its very own wiring and won't pick up the bean.
Looks like it's not possible to hook into the management server configuration easily (would be easier if ServletManagementContextFactory were public).
You can look into ServletManagementChildContextConfiguration to see how the management server is wired.
You could hook into the management server configuration by providing a ManagementWebServerFactoryCustomizer like this (not sure if there's an easier way):
#Configuration
public class TomcatManagementCustomizerConfiguration {
#Bean
ManagementWebServerFactoryCustomizer<ConfigurableServletWebServerFactory> servletManagementWebServerFactoryCustomizer(
#Value("${management.server.threads.min-spare:5}") int managementMinSpareThreads,
ListableBeanFactory beanFactory) {
return new TomcatManagementCustomizer(beanFactory, managementMinSpareThreads);
}
static class TomcatManagementCustomizer extends ManagementWebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
private final int managementMinSpareThreads;
protected TomcatManagementCustomizer(ListableBeanFactory beanFactory, int managementMinSpareThreads) {
super(beanFactory, TomcatWebServerFactoryCustomizer.class);
this.managementMinSpareThreads = managementMinSpareThreads;
}
#Override
#SuppressWarnings("rawtypes")
protected void customize(ConfigurableServletWebServerFactory factory, ManagementServerProperties managementServerProperties, ServerProperties serverProperties) {
super.customize(factory, managementServerProperties, serverProperties);
((TomcatServletWebServerFactory) factory).addConnectorCustomizers((connector) -> {
ProtocolHandler handler = connector.getProtocolHandler();
if (handler instanceof AbstractProtocol) {
AbstractProtocol protocol = (AbstractProtocol) handler;
protocol.setMinSpareThreads(managementMinSpareThreads);
}
});
}
}
}
Can you not just put the following in either properties file or YAML file?
Or is there something I misunderstood?
server.tomcat.threads.min-spare=2
(This is for properties file)
Just to verify (You don't need this as you have been checking the updated value in the log)
Put the following in either properties file or YAML file
management.endpoints.web.exposure.include=health,info,metrics,env
(This is for properties file)
And visit /actuator/env/server.tomcat.threads.min-spare
You need actuator dependency for the link above to work.
You can use #ManagementConfigurationContext and add the configuration class to to your META-INF/spring.properties file.
It is also important to place the configuration class in a package which is not the main package or sub-package of your main application context. This is so that this configuration only applies to the management context.
Below is the sampel configuration following #Holgzn's response.
#ManagementContextConfiguration
public class TomcatManagementCustomizerConfiguration {
#Bean
ManagementWebServerFactoryCustomizer<ConfigurableServletWebServerFactory> servletManagementWebServerFactoryCustomizer(
#Value("${management.server.threads.min-spare:5}") int managementMinSpareThreads,
ListableBeanFactory beanFactory) {
return new TomcatManagementCustomizer(beanFactory, managementMinSpareThreads);
}
static class TomcatManagementCustomizer extends ManagementWebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
private final int managementMinSpareThreads;
protected TomcatManagementCustomizer(ListableBeanFactory beanFactory, int managementMinSpareThreads) {
super(beanFactory, TomcatWebServerFactoryCustomizer.class);
this.managementMinSpareThreads = managementMinSpareThreads;
}
#Override
#SuppressWarnings("rawtypes")
protected void customize(ConfigurableServletWebServerFactory factory, ManagementServerProperties managementServerProperties, ServerProperties serverProperties) {
super.customize(factory, managementServerProperties, serverProperties);
((TomcatServletWebServerFactory) factory).addConnectorCustomizers((connector) -> {
ProtocolHandler handler = connector.getProtocolHandler();
if (handler instanceof AbstractProtocol) {
AbstractProtocol protocol = (AbstractProtocol) handler;
protocol.setMinSpareThreads(managementMinSpareThreads);
}
});
}
}
}
The spring.properties file
org.springframework.boot.actuate.autoconfigure.web.ManagementContextConfiguration=<package>.TomcatManagementCustomizerConfiguration
How to configure a Ninja web application running on Heroku to force the use of SSL, that is, redirect all requests to HTTPS?
Here is the class to add in the conf package:
public class Filters implements ApplicationFilters {
#Override
public void addFilters (List<Class<? extends Filter>> list) {
list.add (HttpsFilter.class);
}
public static class HttpsFilter implements Filter {
#Override
public Result filter (FilterChain filterChain, Context context) {
if ("http".equals (context.getHeader ("X-Forwarded-Proto"))) {
return Results.redirect ("https://" + context.getHostname ()
+ context.getRequestPath ());
}
return filterChain.next (context);
}
}
}
If you look good in the ninja framework documentation it is indicated how to configure it to get what you want
http://www.ninjaframework.org/documentation/configuration_and_modes.html
I have problem with customizing API gateway domain, for my restful app deployed on AWS lambda. Customized domain, works this way, that depending on basePath it chooses different APIs which finally touches Lambda. For example:
api.mycustomdomain.com/view/ping -> goes to application view with path /view/ping
api.mycustomdomain.com/admin/ping -> goes to application admin with path /admin/ping
I am using this example as boilerplate: https://github.com/awslabs/aws-serverless-java-container/tree/master/samples/spring/pet-store
What I would like to achieve is handler which depending on Host header strips prefix from request path.
I have prepared following application.yml file:
server:
contextPath: "/view"
productionHost: "api.mycustomdomain.com"
The problem/question is. How can I now load those into my Lambda function? Here is my naive try:
public class LambdaHandler implements RequestHandler<AwsProxyRequest, AwsProxyResponse> {
SpringLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler;
boolean isinitialized = false;
#Value("${server.contextPath}")
private String prefix;
#Value("${server.productionHost}")
private String productionHost;
public AwsProxyResponse handleRequest(AwsProxyRequest awsProxyRequest, Context context) {
if(awsProxyRequest.getHeaders().get("Host").equals(productionHost))
awsProxyRequest.setPath(awsProxyRequest.getPath().substring(prefix.length()));
if (!isinitialized) {
isinitialized = true;
try {
handler = SpringLambdaContainerHandler.getAwsProxyHandler(PingPongApp.class);
} catch (ContainerInitializationException e) {
e.printStackTrace();
return null;
}
}
return handler.proxy(awsProxyRequest, context);
}
}
Obviously this doesn't work, LambdaHandler is working out of Spring context.
Any ideas how can I deal with that?
It seems you can not load those properties. Follow either of the 2 options given below.
1> You can add following bean in your configuration and that way you can autowire strings and use the way you are already using
#Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
2>
public AwsProxyResponse..{
#Autowired
private Environment env;
..
public AwsProxyResponse handleRequest{
..
String contextPath = env.getRequiredProperty(“server.contextPath”));
...
}
}
Recently I've started developing with Java, and was introduced to the Dropwizard framework. But what's got me stumped here, is that I'm not getting any resources online which would explain how to set it up a Jetty server with my Dropwizard application (I previously made use of Apache Tomcat, but was told that Jetty is a much better alternative). Also, what is use of Embedded-jetty in it?
(I realize that the nature of the question is rather amateurish, but I couldn't come across any online resource that would explain this succinctly :( ...)
The application part:
import io.dropwizard.Application;
public class App extends Application<AppConfiguration> {
public static void main(String[] args) throws Exception {
new App().run(args);
}
#Override
public void run(AppConfiguration configuration, Environment environment) {
final AppResource resource = new AppResource();
environment.jersey().register(resource);
}
The resource with a dummy API to get version:
public class AppResource {
#GET
#UnitOfWork(readOnly = true)
#Path("/version")
#ApiOperation(
value = "Retrieve the version")
#Timed
public Version getVersion() {
return new Version();
}
}