How to structure the content of EJBs - java

I am making a simple CMS just for learning purposes and I have a question how I would organize it. I have an administration section where you can add new pages, edit content etc, and I also have a public part that the user see for example the pages.
So, I have PageEJB class that has logic for adding a page, edit a page, deleting a page, finding a page etc. in other words logic from the admin section and public section is in the same class. Should I instead make a PageAdminEJB and PageEJB and separte the content?

Since you're doing it for learning purposes only, will you learn anything by having two EJBs instead of one?
I'd say: start with one, see how it grows. When it reaches critical mass (when you see it does too much), refactor it. This way you'll learn how hard/easy is to introduce a new EJB to your system. Perhaps the facade design pattern will help you then.
Based on what you wrote, it's difficult to advise decisively one way or the other.

Related

JSP and MVC Best Practices

I am new to JSP programming and am writing a web app for a family member. As I study, I hear a lot about how JSP's are supposed to be used for presentation and servlets are for business logic. My question is basically about how far that goes and when my use of JSTL would be bad practice. Here's an example: I have a login page for my app, and I am using c:if's with custom functions connected to my java classes to process the form. Would that be considered poor MVC practice or, since I'm only referencing my logic code from EL, is this a legitimate use of JSP's?
Your question contains a lot of what are best-practices which invokes a lot of opinion and debate, which is usually frowned upon in this forum. In general, the JSP is the "V"iew in MVC and should be used to present the data provided by the "M"odel which would be your Java code. The "C"ontroller is often scattered between the M and the V (inviting more debate, sorry).
Any logic you put in your JSP that is beyond looking at the data given you and deciding how to present it, moves it towards the Model. Your login page should just collect the credentials and present them to the Model, which should in turn respond with "Invalid" and re-request the credentials (or fail completely) or if valid, move on to the next page.
In practice, IMHO, you should not put a lot, if any, code that manipulates the data except for formatting it - creating table entries, wrapping with links, etc. You should not (IMHO) query databases, perform calculations, etc., in the JSP - let the Model do that.
As duffymo stated, JSPs are old, but they are still valid. I would suggest that you also consider AngularJs (ng) (after reading about the controversy of V1 v. V2).
JSP is an outdated technology and there are very few Softwares that still use it. But if you want to use it I would suggest that you use Oracle Coding Standards with it. This page should give you a clear idea of what you should and shouldn't do with it.
The best practice with JSP - is not to use JSP at all. I’ll try to explain why and be clear.
First I have to explain something that does not have a connection to JSP at all, but it will help you to understand exact problems with JSP technology.
In functional programming there is a term - pure function. It means that it does not have side effects. Additionally, such function does guarantee that for each invocation with the same input it ALWAYS return the same output.
In OOP functions are not pure. It may have side effects. It makes our life more complicated. But what is important is that these side effects can happen only WITHIN your function. You can debug it. More or less it is UNDER YOUR CONTROL.
Let’s imagine our functionality written in JSP as a function f with input I and output O:
O f(I)
The first problem with JSP is that it DOES have side effects AND such side effects can happen not only inside of your function f, but also can affect it from outside. A simple example: you use tiles technology, your jsp page is used as a component in a tiles template. Another component of this template uses getOutputstream() method and writes to this output stream. But an application can either call getOutputStream or getWriter on any given response, it's not allowed to do both. JSP engines use getWriter, and so you cannot call getOutputStream. And you get in your jsp page that works fine when it is alone:
java.lang.IllegalStateException: getOutputStream() has already been called for this response
getOutputStream() has already been called for this response
With a function you get explicitly input parameters. The input is always clear. Additionally you can use constants or, if your function has side effect use another service to get data for processing. But it is always WITHIN your function and more or less under control. With JSP pages you do not have such control at all. Input data can be put into session with different servlets/web components, input data can be put into request scope via servlet with a lot of if statements. You must first investigate a logic of this servlet. It is additional complexity that is not obvious when you create “Hello World!” program, but that really makes you crazy when you maintain such pages, written several years ago.
I think you have already read that mixing both output and logic is not a good idea. JSP allows people to do that. Cause it is “so convenient”.
You cannot test logic within your jsp pages. Or it makes it more difficult.
You can say that correct usage of jsp technology and applying best practices resolve most of issues. Yes. Agree. But it will never get rid of its internal drawbacks and complexity. You always have to check, really developers followed best practices or not? There are better, much better technologies our days.
Note: the only exception, or use case, when I’d personally would use it: for localisation. You do not have get all messages from server. You do not want to ask a server to get a localized string one by one. You do want to get a batch of values, that will be used on your web form, for instance. With JSP + JS you can do that very easily and explicite.

