Is it possible to list the avaiable JNDI datasources? - jdbc

Is it possible to list the avaiable JNDI datasources for the current application? If yes, how can I do this.

Here is some sample code to try in a Servlet:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
try {
InitialContext ictx = new InitialContext();
Context ctx = (Context) ictx.lookup("java:");
out.println("java: = " + ctx.getClass().getName());
printContext(out, ctx, 1);
} catch (Exception exc) {
throw new ServletException(exc);
}
}
private void printContext(PrintWriter out, Context ctx, int indent) throws ServletException, IOException, NamingException {
NamingEnumeration en = ctx.listBindings("");
while (en.hasMore()) {
Binding b = (Binding) en.next();
char[] tabs = new char[indent];
Arrays.fill(tabs, '\t');
out.println(new String(tabs) + b.getName() + " = " + b.getClassName());
try {
if (b.getObject() instanceof Context) {
printContext(out, (Context) b.getObject(), indent + 1);
}
} catch (Exception exc) {
throw new ServletException(exc);
}
}
}
Try it out and let me know if it works

Related

Thowing custom AuthenticationException inside UsernamePasswordAuthenticationFilter's attemptAuthentication not working when reading in AuthEntryPoint

Custom AuthenticationException:
public class UnauthorizedException extends AuthenticationException {
public UnauthorizedException(final String message) {
super(message);
}
public UnauthorizedException(final String message, final Throwable cause) {
super(message, cause);
}
}
Custom UsernamePasswordAuthenticationFilter's attemptFunction():
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
try {
ObjectMapper mapper = new ObjectMapper();
UserRequestDto userRequestDto = mapper.readValue(request.getInputStream(), UserRequestDto.class);
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
userRequestDto.getUsername(), userRequestDto.getPassword()
);
return this.authenticationManager.authenticate(authToken);
} catch (IOException ioException) {
throw new ServerErrorException(this.accessor.getMessage("server.error"));
} catch (DisabledException disabledException) {
throw new UnauthorizedException(this.accessor.getMessage("user.disabledAccount"));
} catch (LockedException lockedException) {
throw new UnauthorizedException(this.accessor.getMessage("user.lockedAccount"));
} catch (BadCredentialsException | EntryNotFoundException badCredentialsException) {
throw new UnauthorizedException(this.accessor.getMessage("user.incorrectCredentials"));
} catch (AuthenticationException entryNotFoundException) {
throw new UnauthorizedException(this.accessor.getMessage("user.incorrectCredentials"));
}
}
Custom AuthenticationEntryPoint:
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
System.out.println(authException.getMessage());
int UNAUTHORIZED = HttpStatus.UNAUTHORIZED.value();
response.setStatus(UNAUTHORIZED);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
Response<Integer> responseBuild = Response.build(String.valueOf(UNAUTHORIZED), true);
new ObjectMapper().writeValue(response.getOutputStream(), responseBuild);
}
The last catch block inside attemptAuthentication() method throws custom AuthenticationException with custom message ("Incorrect username or password"), but when printing AuthenticationException's message in AuthenticationEntryPoint's commence() method, it prints out "InsufficientAuthenticationException: Full authentication is required to access this resource" (both when given username does and does not exist in the database).
What am I missing here?

Spring boot application filter response body

