this is my code
Is there any way to get from ContainerRequestContext
thanks for you help
#Provider
public class LoggingFilter implements ContainerRequestFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(LoggingFilter.class);
#Inject
JsonWebToken jwt;
#Context
UserInfo userInfo;
#Context
UriInfo uriInfo;
#Context
HttpServerRequest request;
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
String method = requestContext.getMethod();
String path = uriInfo.getPath();
String address = request.remoteAddress().toString();
String name = jwt.getName();
LOGGER.info("{}:{}, From {}, By {}",method,path,address,name);
}
}
Have you tried the following?
IOUtils.toString(requestContext.getEntityStream(), StandardCharsets.UTF_8);
Related
I guess this is a bit of a threadsafe question, as I'm not sure how Spring Boot handles beans and web service calls and incoming websocket data.
Is it safe to call controller.doSomething() from McpWebSocketHandler, if I know MCPController.ping() also calls it?
Also, if I have the GameUnitService Autowired in both MCPController and McpWebSocketHandler, will there be any thread contention?
#SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
#RestController
public class MCPController implements MqttListener {
Logger log = LoggerFactory.getLogger(MCPController.class);
#Autowired private JdbcTemplate jdbc;
#Autowired private GameUnitService gameUnitService;
#GetMapping("/ping")
public Object ping(HttpServletRequest request) {
String remoteAddr = request.getHeader(FORWARDED) == null ? request.getRemoteAddr() : request.getRemoteAddr() + "/" + request.getHeader(FORWARDED);
log.info("Got ping from {}", remoteAddr);
doSomething();
return new Response(true, ErrorCode.OK, "pong");
}
public String doSomething() {
return gameUnitService.doSomethingWithDatabase();
}
}
public class McpWebSocketHandler extends AbstractWebSocketHandler {
private ApplicationContext appContext;
private GameUnitService gameUnitService;
private MCPController controller;
public McpWebSocketHandler(ApplicationContext appContext,GameUnitService gameUnitService) {
this.appContext = appContext;
this.gameUnitService = gameUnitService;
controller = (MCPController)appContext.getBean("MCPController");
}
#Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String payload = message.getPayload();
String response = controller.doSomething(); //is this safe?
session.sendMessage(new TextMessage(response));
}
}
#Configuration
#EnableWebSocket
#ComponentScan(basePackageClasses = McpApplication.class)
//public class McpWebSocketConfig implements WebSocketConfigurer, MqttListener {
public class McpWebSocketConfig implements WebSocketConfigurer {
private static final Logger log = LoggerFactory.getLogger(McpWebSocketConfig.class);
#Autowired private ApplicationContext appContext;
#Autowired private GameUnitService gameUnitService;
#Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new McpWebSocketHandler(appContext,gameUnitService), "/socket").setAllowedOrigins("*");
registry.addHandler(new McpWebSocketHandler(appContext,gameUnitService), "/").setAllowedOrigins("*");
}
...
}
How to get current request in class ? I am using below code to inject code. but request is null
import java.net.http.HttpRequest;
#RequestScoped
public class BaseErrorCode {
#Context
HttpRequest request;
}
I use in this way, i'm not sure if it will be valid for you:
#Provider
public class BaseErrorCode implements ContainerRequestFilter{
#Context
HttpRequest request;
public String getHttpMethod() {
return "GET";
}
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// TODO Auto-generated method stub
}
I have written a JAX-RS Client libary which i will be used in different JavaEE WebApps.
These WebApps are providing JAX-RS Endpoints.
I want to passthrough a session attribute as header param for all requests, but the HttpServletRequest is always null.
#PreMatching
#Provider
#Priority(Priorities.HEADER_DECORATOR)
public class JwtTokenClientFilter implements ClientRequestFilter {
#Context
private HttpServletRequest servletRequest;
#Override
public void filter(ClientRequestContext requestContext) throws IOException {
String jwtToken = (String) servletRequest.getSession().getAttribute("jwt_token");
requestContext.getHeaders().add("Authorization", "Bearer " + jwtToken);
}
}
How to inject HttpServletRequest inside of JAX-RS ClientRequestFilter?
Many thanks in advance.
Edit:
Is this maybe a solution, or am i running into some trouble?
Will it work with many request from diffrent users?
/* my server webservice*/
#Path("/autos")
public class CarResource extends MyJaxRsConfig {
#Inject
private CarStatsClient CarStatsClient;
#GET
#RolesAllowed("car_admin")
#Path("{carNo}/stats")
public Response getCarStats(#Valid #NotNull #PathParam("carNo") String carNo) {
return CarStatsClient.getCarStats(carNo);
}
}
/* my client libary*/
//#ApplicationScoped
#RequestScoped
public class CarStatsService implements Serializable, CarStatsClient {
#Inject
private Logger logger;
public static final String RESOURCE_PATH_CAR_STATS = "{carNo}/stats";
#Inject
private JwtTokenClientFilter jwt;
#Inject
#TargetUri(SERVER + "/api/v2/" + CarStatsService.RESOURCE_PATH_CAR_STATS)
private WebTarget carStatsTarget;
#Override
//public Response getCarStats(String jwtToken, String carNo) {
public Response getCarStats(String carNo) {
carStatsTarget.register(jwt); //TODO: create Annotation
Response response = carStatsTarget.resolveTemplate("carNo", carNo).request()
/* .header("Authorization", "Bearer " + jwtToken) */
.get();
if (response.getStatus() != 200) {
logger.warning("->CarStatsService->getCarProfitStats()");
}
return response;
}
}
/* client libary too*/
#RequestScoped
#PreMatching
#Provider
#Priority(Priorities.HEADER_DECORATOR)
public class JwtTokenClientFilter implements ClientRequestFilter, ContainerRequestFilter {
#Context
private HttpServletRequest servletRequest;
#Override
public void filter(ClientRequestContext requestContext) throws IOException {
String jwtToken = (String) servletRequest.getSession().getAttribute("jwt_token");
requestContext.getHeaders().add("Authorization", "Bearer " + jwtToken);
}
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
//
}
}
I'm trying to figure out how to inject an object when registering a AuthDynamicFilter in jersey.
public class CustomApplication extends Application<Configuration> {
public void run(Configuration configuration, Environment environment) throws Exception {
...
environment.jersey().register(new AuthDynamicFeature(CustomAuthFilter.class));
...
}
}
CustomAuthFilter
#PreMatching
public class CustomAuthFilter<P extends Principal> extends AuthFilter<String, P> {
private final Object identity;
#Context
private HttpServletRequest httpServletRequest;
#Context
private HttpServletResponse httpServletResponse;
public LcaAuthFilter(Identity identity) {
this.identity = identity;
}
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
...identity.process(httpServletRequest)
}
}
The above code won't compile because there is no way to inject the Identity Object when creating the CustomAuthFilter.
If you go with:
environment.jersey().register(new AuthDynamicFeature(new CustomerAuthFilter(new Identity())));
In this case, httpServletRequest will be set to null.
The only way I could figure out how to get around this is to not even use AuthDynamicFeature and just go with a normal Filter and inject it that way which is fine. I'm wondering how would you do it with a AuthDynamicFeature.
I'm still new to dropwizard and jersey so please bear with me. Some concepts that I might be messing.
Any Advice Appreciated,
Thanks,
Derek
I have an app that does exactly that. Annotate the constructor with #Inject:
#PreMatching
public class CustomAuthFilter<P extends Principal> extends AuthFilter<String, P> {
private final Identity identity;
#Context
private HttpServletRequest httpServletRequest;
#Context
private HttpServletResponse httpServletResponse;
// Annotate the ctor with #Inject
#Inject
public LcaAuthFilter(Identity identity) {
this.identity = identity;
}
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
...identity.process(httpServletRequest)
}
}
Tell Jersey's dependency injection mechanism to inject the identity with a value you provide:
Identity identity = getTheIdentity();
environment.jersey().register(new AbstractBinder() {
#Override
protected void configure() {
bind(identity).to(Identity.class);
}
});
environment.jersey().register(new AuthDynamicFeature(CustomAuthFilter.class));
If identity is only known at runtime, use a Supplier<Identity> instead (adapt your constructor
as well):
Supplier<Identity> identity = getTheIdentitySupplier();
environment.jersey().register(new AbstractBinder() {
#Override
protected void configure() {
bind(identity).to(new TypeLiteral<Supplier<Identity>>(){});
}
});
environment.jersey().register(new AuthDynamicFeature(CustomAuthFilter.class));
I have the following code which attempts to save a POJO object (Actor) into MongoDB using Spring Mongo Repository, but the repository object is always Null. I have followed multiple examples but mainly this one
The POJO class:
#Document(collection = "actors")
public class Actor
{
#Id
private String id;
...
//constructor
//setters & getters
}
The repository:
public interface ActorRepository extends MongoRepository<Actor, String>
{
public Actor findByFNameAndLName(String fName, String lName);
public Actor findByFName (String fName);
public Actor findByLName(String lName);
}
The service that uses the repository:
#Service
public class ActorService
{
#Autowired
private ActorRepository actorRepository;
public Actor insert(Actor a)
{
a.setId(null);
return actorRepository.save(a);
}
}
And I access the service from a REST controller class:
#RestController
public class Controllers
{
private static final Logger logger = Logger.getLogger(Controllers.class);
private static final ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
private ActorService actorService = new ActorService();
#RequestMapping(value="/createActor", method=RequestMethod.POST)
public #ResponseBody String createActor(#RequestParam(value = "fName") String fName,
#RequestParam(value = "lName") String lName,
#RequestParam(value = "role") String role)
{
return actorService.insert(new Actor(null,fName,lName,role)).toString();
}
...
}
The error that I get is NullPointerException from this line: return actorRepository.save(a); in the ActorService.insert() method.
Any Idea why is this happening?
EDIT: Here is the Spring Configurations
#Configuration
public class SpringMongoConfig extends AbstractMongoConfiguration
{
#Bean
public GridFsTemplate gridFsTemplate() throws Exception
{
return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
}
#Override
protected String getDatabaseName()
{
return "SEaaS";
}
#Override
#Bean
public Mongo mongo() throws Exception
{
return new MongoClient("localhost" , 27017 );
}
public #Bean MongoTemplate mongoTemplate() throws Exception
{
return new MongoTemplate(mongo(), getDatabaseName());
}
}
The problem is that you are not using Spring to get the ActorService dependency -instead you have manually instantiated the dependency using
private ActorService actorService = new ActorService();.
The following code is the easiest fix in order to inject the ActorService dependency into the controller.
#RestController
public class Controllers
{
private static final Logger logger = Logger.getLogger(Controllers.class);
private static final ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
#Autowired
private ActorService actorService;
#RequestMapping(value="/createActor", method=RequestMethod.POST)
public #ResponseBody String createActor(#RequestParam(value = "fName") String fName,
#RequestParam(value = "lName") String lName,
#RequestParam(value = "role") String role)
{
return actorService.insert(new Actor(null,fName,lName,role)).toString();
}
...
}