JSP internationalization RTL/LTR

I want to create a web site which can be viewed with two languages, one LTR and one RTL. This means that all content should be shown in either of the two languages.
My framework is Spring, and I'm using Tiles2, but I think this question is not framework specific.
The obvious solution to supporting two languages is having everything doubled (all JSP's, fragments, etc.), and you get the part of the tree which fits the language you chose. But this causes problems when changing the web site (you might forget to update the other JSP's), and is not scalable (try doing this for 5 or 10 languages).
I know I can use properties files to host strings for the different languages, but then my web site would be a huge collection of spring:message tags and will be a lot harder to maintain (what happens if I have a paragraph of 100 lines, does this all go into a single properties line?)
Is there any kind of framework, plugin, other, which solves this problem? Has anyone come across a clever solution to this problem?
I've never realized a complete project, just some tests. I think this problem is not so big as it seems if you follow some simple rules. Here is what I would try to do:
Specify direction with <body dir='ltr/rtl'>. This is preferred versus CSS direction attribute.
Avoid different left/right margins or paddings in all CSS. If you must break this rule, probably you'll need to use two different files (ltr.css and rtl.css) containing all these different elements.
Sometimes you'll need to move some elements from left to right or vice versa. For example, in LTR you want a menu on the left, but in RTL you want it on the right. You can achieve this using CSS, but this sometimes is complicated if you are not an expert and you must test it in all browsers. Another option is to use some IF depending on the case. This last option will fit very well if you use a grid based CSS library, like Bootstrap.
Choose carefully which CSS and JS libraries you'll use. Obviously, pick the ones which offer RTL/LTR support.
Don't worry too much about the images. If you must change one image depending on the language is probably because it has some text in it. So, you must use different images anyway. This is a problem related to i18n, not a text direction issue.
Don't let your customer to be too much fussy about it. I think that with these rules (and maybe some more) you can get a good result. But if your customer starts complaining about one pixel here and another one there, you'll need to complicate all this and probably is not necessary.
About your language properties file. Yes, use them. Always. This is a good practice even when you are only using one language: HTML structure is separated from content, is very easy to correct or translate, some words or sentences are in only one file...
Usually, web frameworks are used to build web applications rather than web sites, and there are quite few long static paragraphs. Most of the content is dynamic and comes from a database. But yes, the usual way of doing is to externalize everything to resource bundles, usually in the form of properties files.
Putting a long paragraph in a properties file doesn't cause much problem, because you can break long paragraphs into multiple lines by ending each line by a backslash:
home.welcomeParagraph=This is a long \
paragraph splitted into several lines \
thanks to backslashes.
RTL and LTR is one of the upper and more difficult i18n problems.
Basically its a Problem of the view-scope of the MVC-Model. This may also includes pictures and emotional differences like the color of the skin of people. In this case you better abadon to the solution HTML+CSS gives you.
In example:
<style type="text/css">
*:lang(ar) { direction:rtl }
*:lang(de) { direction:ltr }
</style>
The best practice is to ask members of the audience-group about what effect the webpages have to them.
I agree to most of solutions provided here. Your problem is more design (architecturally) oriented rather than technical. You need to choose path whether you need to keep this logic of internationalization on server (java) side or in static files.
In case you want to go for java side (preferable solution), you need to keep two properties file and use jstl tags. This minimizes your work in case you want to add another language in future. This is maintainable solution. I have seen applications supporting more than 15 languages and time zones. In fact release process gets pretty easy.
In case you want to go for keeping multiple css and other static files, you will soon find things running out of your hands pretty soon. I dont think this is a maintainable solution.
Said all this, I will leave this choice to the architect of application. He will be able to judge which way to go based upon the nature of application and constraints given to him.
You don't want to use everywhere. That's a pity because it is just the way you should do it. It is a bad practice to keep hard-coded texts in a jsp if you need internationalization.
Furthermore, Most of the modern IDE allows you to go to the variable declaration by doing ctrl+left click (or hovering the key) so that having a lot of variables in your code should not be a problem for maintenance.
First, you must distinguish, for each text element, whether it is a user interface element (e.g. button label) or redactionnal content.
user interface element labels will be stored in properties file that will have to be translated for each supported language (and provide a default value as a fall back)
redactionnal content will be stored in a content management system that you will organize in order to find easily a localized version of your content