I am working on a spring boot application. I want to modify the response of the request by request body field "Id".
I have implemented below, but still getting just the name in the output while implementing.Any suggestions on implementing below would be helpful:
Below is the requestBody:
{
"id" : "123"
}
In response, I want to append that field to response id(fieldname from request body).
responseBody:
{
"name" : "foo123" //name + id from request
}
MyCustomFilter:
public class TestFilter implements Filter {
#Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
final PrintStream ps = new PrintStream(baos);
MultiReadHttpServletRequest wrapper = new MultiReadHttpServletRequest((HttpServletRequest) request);
MyRequestWrapper req = new MyRequestWrapper(wrapper);
String userId = req.getId();
chain.doFilter(wrapper, new HttpServletResponseWrapper(res) {
#Override
public ServletOutputStream getOutputStream() throws IOException {
return new DelegatingServletOutputStream(new TeeOutputStream(super.getOutputStream(), ps)
);
}
#Override
public PrintWriter getWriter() throws IOException {
return new PrintWriter(new DelegatingServletOutputStream(new TeeOutputStream(super.getOutputStream(), ps))
);
}
});
String responseBody = baos.toString();
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(responseBody);
String name = node.get("name").astext();
((ObjectNode) node1).put("name", name + userId);
chain.doFilter(wrapper, res);
}
MyRequestWrapper:
public class MyRequestWrapper extends HttpServletRequestWrapper {
private ServletInputStream input;
public MyRequestWrapper(ServletRequest request) {
super((HttpServletRequest)request);
}
public String getId() throws IOException {
if (input == null) {
try {
JSONObject jsonObject = new JSONObject(IOUtils.toString(super.getInputStream()));
String userId = jsonObject.getString("id");
userId = userId.replaceAll("\\D+","");
return userId;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
}
MultiReadHttpServletRequest.java
public class MultiReadHttpServletRequest extends HttpServletRequestWrapper {
private byte[] body;
public MultiReadHttpServletRequest(HttpServletRequest request) {
super(request);
try {
body = IOUtils.toByteArray(request.getInputStream());
} catch (IOException ex) {
body = new byte[0];
}
}
#Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream(), getCharacterEncoding()));
}
#Override
public ServletInputStream getInputStream() throws IOException {
return new ServletInputStream() {
ByteArrayInputStream wrapperStream = new ByteArrayInputStream(body);
#Override
public boolean isFinished() {
return false;
}
#Override
public boolean isReady() {
return false;
}
#Override
public void setReadListener(ReadListener readListener) {
}
#Override
public int read() throws IOException {
return wrapperStream.read();
}
};
}
}
Any suggestions are appreciated. TIA.
Nte: After update i am not able to see the updated response as output. I am still seeing just the name but not id appended to it.
The one issue I see with your own implementation of ServletRequest is that you call super.getInputStream() instead of request.getInputStream(). Your own request is empty by default, that's why you're getting time out exception. You have to delegate a call to the actual request:
public class MyRequestWrapper extends HttpServletRequestWrapper {
private ServletInputStream input;
public MyRequestWrapper(ServletRequest request) {
super((HttpServletRequest)request);
}
public String getId() throws IOException {
if (input == null) {
try {
JSONObject jsonObject = new JSONObject(IOUtils.toString(/*DELETEGATE TO ACTUAL REQUEST*/request.getInputStream()));
String userId = jsonObject.getString("id");
userId = userId.replaceAll("\\D+","");
return userId;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
}

How to set implementation of OncePerRequestFilter to filter only one endpoint

Im using this Filter to log my requests and responses, it works very well, but I noticed that I didnt need actualy this filter for all my endpoints - it will be more efficient and enough to filtering and logging requests from only one endpoint.
Is it possible without making if statement in afterRequest method?
Im searching this a lot, but almost every example is with spring security :(
#Slf4j
#Component
public class RequestAndResponseLoggingFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
if (isAsyncDispatch(request)) {
filterChain.doFilter(request, response);
} else {
doFilterWrapped(wrapRequest(request), wrapResponse(response), filterChain);
}
}
protected void doFilterWrapped(ContentCachingRequestWrapper request, ContentCachingResponseWrapper response, FilterChain filterChain) throws ServletException, IOException {
beforeRequest(request, response);
try {
filterChain.doFilter(request, response);
}
finally {
afterRequest(request, response);
response.copyBodyToResponse();
}
}
protected void beforeRequest(ContentCachingRequestWrapper request, ContentCachingResponseWrapper response) {
if (log.isInfoEnabled()) {
val address = request.getRemoteAddr();
val queryString = request.getQueryString();
if (queryString == null) {
log.info("{}> {} {}", address, request.getMethod(), request.getRequestURI());
} else {
log.info("{}> {} {}?{}", address, request.getMethod(), request.getRequestURI(), queryString);
}
Collections.list(request.getHeaderNames()).forEach(headerName ->
Collections.list(request.getHeaders(headerName)).forEach(headerValue ->
log.info("{}> {}: {}", address, headerName, headerValue)));
val content = request.getContentAsByteArray();
if (content.length > 0) {
log.info("{}>", address);
try {
val contentString = new String(content, request.getCharacterEncoding());
Stream.of(contentString.split("\r\n|\r|\n")).forEach(line -> log.info("{}> {}", address, line));
} catch (UnsupportedEncodingException e) {
log.info("{}> [{} bytes body]", address, content.length);
}
}
log.info("{}>", address);
}
}
protected void afterRequest(ContentCachingRequestWrapper request, ContentCachingResponseWrapper response) {
if (log.isInfoEnabled()) {
val address = request.getRemoteAddr();
val status = response.getStatus();
log.info("{}< {} {}", address, status, HttpStatus.valueOf(status).getReasonPhrase());
response.getHeaderNames().forEach(headerName ->
response.getHeaders(headerName).forEach(headerValue ->
log.info("{}< {}: {}", address, headerName, headerValue)));
val content = response.getContentAsByteArray();
if (content.length > 0) {
log.info("{}<", address);
try {
val contentString = new String(content, request.getCharacterEncoding());
Stream.of(contentString.split("\r\n|\r|\n")).forEach(line -> log.info("{}< {}", address, line));
} catch (UnsupportedEncodingException e) {
log.info("{}< [{} bytes body]", address, content.length);
}
}
}
}
private static ContentCachingRequestWrapper wrapRequest(HttpServletRequest request) {
if (request instanceof ContentCachingRequestWrapper) {
return (ContentCachingRequestWrapper) request;
} else {
return new ContentCachingRequestWrapper(request);
}
}
private static ContentCachingResponseWrapper wrapResponse(HttpServletResponse response) {
if (response instanceof ContentCachingResponseWrapper) {
return (ContentCachingResponseWrapper) response;
} else {
return new ContentCachingResponseWrapper(response);
}
}
}

How I get the HandlerMethod matchs a HttpServletRequest in a Filter

I'm writing a simple proxy app, and want mapped url will be handled by my controller, but other url (includes error) can be forwarded to another different address. So I use Filter rather than HandlerInterceptorAdapter that cannot be invoked if the resourece is not found because certain "resourece path handler" deals it.
Expectation
http://localhost:8090/upload.html > Filter > http://localhost:8092/upload.html
http://localhost:8090/files/upload > Controller > http://localhost:8092/files/upload
Not
http://localhost:8090/upload.html > Filter > http://localhost:8092/upload.html
http://localhost:8090/files/upload > Controller > http://localhost:8092/files/upload
Or
http://localhost:8090/upload.html > Interceptor > http://localhost:8090/error Not found
http://localhost:8090/files/upload > Filter > http://localhost:8092/files/upload
Demo
I set up a Filter in my subclass of WebMvcConfigurerAdapter.
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
private javax.servlet.Filter proxyFilter() {
return new OncePerRequestFilter() {
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
System.out.println("[doFilterInternal]isCommitted=" + response.isCommitted() + ", URI = " + request.getRequestURI());
// if(!isRequestMappedInController(request, "my.pakcage"))
httpProxyForward(request, response);
}
};
}
// #Bean
// private FilterRegistrationBean loggingFilterRegistration() {
// FilterRegistrationBean registration = new FilterRegistrationBean(proxyFilter());
// registration.addUrlPatterns("/**");
// return registration;
// }
Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HandlerInterceptorAdapter() {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// How I determine a controller has handled the request in my interceptor?
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = ((HandlerMethod) handler);
if (handlerMethod.getMethod().getDeclaringClass().getName().startsWith("nxtcasb.casbproxy")) {
System.out.println("[preHandle]dealt: request uri = " + request.getRequestURI() + ", HandlerMethod = " + ((HandlerMethod) handler).getMethod());
return true;
} else {
System.out.println("[preHandle]isCommitted=" + response.isCommitted() + ", HandlerMethod = " + ((HandlerMethod) handler).getMethod());
}
}
// act as an api-gateway
System.out.println("[preHandle]undealt: request uri = " + request.getRequestURI() + ", handler = " + handler);
//ModelAndView modelView = new ModelAndView("redirect: http://www.bing.com");
//throw new ModelAndViewDefiningException(modelView);
httpProxyForward(request, response);
return false;
}
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if (handler instanceof HandlerMethod) {
System.out.println("[postHandle]dealt: uri = " + request.getRequestURI() + ", handler = " + ((HandlerMethod) handler).getMethod());
} else {
System.out.println("[postHandle]undealt uri = " + request.getRequestURI() + ", handler = " + handler);
}
}
}).addPathPatterns("/**", "/error");
}
/**
* this is the same as <mvc:default-servlet-handler/> <!-- This tag allows for mapping the DispatcherServlet to "/" -->
*
* #param configurer
*/
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//registry.addResourceHandler("/**").addResourceLocations("classpath:/public");
}
protected void httpProxyForward(HttpServletRequest request, HttpServletResponse response) {
HttpClient httpClient = CreateHttpClient();
HttpUriRequest targetRequest = null;
HttpResponse targetResponse = null;
try {
targetRequest = createHttpUriRequest(request);
targetResponse = httpClient.execute(targetRequest);
} catch (IOException e) {
e.printStackTrace();
} finally {
// make sure the entire entity was consumed, so the connection is released
if (targetResponse != null) {
EntityUtils.consumeQuietly(targetResponse.getEntity()); // #since 4.2
//Note: Don't need to close servlet outputStream:
// http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter
}
}
}
}
The api url /files/upload:
#RestController
#RequestMapping(value = "/files")
public class FileUploadProxyController {
private static final Logger logger = LoggerFactory.getLogger(FileUploadProxyController.class);
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public ResponseEntity upload(HttpServletResponse response, HttpServletRequest request) {
try {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Iterator<String> it = multipartRequest.getFileNames();
MultipartFile multipart = multipartRequest.getFile(it.next());
String fileName = multipart.getOriginalFilename();
File dir = new File("files", "proxy-uploaded");
dir.mkdirs();
logger.debug("current dir = {}, uploaded dir = {}", System.getProperty("user.dir"), dir.getAbsolutePath());
File file = new File(dir, fileName);
Files.copy(multipart.getInputStream(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
//FileCopyUtils.copy(multipart.getInputStream())
// byte[] bytes = multipart.getBytes();
// BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream("upload" + fileName));
// stream.write(bytes);
// stream.close();
RestTemplate restTemplate = new RestTemplate();
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
//// if Spring version < 3.1, see https://jira.springsource.org/browse/SPR-7909
// requestFactory.setBufferRequestBody(false);
restTemplate.setRequestFactory(requestFactory);
String url = "http://localhost:8092/files/upload";
// [resttemplate multipart post](https://jira.spring.io/browse/SPR-13571)
// [Spring RestTemplate - how to enable full debugging/logging of requests/responses?](https://stackoverflow.com/questions/7952154/spring-resttemplate-how-to-enable-full-debugging-logging-of-requests-responses?rq=1)
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("file", new FileSystemResource(file));
param.add("param1", fileName);
param.add("param2", "Leo");
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String,Object>>(param);
ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
//String string = restTemplate.postForObject(url, param, String.class);
//ResponseEntity e = restTemplate.exchange(url, HttpMethod.POST,
// new HttpEntity<Resource>(new FileSystemResource(file)), String.class);
return responseEntity;
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity("Upload failed", HttpStatus.BAD_REQUEST);
}
}
#RequestMapping("/hello")
public String hello() {
return "hello word";
}
}
Afer reading Spring mvc autowire RequestMappingHandlerMapping or Get destination controller from a HttpServletRequest
The following code works:
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
// https://stackoverflow.com/questions/129207/getting-spring-application-context
#Autowired
private org.springframework.context.ApplicationContext appContext;
private static final String MY_CONTROLLER_PACKAGE_NAME = "nxtcasb.casbproxy";
#Bean
protected javax.servlet.Filter proxyFilter() {
return new OncePerRequestFilter() {
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
HandlerMethod handlerMethod = null;
try {
RequestMappingHandlerMapping req2HandlerMapping = (RequestMappingHandlerMapping) appContext.getBean("requestMappingHandlerMapping");
// Map<RequestMappingInfo, HandlerMethod> handlerMethods = req2HandlerMapping.getHandlerMethods();
HandlerExecutionChain handlerExeChain = req2HandlerMapping.getHandler(request);
if (Objects.nonNull(handlerExeChain)) {
handlerMethod = (HandlerMethod) handlerExeChain.getHandler();
if (handlerMethod.getBeanType().getName().startsWith(MY_CONTROLLER_PACKAGE_NAME)) {
filterChain.doFilter(request, response);
return;
}
}
} catch (Exception e) {
logger.warn("Lookup the handler method", e);
} finally {
logger.debug("URI = " + request.getRequestURI() + ", handlerMethod = " + handlerMethod);
}
httpProxyForward(request, response);
}
};
}
// #Bean
// private FilterRegistrationBean loggingFilterRegistration() {
// FilterRegistrationBean registration = new FilterRegistrationBean(proxyFilter());
// registration.addUrlPatterns("/**");
// return registration;
// }
/**
* this is the same as <mvc:default-servlet-handler/> <!-- This tag allows for mapping the DispatcherServlet to "/" -->
*
* #param configurer
*/
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//registry.addResourceHandler("/**").addResourceLocations("classpath:/public");
}
protected void httpProxyForward(HttpServletRequest request, HttpServletResponse response) {
HttpClient httpClient = CreateHttpClient();
HttpUriRequest targetRequest = null;
HttpResponse targetResponse = null;
try {
targetRequest = createHttpUriRequest(request);
targetResponse = httpClient.execute(targetRequest);
} catch (IOException e) {
e.printStackTrace();
} finally {
// make sure the entire entity was consumed, so the connection is released
if (targetResponse != null) {
EntityUtils.consumeQuietly(targetResponse.getEntity()); // #since 4.2
//Note: Don't need to close servlet outputStream:
// http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter
}
}
}
}

