Should class names contain name of package? - java

I have to implement a logging mechnism in Java.
So I use JEE and use RequestFilter and Interceptors.
I put all that in a package called logging.
My classes are: RequestFilter, ResponseFilter and Constants
So my question. Is that ok to leave out logging in the class name because it is present in the package already ?
Or should I rather do. package logging and duplicate logging: RequestFilterLogging, ResponseFilterLogging, ConstantsLogging

It really depends on a few questions:
1- Is the purpose of RequestFilter to always log only?
2- Is there a plan for you to modify it to add further logic? For example customizing headers of requests, etc?
3- Do you plan on having more than 1 RequestFilter and specifying priorities?
If your design is to have multiple request filters, each doing their own custom logic, with priortization, then I would do it as such:
com.app.requestfilters
--> LoggingRequestFilter
--> HeadersRequestFilter
If your design is to have 1 RequestFilter that does a lot of things, not only logging:
com.app.requestfilters
--> CustomRequestFilter
In my opinion, it is best to not reuse class names that exists in libs/frameworks that you are using:
In Apache Tomcat, there is a RequestFilter, and if you are extending this class, then yours should be a different name
https://tomcat.apache.org/tomcat-7.0-doc/api/org/apache/catalina/filters/RequestFilter.html

Related

Akka constructor wiring via spring

I have read the links
Akka and spring configuration
http://doc.akka.io/docs/akka/2.4.1/java/untyped-actors.html
Spring is no longer available as a module in Akka 2.4.1 but can be created and used as an extension. I also understand that the concept of bean/actor creation being managed by DI-fwk like Spring can cause fundamental conflicts with the Akka Actor parent-child/supervision model. So I still don't understand how to wire these together.
I have a set of actor classes and I have written them to be generic enough for example: properties like "listener", "name", "messageQueueName" etc are configurable. The link above tells me that I provide convenience factory constructors and then create actor with the code snippet
system.actorOf(DemoActor.props(42), "demo");
It is this line that I do not like. What I want to write in my application.conf is something like
deployment {
/demo {
magicNumber : 42
}
}
and then in all my application I simply want to look up the actor (I am okay to use the actorSelection) method.
Am I doing something wrong?
I think you are on the wrong path there, you should have a look at these tutorials:
http://www.lightbend.com/activator/template/akka-java-spring
https://myshittycode.com/2015/08/26/akka-spring-integration/
and for passing arguments via constructors check my answer to this question:
Custom Spring Bean Parameters
The configuration file is used for akka specific parameters (like specifying the dispatcher, mailbox, etc.)

Accessing a Filter object through a WebApplicationContext