Java - Trying to plan the layout of a programs classes

I'm having a bit of trouble figuring this out so if you can help that would be great.
I have written a bit of code that gets a list of URLs from a sitemap. I then go each page, scrape all the links, and then test their status(200,404, etc).
I am using HttpClient. I have it all working OK but as I am new to Java I reckon my code is a complete hack/maze and I could most likely get far better performance if it was organised correctly. So what I have is
Main class - This builds the gui
Parse the sitemap class - This parses the sitemap and get a list of the urls.
Class called PingURl - I'm sure my above is poor but this is the bit I reckon is worst. This class opens all the urls, scrapes them for links, then tests the links for their status and returns it. I presume this class should be broken down? Most importantly I think I should be isolating the testing of the links in it's own class, so it would be easy to implement threads later on?
Basically I'm looking for advice. If someone could help me with laying out the project a bit better. Secondly I believe this is my weakest area so to improve I need to learn more about this, I don't even know what to call this(design/layout problem?). Can you also recommend resources to learn more about this?
Java is a language which IMO, embodies good OO design. Designing with OO in mind is very effective.
http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/oo.html
In terms of your problem, I think it works pretty well. You are kind of following a Model-View-Controller pattern: http://www.codinghorror.com/blog/2008/05/understanding-model-view-controller.html
I can't tell you how to design your code, but I will tell you how I would do it if I were presented with the same problem:
I would get a class to represent a hyperlink. In that class there would be the hyperlink that has been scraped, and a getter and setter. As well as a boolean value and a ping function. That means that if I create a "hyperlink" object, then I can invoke ("ping") on that object because it is part of that class. That means that the ping function simply sets the boolean that represents connectivity.
That way, your parser basically gets a page, and for each link it finds, it creates a new "hyperlink" object based on your own "hyperlink" class. And puts it in an array. So once your parser executes you get an array of pointers to hyperlinks.
Then all you have to do is invoke the ping function on each one to see if it is there.
I think this design is the best because it scales from doing one hyperlink test to doing 1000 quite easily.
There is soooo much stuff out there about design, there are countless principals as well. There is never one absolute way to solve a problem. But the more experience you get, and the more you read up on design patterns and models the better you will get at it :)

Decorating a multi-client webapp

