跳至主要内容

博文

目前显示的是 十一月, 2017的博文

Java EE Security API 1.0: SecurityContext

SecurityContext In Java EE 7 or earlier versions, other specfications, such as Servelt, EJB, JAX-RS, JAX-WS, etc. have their own specific APIs to query current security context. Servlet - HttpServletRequest#getUserPrincipal, HttpServletRequest#isUserInRole EJB - EJBContext#getCallerPrincipal, EJBContext#isCallerInRole JAX-WS - WebServiceContext#getUserPrincipal, WebServiceContext#isUserInRole JAX-RS - SecurityContext#getUserPrincipal, SecurityContext#isUserInRole JSF - ExternalContext#getUserPrincipal, ExternalContext#isUserInRole CDI - @Inject Principal WebSockets - Session#getUserPrincipal In Java EE 8, you can use the new SecurityContext introduced in Java EE Security 1.0 instead. A default implementation should be available at runime, you can inject it in CDI beans. @Inject SecurityContext securityContext; The new SecurityContext provides similiar methods with the one in other specfications. Principal getCallerPrincipal(); <T extends Principal> Se

Java EE Security API 1.0: IdentityStore

There are two built-in IdentityStore implementations provided in Glassfish v5, Database or Ldap. An example of using built-in @DatabaseIdentityStoreDefinition to setup database based IdentityStore . @DatabaseIdentityStoreDefinition ( dataSourceLookup = " ${'java:global/MyDS'} " , callerQuery = " #{'select password from caller where name = ?'} " , groupsQuery = " select group_name from caller_groups where caller_name = ? " , hashAlgorithm = Pbkdf2PasswordHash . class, priorityExpression = " #{100} " , hashAlgorithmParameters = { " Pbkdf2PasswordHash.Iterations=3072 " , " ${applicationConfig.dyna} " } // just for test / example ) @ApplicationScoped @Named public class ApplicationConfig { public String [] getDyna () { return new String []{ " Pbkdf2PasswordHash.Algorithm=PBKDF2WithHmacSHA512 " , " Pbkdf2PasswordH

Java EE Security API 1.0: HTTP authentication

HTTP authentication HttpAuthenticationMechanism allow customsize your own HTTP authentication mechanism. An examples for custom HttpAuthenticationMechanism . @ApplicationScoped public class TestAuthenticationMechanism implements HttpAuthenticationMechanism { @Inject private IdentityStoreHandler identityStoreHandler; @Override public AuthenticationStatus validateRequest ( HttpServletRequest request , HttpServletResponse response , HttpMessageContext httpMessageContext ) throws AuthenticationException { final String name = request . getParameter( " name " ); final String pwd = request . getParameter( " password " ); if (name != null && pwd != null ) { // Get the (caller) name and password from the request // NOTE: This is for the smallest possible example only. In practice // putting the password in a request query parameter is highly

Servlet 4.0: Http Trailer

Http Trailer Servlet 4.0 added Http Trailer( RFC 7230 ) supports, which is a specific collection of http headers comes after response body. It is useful in some case, such as chunked transfer encoding or implements some specific protocols. The reading side, HttpServletRequest has a method isTrailerFieldsReady() to check if the trailer fields are available, if it returns true, the trailer fields can be read via getTrailerFields() method. The writing side, HttpServletResponse has a method setTrailerFields , which accpets a Supplier as it's parameter. An example of Http Trailer to handle chunked tranfer encoding. @WebServlet ( " /test " ) public class TestServlet extends HttpServlet { @Override protected void doPost ( HttpServletRequest req , HttpServletResponse res ) throws ServletException , IOException { res . setContentType( " text/plain " ); res . addHeader( " Transfer-encoding " , &q

Servlet 4.0: Runtime Discovery of Servlet Mappings

Runtime Discovery of Servlet Mappings When a servlet is activated, the mapping info can be discoverable at runtime. Described in the Servlet spcefication. The method getHttpServletMapping() on HttpServletRequest returns an HttpServletMapping implementation that provides information for the mapping that caused the current Servlet to be invoked. Please see the javadocs for the normative specification. Please see sections Section 9.3.1, “Included Request Parameters” on page 9-101Section 9.4.2, “Forwarded Request Parameters” on page 9-102 and Section 9.7.2, “Dispatched Request Parameters” on page 9-104 for relevant request attributes. But please notice: As with the included and forwarded request parameters, the HttpServletMapping is not available for servlets that have been obtained with a call to ServletContext.getNamedDispatcher(). An sample to print the mapping information of a servlet. @WebServlet ( name = " MyServlet " , urlPatterns = {

Servlet 4.0: HTTP/2 Server PUSH

Server Push One highlight feature of HTTP/2 is Server Push. Servlet 4.0 add PushBuilder to handle push. An exmaple of enable Servlet Push. @WebServlet ( urlPatterns = " " ) @ServletSecurity ( httpMethodConstraints = { @HttpMethodConstraint ( value = " GET " , transportGuarantee = CONFIDENTIAL ) }) public class PushServlet extends HttpServlet { @Override protected void doGet ( HttpServletRequest req , HttpServletResponse res ) throws IOException , ServletException { PushBuilder pushBuilder = req . newPushBuilder() . path( " main.css " ); pushBuilder . push(); res . getWriter() . println( " <html><head><title>HTTP2 Test</title><link rel= \" stylesheet \" href= \" main.css \" ></head><body>Hello Servlet Push!!!</body></html> " ); } } Run this application on Glassfish v5 in NetBeans ID

JAX-RS 2.1: Server Sent Event

Server Sent Event Jersey itself supports SSE for years, now it is standardized as a part of JAXRS 2.1. A simple SSE example. @Path ( " events " ) @RequestScoped public class SseResource { @GET @Produces ( MediaType . SERVER_SENT_EVENTS ) public void eventStream ( @Context Sse sse , @Context SseEventSink eventSink ) { // Resource method is invoked when a client subscribes to an event stream. // That implies that sending events will most likely happen from different // context - thread / event handler / etc, so common implementation of the // resource method will store the eventSink instance and the application // logic will retrieve it when an event should be emitted to the client. // sending events: eventSink . send(sse . newEvent( " event1 " )); } } Notice, you should declare @Produces value as text/event-stream ( via MediaType.SERVER_SENT_EVENTS ). SseEve

JAX-RS 2.1: Reactive Client

Reactive Client In JAXRS 2.0, a client to handle async resources looks like. public class AsyncClient { public final static void main ( String [] args ) throws Exception { WebTarget target = ClientBuilder . newClient() . target( " http://localhost:8080/jaxrs-async/rest/ejb " ); Future< String > future = target . request() .async() .get( String . class); System . out . println( " ejb resource future: " + future . get()); target . request() .async() .get( AsyncClient . responseInvocationCallback()); } private static InvocationCallback< Response > responseInvocationCallback () { return new InvocationCallback< Response > () { @Override public void completed ( Response res ) { System . out . println( " Status: " + res . getStatusInfo());