I want to call a method on a Filter object after it has been added according to the web.xml definition. All I got is a WebApplicationContext object (let's call it: wac).
I'm able to add new Filter objects via: wac.getServletContext().addFilter("otherfilter", otherFilter);
Also, I can test successfully for its existence via: wac.getServletContext().getFilterRegistration("myfilter")
But how may I access (and possibly modify) Filter objects which have been added before?
I'm not sure how to do it exactly as you want, but this problem is usually solved using different approach.
You can declare your Filter as a bean in your application context and then register a DelegatingFilterProxy in web.xml to delegate filtering to your filter.
In this case your filter will be a regular Spring bean, and you'll be able to access it like any other bean.
The Servlet API does not provide any mechanism to directly access a Filter instance once it has been added to a ServletContext. The best you are going to get with the Servlet API is the FilterRegistration interface you have already found which lets you modify the same set of configuration options as you can via web.xml.
Depending on exactly what you want to do, you might be able to code your way around this problem using init parameters but that is never going to be a particularly clean solution. I'd go with the DelegatingFilterProxy solution suggested by axtavt.

Configure a Service .. with XML ( instead of properties )

i have a ( bnd-annotated ) component that implements a simple api and exposes itself as a service
package com.mycompany.impl;
import com.mycompany.api.IFoo;
#Component(designateFactory=FooImpl.Configuration.class)
class FooImpl implements IFoo {
interface Configuration {
String foo();
// ..
}
Configuration configuration;
#Activate
public void activate(Map properties) {
configuration = Configurable.createConfigurable(Configuration.class, properties);
// ..
}
}
its configuration is loaded from a watched directory by Felix FileInstall and the service is instantiated by the Felix Configuration Service ( at least, i assume thats whats happening - i’m new to OSGi, please bear with me ) This, with the generated MetaType descriptor is working great.
However, as it stands, FooImpl requires structured configuration ( lists of lists, maps of lists..etc ) and i was wondering if there is an elegant ( * ) way to configure instances of the component through a similar workflow; that is to say, configuration discovery and instantiation/deployment remains centralised.
It seems to me that the Configuration Service spec manages maps - will i have to roll my own Configuration Service & FileInstall to be able to present components with xml/json/yaml backed structured configuration?
as opposed to, say, defining the location of an xml configuration file in properties ...confiception ? and doing my own parsing.
Yes and no...
The OSGi Configuration Admin service deals with abstract Configuration records, which are based on flat maps (actually java.util.Dictionary, but it's essentially the same thing). Config Admin does not know anything about the underlying physical storage; it always relies on somebody else to call the methods on the ConfigurationAdmin service, i.e. getConfiguration, createFactoryConfiguration etc.
The "somebody else" that calls Config Admin is usually called a "management agent". Felix FileInstall is a very simple example of a management agent that reads files in the Java properties format. Actually FileInstall is probably too simple and I don't consider it appropriate for production deployment — but that's a separate discussion.
It sounds like you want to write your own management agent that reads XML files and feeds them into Config Admin. This is really not a large or difficult task and you should not be afraid to take it on. Config Admin was designed under the assumption that applications would have very diverse requirements for configuration data storage, and that most applications would therefore have to write their own simple management agent, which is why it does not define its own storage format or location(s).
However, once the configuration data has been read by your management agent, it must be passed into Config Admin as a map/dictionary, which in turn will pass it to the components as a map. Therefore the components themselves do not receive highly structured data e.g. trees or nested maps. There is some flexibility though: configuration properties can contain lists of the based type; you can also use enum values etc.

Spring MVC Request mapping, can this be dynamic/configurable?

With Spring MVC, I know how you set the RequestMapping in every controller and method/action.
But what if I wanted this to be configurable, so for example I the following controllers:
BlogController
- with methods for listing blogs entries, single entry, new, update, etc.
ArticleController
- with methods for listing articles entries, single entry, new, update, etc.
Now in my application, the administrator can setup 2 blogs for the webiste, and 1 article section so the urls would be like:
www.example.com/article_section1/ - uses ArticleController
www.example.com/blog1/ - uses BlogController
www.example.com/blog2/ - uses BlogController
Maybe after a while the administrator wants another article section, so they just configure that with a new section like:
www.example.com/article_section2/
This has to work dynamically/on-the-fly without having to restart the application of course.
My question is only concerned with how I will handle url mappings to my controllers.
How would this be possible with Spring MVC?
I only know how to map urls to controllers using #RequestMapping("/helloWorld") at the controller or method level, but this makes the url mappings fixed and not configurable like how I want it.
Update:
I will be storing the paths in the database, and with the mapping to the type of controller so like:
path controller
/article_section1/ article
/blog1/ blog
/blog2/ blog
..
With the above information, how could I dispatch the request to the correct controller?
Again, not looking to reload/redeploy, and I realize this will require more work but its in the spec :)
Would this sort of URL mapping work for you?
www.example.com/blog/1/
www.example.com/blog/2/
If yes, then that's easy: Spring 3 supports path variables: http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html#mvc-ann-requestmapping-advanced
Alternatively, you can create a generic request mapping and your own sub-dispatcher that reads a config file, but I think that's probably more work than it's worth.
Truly changing the request mappings at runtime might be hard (and not really recommended, since small errors can easily occur). If you still wish to do it, perhaps JRebel, and more specificly LiveRebel can be interesting for live redeployment of code and configuration.
Otherwise, like other posts suggested, RequestMappings supports wildcards, the limits of this should be clear after a quick read of the official documentation.
Try using with #RequestMapping wild cards as below:
#RequestMapping(value="/article_section*/"}
public void getArticle(....){
//TODO implementation
}
#RequestMapping(value="/blog*/"}
public void getBlog(....){
//TODO implementation
}
Hope this helps!!!
Also another solution might be to create a custom annotation that holds the already defined path on the #RequestMapping and also the new one to apply, let's say #ApiRestController.
Then, before the Spring context loads, the #Controller classes can be changed to have their annotation values changed at runtime by the new one (with the desired path). By doing this, Spring will load the enhanced request mapping and not the default one.
Created a small project to exemplify this for someone that needs this in the future https://gitlab.com/jdiasamaro/spring-api-rest-controllers.
Hope it helps.
Cheers.
doesn't this work?
#RequestMapping("/helloWorld*")

A servlet or filter that dynamically maps /xxx/yyy/zzz to class XxxYyyZzz.java

I want to write a servlet or filter that automatically maps the url /xxx/yyy/zzz to class XxxYyyZzz.java.
For example the following URLs will map to the following java classes:
/comment/add --> CommentAdd.java
/comment/delete --> CommentDelete.java
/comment/view --> CommentView.java
/search --> Search.java
/viewposts --> Viewposts.java
In addition the servlet or filter must comply with two extra requirements:
The servlet or filter should have a servlet mapping of "/*", I dont want a prefix with several servlets "/comment/*", "/search", etc.
Maybe difficult, but having a servlet mapping of /* should not allow it to override the JSP processing. Meaning, if a class is not found, it should check if a jsp page exists and run it.
I want to know how can this be done using the Servlet API. Please don't refer me to any framework that does the job. Just show me the code.
The classes that are mapped to will follow the command pattern or could be a subclass of the HttpServlet. In both cases, a method should exist like "execute(HttpServletRequest request, and HttpServletResponse response)". This method will be automatically executed once the URL is accessed and the java class is figured out possibly using a single servlet or filter.
I'm not sure, if I got what you mean. In case I did:
You need nothing special, write a single Servlet mapped to "/", so it gets everything. Parse the PATH_INFO (don't know now how it gets called in Java), use Class.forName (or use a pre-filled Map), and call its method execute.
Here is a http://www.tuckey.org/urlrewrite/ filter implementation that might help you. Check it out. I have not used it myself though.
You can use Stripes framework with its default NameBasedActionResolver config.

Categories

Resources