I have a web-app in Java, Spring, Struts 2 and Hibernate, that servers multiple clients. Each client with multiple users. To create a personal feel for each client, i would like to customize the header for each client.
I'm using sitemesh as decorator, and am looking for tips or examples or someone who can point me in the right direction as to how to acomplish this in the best practice.
What would you think? Should i just code it direct in the header.jsp? Extracting the info about the logged in user and from that create a custom header by code? Or is there a more clever solution out there?
Thanks!
Update:
To further clearify what i want:
Different properties-files for each client is not an option. We are looking at potentionally hundreds of clients. It needs to be database-driven. But thats the easy part. There is no problem storing the information in db and extracting it when needed.
What im trying to figure out is if there is some sort of standard way of doing this. Some sort of filter or Action that is run before the sitemesh decorator that will provide the decorator with the correct info?
Struts2 provides application scope, for variables which are global to the application.
Load all the customer specific strings into #application scope (I would use spring to do this when the application starts up). From there referencing the strings would be pretty obvious: #application.greeting I don't like the idea of using an interceptor because there is nothing to intercept. I would say for what you are doing application scope is the perfect place. If it is a single client system I can see no reason why anything would be stored in application scope.
Aside: Tiles uses a different template paradigm than site mesh, and they have slightly different purposes. As such the two can be complimentary. Tiles relying on XML definitions can have it's definitions stored in a DB and is definitely less computationally intensive, however where there is interplay between different UI components... or disparate elements appearing on the page you need to use sitemesh. So for basic template needs tiles does everything and is quite easy to understand but say you wanted to make add a certain widget in the middle of the page which relies on JS which needs to be added to the header it would be tricky to do this in Tiles (although the obvious solution is to just roll the JS functionality into one JS file for all possible uses in a particular part of the site).
Asside 2: By using a view technology such as velocity or freemarker in conjunction with tiles it is conceivable to move the entire view layer into a database. I just thought I would mention that as for some maintenance issues that could be extremely beneficial.
Sitemesh makes it's decisions about what decoration to use based upon the requested URL string, so unless you have a reference to the client in every url - either as part of the main url string or as a known parameter, then Sitemesh out of the box is not going to help.
This leaves a few possibilities to achieve what you want;
1) Write a filter that runs before Sitemesh that adds, for example, "&clientId="xx" to every incoming request.
2) Dive into the source code for Sitemesh & look for where Sitemesh finally makes it's decision about which decorators to use and override it. I've never tried this so I don't know how practical this might be.
3) Make the style sheet definition in your jsp pages an OGNL expression and provide that information in a base action class that all your actions extend. In this way you end up with (potentially) a different CSS file for each client and you provide your customisation via CSS.
Hope that this helps.