How to debug missing resource/reference on xhmtl?

Sometimes I get an exception on my filter, in line:
chain.doFilter(request, response);
And, after a long search, I'll discover that some xhtml file referenced in another xhtml file was missing, or was not declared in faces-config.xml.
And I search the problem by deleting the elements of the xhtml file and see where the exception stops to occur.
Is there a better way to debug this?
Add an exception handler factory that handles the exceptions, and redirect or forward to an error page or login page.
Good logging in this will help you find the error easily and help you fix the issue sooner.
web.xml:
<factory>
<exception-handler-factory>com.framework.exceptionmgmt.CustomExceptionHandlerFactory</exception-handler-factory>
</factory>
factory:
#Override
public ExceptionHandler getExceptionHandler() {
return new CustomExceptionHandler(wrapped.getExceptionHandler());
}
/**
* Returns the wrapped factory.
*/
#Override
public ExceptionHandlerFactory getWrapped() {
return wrapped;
}
handler:
#Override
public void handle() throws FacesException {
for (final Iterator<ExceptionQueuedEvent> it = getUnhandledExceptionQueuedEvents().iterator(); it.hasNext();) {
Throwable t = it.next().getContext().getException();
System.out.println("Exception in page: "+t.getMessage());
while ((t instanceof FacesException || t instanceof EJBException || t instanceof ELException) && t.getCause() != null) {
t = t.getCause();
}
if (t instanceof FileNotFoundException || t instanceof ViewExpiredException) {
final ExternalContext externalContext = facesContext.getExternalContext();
final Map<String, Object> requestMap = externalContext.getRequestMap();
try {
// Log the information in the logs
String message;
if (t instanceof ViewExpiredException) {
final String viewId = ((ViewExpiredException) t).getViewId();
message = "View is expired. <a href='/ifos" + viewId + "'>Back</a>";
} else {
message = t.getMessage(); // beware, don't leak internal
// info!
}
requestMap.put("errorMsg", message);
try {
HttpServletRequest origRequest = (HttpServletRequest) facesContext.getExternalContext()
.getRequest();
String requestedURL = origRequest.getRequestURL().toString();
resetResponse(facesContext);
redirectToCorrectPage(origRequest.getContextPath()+"/error.xhtml",facesContext);
} catch (final IOException e) {
}
facesContext.responseComplete();
} finally {
it.remove();
}
}else{
try {
resetResponse(facesContext);
Map<String, Object> sessnMap = FacesContext
.getCurrentInstance().getExternalContext()
.getSessionMap();
// For checking whether user is logged in or not If not then redirect to login page instead of error page
Boolean isUserLoggedIn = (Boolean) sessnMap
.get("isUserLoggedIn");
if (isUserLoggedIn == null || !isUserLoggedIn) {
redirectToCorrectPage(
((HttpServletRequest) facesContext
.getExternalContext().getRequest()).getContextPath()
+ "/error.xhtml",
facesContext);
} else {
redirectToCorrectPage(
((HttpServletRequest) facesContext
.getExternalContext().getRequest()).getContextPath()
+ "/error.xhtml",
facesContext);
}
} catch (final IOException e) {
}finally {
it.remove();
}
facesContext.responseComplete();
}
}

Resources