I have base class which contains ThreadLocal :
#Singleton
public class BaseView extends HttpServlet {
protected ThreadLocal<Locale> locale = new ThreadLocal<Locale>();
private Locale getLocale() {
return (Locale) ObjectUtils.defaultIfNull(locale.get(), Locale.ENGLISH);
}
...
}
And it is extended in EmailValidatedView:
#Singleton
public class EmailValidatedView extends BaseView {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String token = req.getParameter("token");
if (token != null) {
try {
User user = userService.validateEmail(token);
locale.set(user.parseLocale());
} catch (ServiceException e) {
e.printStackTrace();
}
}
sendResponse("validatedEmail.vm", resp.getWriter(), $());
}
}
When token is invalid, I get ServiceException and locale is not set. In this case sendResponse() method should use default locale - English. However, if I make refresh for the same page in browser with invalid token, I may get different/non related languages every time. Why does it happen?
Most HTTP servers reuse threads from a pool. Keeping a thread-safe config is a good thing, and ThreadLocal can help, but your logic is structured such that your locale will not be reset every request. Therefore, it's unsurprising that the thread's old locales from past requests will bleed through.
You'll need to ensure your locale is set every single request that reads it, and that the default locale is set (or equivalently that the ThreadLocal value is cleared) for every new request.
Related
Google foo failed me. I want to find out if there is a standard "by the book" way of transforming the input locales from Accept-Language header to correct ResourceBundle.
ResourceBundle::getBundle() method(s) accepts a single locale but Accept-Language can have multiple locales weighted by index, eg: de;q=1.0, sl;q=0.9.
Current code:
#Context
private HttpServletRequest request;
public String getString(String key) {
ResourceBundle i18n = ResourceBundle.getBundle("locale/strings", this.request.getLocale());
return i18n.getString(key);
}
The problem is that getLocale() returns the preferred locale, in this case de. If available resource bundles are sl and en, this will try to find de and then fallback to en, but the actual expected result by the client is sl!
My question is basically, do I have to implement a custom fallback code that iterates over HttpServletRequest.getLocales() (I don't want to reinvent the wheel..) or is there a more standard and straightforward way of doing this? I'd also settle for some 3rd party lib that fills this gap.
Custom solution so far:
#RequestScoped
public class Localization {
#Context
private HttpServletRequest request;
private ResourceBundle i18n;
#PostConstruct
void postConstruct() {
//List of locales from Accept-Language header
List<Locale> locales = Collections.list(request.getLocales());
if (locales.isEmpty()) {
//Fall back to default locale
locales.add(request.getLocale());
}
for (Locale locale : locales) {
try {
i18n = ResourceBundle.getBundle("bundles/translations", locale);
if (!languageEquals(i18n.getLocale(), locale)) {
//Default fallback detected
//The resource bundle that was returned has different language than the one requested, continue
//Only language tag is checked, no support for detecting different regions in this sample
continue;
}
break;
}
catch (MissingResourceException ignore) {
}
}
}
private boolean languageEquals(Locale first, Locale second) {
return getISO2Language(first).equalsIgnoreCase(getISO2Language(second));
}
private String languageGetISO2(Locale locale) {
String[] localeStrings = (locale.getLanguage().split("[-_]+"));
return localeStrings[0];
}
public ResourceBundle i18n() {
return this.i18n;
}
}
I would write an Interceptor, there you can set the language you want and apply the logic you want into a ThreadLocal or pass it down.
i.e you check against the available languages and define an order or set a default.
If you use Spring, you could then set LocaleContextHolder manualy or use the LocaleContextResolver instead of writing a own interceptor.
Using a RestTemplate, I am querying a remote API to return an object either of expected type (if HTTP 2xx) or an APIError (if HTTP 4xx / 5xx).
Because the response object is indeterminate, I have implemented a custom ResponseErrorHandler and overridden handleError(ClientHttpResponse clientHttpResponse) in order to extract the APIError when it occurs. So far so good:
#Component
public class RemoteAPI {
public UserOrders getUserOrders(User user) {
addAuthorizationHeader(httpHeaders, user.getAccessToken());
HttpEntity<TokenRequest> request = new HttpEntity<>(HEADERS);
return restTemplate.postForObject(CUSTOMER_ORDERS_URI, request, UserOrders.class);
}
private class APIResponseErrorHandler implements ResponseErrorHandler {
#Override
public void handleError(ClientHttpResponse response) {
try {
APIError apiError = new ObjectMapper().readValue(response.getBody(), APIError.class);
} catch ...
}
}
private void refreshAccessToken(User user) {
addAuthorizationHeader(httpHeaders, user.getAccessSecret());
HttpEntity<TokenRequest> request = new HttpEntity<>(HEADERS);
user.setAccessToken(restTemplate.postForObject(TOKEN_REFRESH_URI, request, AccessToken.class));
}
}
The challenge is that getUserOrders(), or a similar API call, will occasionally fail with a 'recoverable' error; for instance, the API access token may have expired. We should then make an API call to refreshAccessToken() before re-attempting getUserOrders(). Recoverable errors such as these should be hidden from the user until the same ones have occurred multiple times, at which point they are are deemed non-recoverable / critical.
Any errors which are 'critical' (e.g.: second failures, complete authentication failure, or transport layer failures) should be reported to the user as there is no automatic recovery available.
What is the most elegant and robust way managing the error handling logic, bearing in mind that the type of object being returned is not known until runtime?
Option 1: Error object as a class variable with try / catch in each API call method:
#Component
public class RemoteAPI {
private APIError apiError;
private class APIResponseErrorHandler implements ResponseErrorHandler {
#Override
public void handleError(ClientHttpResponse response) {
try {
this.apiError = new ObjectMapper().readValue(response.getBody(), APIError.class);
} catch ...
}
}
public UserOrders getUserOrders(User user) {
try {
userOrders = restTemplate.postForObject(CUSTOMER_ORDERS_URI, request, UserOrders.class);
} catch (RestClientException ex) {
// Check this.apiError for type of error
// Check how many times this API call has been attempted; compare against maximum
// Try again, or report back as a failure
}
return userOrders;
}
}
Pros: Clarity on which method originally made the call
Cons: Use of a class variable for a transient value. Lots of boilerplate code for each method that calls the API. Error handling logic spread around multiple methods.
Option 2: User object as a class variable / Error management logic in the ResponseErrorHandler
#Component
public class RemoteAPI {
private User user;
private class APIResponseErrorHandler implements ResponseErrorHandler {
#Override
public void handleError(ClientHttpResponse response) {
try {
APIError apiError = new ObjectMapper().readValue(response.getBody(), APIError.class);
// Check this.apiError for type of error
// Check how many times this API call has been attempted; compare against maximum
// Try again...
getUserOrders();
...or report back as a failure
} catch ...
}
}
Pros: Error management logic is in one place.
Cons: User object must now be a class variable and handled gracefully, because the User object cannot otherwise be accessible within the ResponseErrorHandler and so cannot pass it to getUserOrders(User) as before. Need to keep track of how many times each method has been called.
Option 3: Error management logic outside of the RemoteAPI class
Pros: Separates error handling from business logic
Cons: API logic is now in another class
Thank you for any advice.
Answering my own question: it turns out that there were fallacies in the question itself.
I was implementing a ResponseErrorHandler because I thought I needed it to parse the response even when that response was returned with a HTTP error code. In fact, that isn't the case.
This answer demonstrates that the response can be parsed into an object by catching a HttpStatusCodeException and otherwise using a standard RestTemplate. That negates the need for a custom ResponseErrorHandler and therefore the need to return an object of ambiguous type. The method that is handed the error can catch the HttpStatusCodeException, try to refresh the access token, and then call itself again via recursion. A counter is required to prevent endless recursion but that can be passed through rather than being a class variable.
The downside is that it still requires error management logic spread around the class, along with plenty of boilerplate code, but it's a lot tidier than the other options.
public UserOrders getUserOrders(User user, Integer methodCallCount) {
methodCallCount++;
UserOrders userOrders;
try {
userOrders = restTemplate.postForObject(USER_ORDERS_URI, request, UserOrders.class);
} catch (RestClientException ex) {
APIError apiError = new ObjectMapper().readValue(response.getBody(), APIError.class);
if (methodCallCount < MAX_METHOD_CALLS) {
if (apiError.isType(ACCESS_TOKEN_EXPIRED)) {
refreshVendorAccessTokenInfo(user);
userOrders = getUserOrders(user, methodCallCount);
}
}
}
return userOrders;
}
We are using Guice in our project for DI. Currently we have some configurations(properties) that we load a t server startup from a file. These are then bound to all the components & used for all the requests.
But now, we have multiple property files & load them at startup. These configurations can be different per REST(Jersey) request as they depend on the input.
So, we need to bind these configurations dynamically for each request. I looked into Guice API for #RequestScoped, but did not find anything specificallyu helpful.
There are few questions similar to this, but no luck yet. Can you please help me with this.
I'm providing 2 ways of doing this and both are request scoped.
Using HttpServletRequest, for classes where you can Inject request object.
Using ThreadLocal, Generic way. It can be used in any class.
(NOTE: This method wouldn't work if your creating new threads in your code and want to access the value. In which case you'll have to pass the values through Objects to those threads)
I meant something like this:
public class RequestFilter implements ContainerRequestFilter {
#Context
private HttpServletRequest request;
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
List listOfConfig = //load Config;
request.setAttribute("LOADED_CONFIG",listOfConfig);
// If you want to access this value at some place where Request object cannot be injected (like in service layers, etc.) Then use below ThreadLocals.
ThreadLocalWrapper.getInstance().get().add("adbc"); // In general add your config here, instead of abdc.
}
}
My ThreadLocalWrapper looks like this:
public class ThreadLocalWrapper {
private static ThreadLocal<List<String>> listOfStringLocals; // You can modify this to a list of Object or an Object by itself.
public static synchronized ThreadLocal<List<String>> getInstance() {
if (listOfStringLocals == null) {
listOfStringLocals = new ThreadLocal<List<String>>() {
#Override
protected List<String> initialValue() {
return new ArrayList<String>();
}
};
}
return listOfStringLocals;
}
}
To Access the value:
In Controller - Inject HttpServletRequest Object and do getAttribute() to get the value. Since HttpServletRequest Object is requestScoped, you can set the loaded config. into this and access it in your controller's using request Object again.
In Any other part of the code - If HttpServletRequest is not available then you can always use the ThreadLocal example shown. To access this value.
public class GuiceTransactionImpl implements GuiceTransaction {
private String value = "";
public GuiceTransactionImpl(String text) {
value = text;
}
#Override
public String returnSuccess() {
return value + " Thread Local Value " + ThreadLocalWrapper.getInstance().get();
}
}
(I'm not sure exactly how to phrase the title here, and because of that I'm not really sure how to go about searching for the answer either.)
I have a Java servlet engine that handles requests. Say we have a doGet() request:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//set up user data
//do whatever the user requested
SomeClass c = new SomeClass();
c.doSomething();
}
Now in doSomething(), I want to be able to access which user made the request. Right now I'm doing it by creating a Java object within the method and passing it to wherever I need it:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//set up user data
MyUserObj userObj = new MyUserObj();
userObj.setId('123');
//do whatever the user requested
SomeClass c = new SomeClass(userObj);
c.doSomething();
}
By doing this, I have access to the instance of MyUserObj, and it can be further passed along in the application as needed.
I know in ASP.NET MVC3 I can acheive this by storing items/attributes for the current thread like this: HttpContext.Current.Items.Add("myId", "123"). HttpContext is then available in other functions without explicitly having to pass around an object.
Is there a way in Java to set some variables per request (or even set the MyUserObject to be accessed later) without passing the object through as a parameter?
There isn't in the servlet API, but you can make your own pretty easily. (Some frameworks like spring-mvc, struts provide such functionality)
Just use a public static ThreadLocal to store and retrieve the object. You can even store the HttpServletRequest itself in the threadlocal and use its setAttribute()/getAttribute() methods, or you can store a threadlocal Map, to be agnostic of the servlet API. An important note is that you should clean the threadlocal after the request (with a Filter, for example).
Also note that passing the object as parameter is considered a better practice, because you usually pass it from the web layer to a service layer, which should not be dependent on web-related object, like a HttpContext.
If you decide that it is fine to store them in a thread-local, rather than passing them around:
public class RequestContext {
private static ThreadLocal<Map<Object, Object>> attributes = new ThreadLocal<>();
public static void initialize() {
attributes.set(new HashMap<Map<Object, Object>>());
}
public static void cleanup() {
attributes.set(null);
}
public static <T> T getAttribute(Object key) {
return (T) attributes.get().get(key);
}
public static void setAttribute(Object key, Object value) {
attributes.get().put(key, value);
}
}
And a necessary filter:
#WebFilter(urlPatterns="/")
public class RequestContextFilter implements Filter {
public void doFilter(..) {
RequestContext.initialize();
try {
chain.doFilter(request, response);
} finally {
RequestContext.cleanup();
}
}
}
You can attach an object to the current request with setAttribute. This API is primarily used for internal routing, but it's safe to use for your own purposes too, as long as you use a proper namespace for your attribute names.
I have the following two classes and I am starting to see a pattern that even with my little Java background is screaming for a fix. Every new Object is going to require a set of Actions and the number of classes could grow out of hand. How do I refactor this into a generic DeleteAction class?
I know some of the answers will be use Hibernate, or JPA, or some Framework, but at the moment I can't utilize any of those tools. Oh, and our server only has jdk 1.4 (don't ask!). Thanks.
public class DeleteCommitmentAction implements ControllerAction {
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException {
CommitmentListDAO clDAO = new CommitmentListDAO();
CommitmentItemForm ciForm = new CommitmentItemForm(clDAO);
CommitmentItem commitmentItem = ciForm.deleteCommitmentItem(request);
RequestDispatcher view = request.getRequestDispatcher("views/commitmentView_v.jsp");
view.forward(request, response);
}
}
.
public class DeleteProgramAction implements ControllerAction {
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException {
ProgramDAO prgDAO = new ProgramDAO();
ProgramForm prgForm = new ProgramForm(prgDAO);
ProgramForm prg = prgForm.deleteProgram(request);
RequestDispatcher view = request.getRequestDispatcher("views/programView_v.jsp");
view.forward(request, response);
}
}
The approach that I think I need to take is to make interfaces. Starting with the DAO, I have created the following interface.
public interface GenericDao {
public void create(Object object, STKUser authenticatedUser) throws DAOException;
public void retreive(String id, STKUser authenticatedUser) throws DAOException;
public void update( final Object object, STKUser authenticatedUser) throws DAOException;
public void delete(String id, STKUser authenticatedUser) throws DAOException;
}
And then in my DeleteAction class I tried this
GenericDao gDAO = new GenericDao();
but Eclipse is stating "Cannot instantiate the type GenericDao" So now I am lost.
Update: Based on Péter Török's answer, here is what I have:
This is the servlet specific for handling operations on Commitment Items:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String schema = General_IO.getSchemaPath("TPQOT_463_COMMITMENT", request.getServerName());
CommitmentListDAO clDAO = new CommitmentListDAO();
CommitmentItemForm ciForm = new CommitmentItemForm(clDAO);
CommitmentItem commitmentItem = new CommitmentItem();
// I think this is the Application Controller Strategy
actionMap.put(null, new ListCommitmentsAction());
actionMap.put("list", new ListCommitmentsAction());
actionMap.put("view", new ViewCommitmentItemAction(schema));
//actionMap.put("delete", new DeleteCommitmentAction(schema));
// Change to the Generic DeleteAction and pass in the parameters
actionMap.put("delete", new DeleteAction(ciForm, commitmentItem, schema, "views/commitmentDeleteConfirm_v.jsp", "views/commitmentView_v.jsp" ));
// When happy with this approach, change other actions to the Generic Versions.
actionMap.put("sqlConfirmDelete", new DeleteCommitmentConfirmAction());
actionMap.put("edit", new EditCommitmentItemAction(schema));
actionMap.put("sqlUpdate", new UpdateCommitmentItemAction1(schema));
actionMap.put("new", new NewCommitmentFormAction(schema));
actionMap.put("sqlInsert", new InsertCommitmentItemAction1(schema));
String op = request.getParameter("method");
ControllerAction action = (ControllerAction) actionMap.get(op);
if (action != null) {
action.service(request, response);
} else {
String url = "views/errorMessage_v.jsp";
String errMessage = "Operation '" + op + "' not a valid for in '" + request.getServletPath() + "' !!";
request.setAttribute("message", errMessage);
request.getRequestDispatcher(url).forward(request, response);
}
}
And here is the Generic DeleteAction:
public class DeleteAction implements ControllerAction {
private Form form;
private Object obj;
private String schema = null;
private String xPage;
private String yPage;
public DeleteAction(Form form, Object item, String schema, String yPage, String xPage) {
this.form = form;
this.item = item; //passed in javabean??
this.schema = schema;
this.xPage = xPage;
this.yPage = yPage;
}
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
item = form.delete(request);
/* Database schema is described in xml files.
Hash maps of field names, sizes, and titles; foreign key names, titles,
lookup tables; and primary keys information are used to dynamically
build HTML forms in the views.
*/
HashMap test = ReadTableSchema.returnSchema(schema);
HashMap hshFields = (HashMap) test.get("hshFields");
HashMap hshForeignKeys = (HashMap) test.get("hshForeignKeys");
HashMap hshPrimaryKeys = (HashMap) test.get("hshPrimaryKeys");
request.setAttribute("hshFields", hshFields);
request.setAttribute("hshPrimaryKeys", hshPrimaryKeys);
request.setAttribute("hshForeignKeys", hshForeignKeys);
request.setAttribute("item", item);
request.setAttribute("form", form);
request.setAttribute("pageName", "Delete");
//Check for deletion authorization if successful forward to the confirmation page
if (form.isSucces()) {
request.setAttribute("message", "Please confirm permanent deletion of the data below.");
RequestDispatcher view = request.getRequestDispatcher(yPage);
view.forward(request, response);
} else {
// Not authorized to delete the data so just re-display
RequestDispatcher view = request.getRequestDispatcher(xPage);
view.forward(request, response);
}
}
}
then here is the interface (right now just for delete) that will be used by all forms.
public interface CRUD {
public Object delete(HttpServletRequest request);
}
You can't instantiate an interface, you need a concrete subclass for that. However, creating concrete subclasses just increases the number of classes, which you are trying to avoid. It is better to use composition instead of inheritance.
Namely, if you manage to make a common interface for the forms, and hide the actions deleteCommitmentItem, deleteProgram etc. behind one single method, you can parametrize your action instances with the required form (or a factory to provide this), e.g.:
public class GenericAction implements ControllerAction {
private Form form;
private String page;
GenericAction(Form form, String page) {
this.form = form;
this.page = page;
}
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException {
Item item = form.performDelete(request);
RequestDispatcher view = request.getRequestDispatcher(page);
view.forward(request, response);
}
}
...
CommitmentListDAO clDAO = new CommitmentListDAO();
CommitmentItemForm ciForm = new CommitmentItemForm(clDAO);
GenericAction deleteCommitmentAction = new GenericAction(ciForm, "views/commitmentView_v.jsp");
ProgramDAO prgDAO = new ProgramDAO();
ProgramForm prgForm = new ProgramForm(prgDAO);
GenericAction deleteProgramAction = new GenericAction(prgForm, "views/programView_v.jsp");
Thus you need no new classes for new kinds of actions, just instantiate GenericAction with different parameters.
It's clear by your naming that you already have implemented DAO objects (CommitmentListDAO, ProgramDAO). You should (probably) modify these classes to implement your new interface. Then your problem now becomes, how do you know which DAO to instantiate when you're in your generic delete action. Either that DAO should be passed into your action directly, or some other information on how to instantiate it (either a Class or factory) must be provided to your action.
GenericDAO is an interface, it cannot be instantiated directly. I don't know much Java, but every OOP language is pretty much the same. So what you need to do is create a concrete implementation of your interface (as a class) and then instantiate that instead. Something like this (sorry for the C# code but you get the idea):
public interface IGenericDAO {
void create(...);
}
and the implementation:
public class GenericDAO implements IGenericDAO {
public void create(...) {
/* implementation code */
}
}
Does that make sense?
One servlet per action is not unreasonable. Consider that if you have to do some action X, then you need to do X. Write a servlet to do X. It's that simple.
As you're noticing, this could lead to a lot of nearly identical servlets. That's ok because now you can use delegation (as Peter Torok recommends) or inheritance to move all the shared and abstracted code into one place. Which is better? Either is better than neither. You are 90% of the way to victory if you use one or both as appropriate.
I prefer a main servlet from which all others inherit. This allows me to wrap every service call in a consistent proper transaction in the base controller class. The subclasses never have to worry about it. This code shows the gist of it.
public class BaseControllerAction implements ControllerAction {
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException {
Connection conn = null;
try {
conn = getAConnection();
log.info("+++ top of "+getClass().getName());
conn.getTranaction().begin();
String dest = go(request, response, conn);
conn.getTransaction().commit();
RequestDispatcher view = request.getRequestDispatcher(dest);
view.forward(request, response);
} catch (Exception e) {
conn.getTransaction().rollback();
} finally {
conn.close();
log.info("--- Bottom of "+getClass().getName());
}
protected abstract String go(HttpServletRequest request, HttpServletResponse response, Transaction transaction) throws ServletException;
}
and now you can implement your servlet:
public class DeleteCommitmentAction extends BaseControllerAction {
protected String go(HttpServletRequest request, HttpServletResponse response, Connection conn) throws ServletException {
// Given what this method is supposed to do, it's very reasonable
// to refer to models and DAOs related to deleting commitments.
Long id = new Long(request.getParameter("id"));
CommitmentDAO.delete(conn, id);
return "views/commitmentView_v.jsp";
}
}
So now none of your servlets have to worry about transactions or opening and closing connections. They only have to worry about the details of their specific task. Obviously I don't know your system so I can't give detailed suggestions but this is how I did two decent-sized apps recently. They have about 30 servlets each. But the servlets are generally about 15 lines long. I ended up with a utility class that implemented the sorts of tasks needed by all the servlets. Poor man's delegation, perhaps.
Interface can't be instantiated. Instead, you should create a concrete class implementing the interface and instantiate this class.