How do you structure a java program? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
For quite awhile I have been trying to make a simple "game" in Java that is really just an applet with a square and a grid. What I want it to do in the end is the user clicks and the square will move to where the user clicked rounded to the nearest grid square.
The problem is I am a self taught beginner and I am having a hard time figuring out how to actually structure the program, some examples:
should I have a separate class listening for mouse clicks?
When I receive a click should I send it to some other object that represents the box and let it decide what it wants to do or just call some function that makes the box move?
I really want to learn all this "when to use what" stuff for myself so any links or general advice is appreciated.
What you're really asking is how to develop a game, which is notably different from a typical Java application. However, I'll give you a few ideas to at least point you in the right direction.
Take advantage of the fact that Java is an object-oriented language. That is, objects should each have their own responsibility.
Separate your game into three key layers: the application layer, the game logic layer, and the presentation layer.
The application layer should contain all of your helpers and generic subsystems, things like random number generators, text parsers, file access modules, mesh loaders, etc.
The game logic layer should implement all of the rules of your game, and be responsible for maintaining canonical state. Basically, when you press the "W" on the keyboard to move forward, the game logic layer should receive MOVE_FORWARD_REQUEST from the UI.
The presentation layer should be responsible for two things: getting input, and rendering your world. When it gets input, like the "W" key, it should map that to an action, and send that to the game logic layer to be processed. Then, it should render the world based on whatever the game logic told it to do.
Game development is obviously an entire realm with many books dedicated to it. One of my favorites is Game Coding Complete, which does focus on C/C++, but should give you a good idea about how you ought to structure your game.
Good luck!
One main principle of good software development is the Single Responsibility Priciple. It states that a function or class should only have one responsibility.
This way your classes and objects shouldn't become too big and unmanageable.
I think one of the most important concepts to master when developing software is the concept or Orthogonality. It's not the simplest definition, but in essence it means that one component (such as reading mouse clicks) shouldn't be directly tied to an unrelated component (moving a square on the screen).
In your case, the code reading mouse clicks should be separate from the code that actually moves the box. Whether you implement this as inner/anonymous classes or not is up to you. But if you follow the Orthogonality principle, it will be easy to change at a later date should you change your mind.
One problem here is that all the rules have some leeway in them where you have to use your own best judgement.
For example, the app you are describing now seems to me so simple I'd probably do it in a single class, with perhaps a couple of nested, perhaps anonymous classes. In any event, I could make a decent case for fitting the whole thing into a single source file, claiming that multiple source files would actually increase the complexity of the whole thing.
But if your GUI had a number of different controls, perhaps each controlling different behavior, it would become time to split the functionality up so you're not ending up with a big bowl of spaghetti code.
The Java GUI libraries try to naturally separate (view+controller) from model. You are encouraged to define and display the GUI in one module (= file) but to have your data model and perhaps functionality in another. For complicated GUIs, there may also be multiple GUI implementation modules held together by code.
One way to keep things "clean" is to work in "layers" where each layer "knows" only what it needs to know. To be specific, the GUI layer needs to know about the existence of its underlying models – tables and lists and whatnot need to be connected to TableModels and ListModels, etc. It doesn't need to know about details of these models though, so it can simply refer to those models by interface.
The model layer, on the other hand, need know nothing about the GUI. The less it knows, the better, and this would theoretically enable you to exchange GUIs without needing to touch the models.
My model can also contain ActionListeners to respond to actions undertaken by e.g. pushing buttons in the GUI.
Of course, actions and changes to the model will often result in changes to the GUI. How to communicate these changes to the GUI if the model layer doesn't know about the GUI? You can use bound bean properties here. Here's a short tutorial: http://www.javalobby.org/java/forums/t19476.html . So you have the same kind of structure: Changes happen in your model, they're communicated to beans with property change support within the model, and the GUI can attach listeners to those properties to find out something changed.
Whether you perform actual, effective actions (e.g. writing files, converting data, whatever) within your model code or whether you split "processing" code off into yet another module is up to you and will again depend on how cluttered your model already is. If there's a tiny handful of fields and methods feeling lonely in there, you may decide to mash things together but the moment it starts to look messy you'll want to refactor your processing code out into its own module. Processing sounds like the kind of module that doesn't want to know about other modules either; you may end up just calling its methods from the model level.
I've described my basic style for doing GUI development. There are certainly other recommendations out there, and you will likely develop your own style based on your experience. This is just intended to give you an idea and a possible starting point.
Step 1 - find the demo applets supplied by Sun. http://java.sun.com/applets/jdk/
Step 2 - read those demo applets. At least three. Preferably all of them.
One you've read several applets, you should see a little more clearly how to organize programs. You can then ask questions with a lot more focus pointing to specific applet examples and your specific programming problem.
Yeah, I'm a beginner programmer myself. Yeah, segregating functionality across multiple classes is a good way to reduce complexity and increase cohesion of individual classes.
Increasing cohesion good because by having more complex data structure your algorithms become less complex and your code is less dependent on each other.
For instance in your case it might be a good idea to separate the classes in accordance to MVC (Model View Controler).
You have a Model which represents the way your game data is structured.
You have a Viewer which present your Model in what ever form you please.
Have a Controller which picks up changes in the Model (via Listeners) and then updates the Viewer
Now you can change your Model and add extra functionality requiring only small changes in the way the Viewer works.
There are many Patterns out there but there isn't a hard rule when to use one over the other. There are some cases in which you can use several and there are cases in which will require you to chose one design pattern over the other.
Every beginning Java programmer should start with the Sun Tutorials. They are quite good.
Another good source, especially among free sources, is Bruce Eckel's "Thinking in Java", available from http://www.mindview.net/Books/TIJ/.
But the latter is a little dated compared to the former. That is why I recommend both.

Categories