How to send request parameters to business logic [closed] - java

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 7 years ago.
Improve this question
I know that it's bad idea to embed business logic in your servlets, it's accepted to do on application server's side. Sometimes you have a lot of parameters in your request, and all of them you need to send to classes that represents your business logic. How would be better to do it? (I thought about JavaBeans but they were designed for another purpouse.)
Thanks.

You should separate your business logic into a separate class, which implements an interface, and the servlet class should simply be responsible for deserialising the input stream into some kind of request object, passing it to the business logic object, and then serialising the response. If you add a little bit of DI magic then it can become fairly simple to locate and construct the correct implementation of the business logic class to use.
Example
public interface TheBusiness {
MyBusinessResponse doProcess(MyBusinessRequest request);
}
public final class MyBusinessClass implements TheBusiness {
#Override
public MyBusinessResponse doProcess(MyBusinessRequest request) {
// all the complex logic goes here.
return response;
}
}
public class MyBusinessServlet extends HttpServlet {
private final TheBusiness theBusiness;
private final ObjectMapper objectMapper;
public MyBusinessServlet() {
theBusiness = // locate and construct implementation.
objectMapper = // Initialise Jackson deserialisation.
}
public void doGet(HttpServletRequest request, HttpServletResponse response) {
final MyBusinessRequest requestBody = objectMapper.readValue(
request.getInputStream(), MyBusinessRequest.class);
final MyBusinessResponse responseBody = theBusiness.doProcess(requestBody);
objectMapper.writeValue(response.getOutputStream(), responseBody));
}
}
The only tricky thing here is instantiating your MyBusinessClass. There are patterns for different DI frameworks which can help there. Mostly they involve using a framework-provided servlet to do all that marshalling and unmarshalling for you and you just need to code up the business logic and annotate a class appropriately. Both Spring-MVC and Jersey do that. The important thing is that the servlet class deals with all the HTTP-type interaction and with serialisation, while the logic is encapsulated elsewhere behind an interface - so each class can be well tested in isolation.

Related

Using Command- Pattern to create an object and add this to an ArrayList [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a Problem to understand the exercise.
What I have to do is:
Different users must be able to add and delete a ticket to a
ticketsystem (in a List)
I have to do this with the Command- Design- Pattern
But I actually don´t know how to do this.
I have thought about the following:
Student press the "createTicketForinsideBuildingDamage"- Button
-> this sets the "executionCommand" to "insideBuildingDamageCommand" and executes it
-> this creates a "insideBuildingDamage"- class and it asks for the data like date, type, name...
-> !!!and this has to be added to the Ticketsystemlist automatically!!! but how can I do this?
Or am I completley wrong?
I don´t want a solution like full code. But an idea, how I can do this.
Thank you
Firstly, I think you should understand how the design pattern works and how the classes interact with each other. You can see an example here https://refactoring.guru/design-patterns/command.
My way of doing it:
Command.java
// concrete commands will implement this interface
// you can also use an abstract class if you want to have certain attributes, such as a TicketSystem
public interface Command {
// this method can be set to return something useful instead of void, if needed
void execute();
}
AddTicketCommand.java
public class AddTicketCommand implements Command {
// TicketSystem and Ticket attributes
// constructor that initializes the attributes
#Override
public void execute() {
// add the Ticket to the TicketSystem
}
}
Invoker.java
public class Invoker {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void invoke() {
command.execute();
}
}
Therefore, when you want to use a certain command, you set it with accordingly. For example: invoker.setCommand(new AddTicketCommand(new TicketSystem(), new Ticket())) and then call it with invoker.invoke().
Hope it helped!

Architecture of a class, and best practice? [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 4 years ago.
Improve this question
So I am in charge of creating a project that has to do with calculations of pay. One aspect of the project is to analyze a proper input such as 4:00 PM, and other aspects including calculating the pay for the hours put in, and the type of job etc.
my question more so has to do with the best practices for designing the classes around this.
Should I have one class that analyzes the input string, and only does that? and one class for the calculator to display the proper output or should it all be in one class?
both ways are fine for me to do, but what is considered professional?
is it best practice to split classes based on their unique functionality even if you dedicate a class to simply one method?
At the boundary of your application you'll be accepting requests through a user interface or a system interface. You should treat anything originating from outside your application as untrusted and potentially wrong. For example, if you receive a HTTP request there is no guarantee that it is valid and contains the fields you expect. If you read form a file, it might be incorrectly formatted.
There should be a layer at the boundary of your application which takes input (which is just a bunch of bytes in the end) and turns it into a representation as Java objects of the suitable type (e.g. Boolean, LocalDate). If everything is a String, you are probably doing it wrong.. If this layer is unable to do this, it should send back an error.
Once you have expressed the request as a correctly typed Java objects, your business logic should process the request. This makes it possible to use the same logic when data is provided through a different interface, separates plumbing (parsing) from business logic (calculations). It allows the business logic to be more easily unit tested.
When you output a response back to the user (or system), you should convert from your nicely structured Java objects back to the output representation at the last moment.
I suggest you take a look at the javax.validation package and the Bean Validation JSR's 1.0 and 2.0
Using this approach you can create Java classes to represent your data and annotate them with the required validations. Triggering the validation to happen depends a little bit on the context.
In a Spring Boot application putting #Valid on the received controller parameter does the trick. See also this cheat sheet:
import javax.validation.Valid;
import com.company.app.model.Article;
#Controller
public class ArticleController {
...
#RequestMapping(value="/postArticle", method=RequestMethod.POST)
public #ResponseBody String postArticle(#Valid Article article, BindingResult result, HttpServletResponse response){
if(result.hasErrors()){
String errorMessage = "";
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
List<ObjectError> errors = result.getAllErrors();
for( ObjectError e : errors){
errorMessage+= "ERROR: " + e.getDefaultMessage();
}
return errorMessage;
}
else{
return "Validation Successful";
}
}
}
In a standalone application it could be done like this:
public class BeanValidationExample {
public static void main (String[] args) {
Configuration<?> config = Validation.byDefaultProvider()
.configure();
ValidatorFactory factory = config.buildValidatorFactory();
Validator validator = factory.getValidator();
factory.close();
Person person = new Person();
person.setDateOfBirth(new Date(System.currentTimeMillis() + 10000));
Set<ConstraintViolation<Person>> violations = validator.validate(person);
violations.forEach(v -> System.out.println(v.getPropertyPath() +
"- " + v.getMessage()));
}
}

Intercept outgoing HTTP requests [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
so I'm looking for a library or some way of intercepting any outgoing HTTP requests from my Java application? Why? Because I want to unit test an API integration and since I'm using a library (wrapper) for that API, I can't modify any of it's code. It's not my code that's actually making the HTTP requests.
So, I need to intercept them, view them and assert they are correct according to the API's documentation.
I've tried looking online, but I couldn't find the exact thing I'm looking for. Most libraries out there will let me do it, only if I configure the requests themselves properly, but I can't do that, since they're made by an API wrapper, not my code.
Cheers
P.S Some example code
String path = "/some/path";
String repoOwner = "John Doe";
String repoName = "John repo"
GitHubClient client = new GitHubClient();
client.setCredentials(this.username, this.password);
RepositoryService repositoryService = new RepositoryService(client);
CommitService commitService = new CommitService(client);
Repository repo = repositoryService.getRepository(repoOwner, repoName);
List<RepositoryCommit> commits = commitService.getCommits(repo, null, path);
This will use the API wrapper to get all the commits in a given repository. Suppose I wanted to see the HTTP requests this code is making and then I wanted to Unit Test them and assert they are correct. How would I do that? Is there any way to intercept them, catch them kind of like an exception, and do stuff with them, such as assertions?
What you're trying to do is not easy and from my point of view it doesn't make much sense.
You're trying to test your application but mostly you're trying to test the GitHubClient library.
If I were you I would use only mocks in your tests and verify the input arguments. So the test would like like this (using mockito):
List<RepositoryCommit> commits = new ArrayList<>();
commits.add(new RepositoryCommit(....));
commits.add(new RepositoryCommit(....));
when(commitService.getCommits(repo, null, path)).thenReturn(commits);
That way you avoid of the library testing.
If you want to actually investigate what the library does - what requests it sends and what is going on - I would recommend you to go through the library code, find the place where the request is actually set up and just run your app in debug mode and add a breakpoint there.
If you really want to handle (e.g. log, replicate...) the real requests to GitHub even in production you could use AspectJ for that. That would change the byte code so that you could wrap particular method calls. Again you would have to find the place in the GitHub library where the real GitHub (I suppose HTTP) call is performed and attach aspect to that call. In aspect you basically declare which method you want to intercept and what you want to do before its call or after. I'm not really expert in this area so I can't provide you more info - there is a tutorial about Aspects - https://eclipse.org/aspectj/doc/next/progguide/starting.html
Other option is also install some network watch tool like wireshark
EDIT
Other option how to avoid costly calls to GitHub is to create a simple wrapper like this:
public class GitHubServiceImpl implements GitHubService {
private Rpository repo;
/** other methods **/
#Override
public List<RepositoryCommit> getAllCommits(String path) {
return commitService.getCommits(repo, null, path));
}
}
And here is the actual service you want to test.
public class CommitService {
private GitHubService gitHubService;
private String path;
public List<RepositoryCommit> getAll() {
return gitHubService.getAllCommits(path);
}
}
and for integration tests create special implementation of the GitHubService interface:
public class TestGitHubService implements GitHubService {
private Map<String, RepositoryCommit> preArrangedCommits;
/** other methods **/
public void setPreArrangedCommits(Map<String, RepositoryCommit> preArrangedCommits) {
this.preArrangedCommits = preArrangedCommits;
}
#Override
public List<RepositoryCommit> getAllCommits(String path) {
return preArrangedCommits;
}
}
and in the test call:
public class CommitServiceIntegrationTest {
// #Autowired, #Bean maybe?
private CommitService commitService;
// #Autowired, #Bean maybe?
private GitHubService gitHubService;
public void testGetAll() {
Map<String, RepositoryCommit> preArrangedCommits = new HashMap<>();
preArrangedCommits.put("path/", new RepositoryCommit(...));
gitHubService.setPreArrangedCommits(preArrangedCommits);
List<RepositoryCommit> commits = commitService.getAll();
assertEquals(commits, preArrangedCommits);
}
}
I would go this way.
Frank

How do we actually implement the entity boundary control pattern in java? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am trying to create a library management system. Now, I know that the boundary cannot interact with the entity directly. The control class acts as a mediator between the boundary and the entity classes. However, when are the objects of these classes created?
First, lets talk about the login. The boundary will be the login form's UI created using Java Swing. The Controller class will be PersonController which contains a function called "validateUser()". The Entity class called User contains the use's information and accesses the database.
Now, I need to create the UI, fetch username & password from the UI using action listeners and then, create a User entity with the username & password, and then, call validateUser() method of the PersonController to check if the login is correct and the user is valid.
How do I do this? Where do I create these objects?
Here's my code till now:
public class MainClass { // main class
public static void main(String[] args) {
PersonController loginSession = new PersonController(); //UNSURE
}
}
public class PersonController {
public PersonController(){
LoginUI loginForm = new LoginUI(); //UNSURE
loginForm.setVisible(true); //UNSURE
}
//implementation of the validateUser() function
}
public class User {
private String username;
private String password;
private String role;
private String name;
private String phone;
private String email;
// get & set methods and accessing the database
}
public class LoginUI{
//entire code for the UI in Java Swing created using Netbeans IDE
}
To my mind the process should work something like this...
You have three elements, the UI, the model and the controller.
The UI presents choices to the user...
The model will be required to create a User object (as your UI should not have the knowledge of how this is actually achieved).
The controller will be responsible for responding to events from the UI and making decisions on what it should do.
When the user types in there values and clicks the "accept" action (what ever it might be), the controller captures that event and requests from the UI a User object. The UI takes the information entered by the user and asks the model to create a User object with these values.
The controller can they validate the User object.
At any point any part of the process may choose to throw an exception. As the UI is the only part of the system that can actually talk back to the user, it's the UI's responsibility to show these errors.
The basic work flow might look something like this...
Create the model, form and controller.
Add the model to the form, add the form to the controller.
The interaction between these distinct elements MUST be done via interfaces where ever possible. No part should know more about the other part then it absolutely needs to - IMHO.
My first step would be - get it clear in your mind what it is you want to achieve. Work out who is responsible for what and design the bridges you need to connect them together

Pluggable Error Handling Strategy [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have service object (Service A), that has some specific repetitive asynchronous task . This service object also has a supervising object (Service B). I want to handle most of the errors concerning the specific task in Service A and only inform Service B if it needs to take any additional measures (e.g. when Service A does not know how to handle the error).
Since Service A depends on external resources (e.g. network availabilty) there are many different exceptions, that can be thrown and I do not know all of them right now.
Because of that I would also like to have a pluggable eror-handling strategy inside Service A so that it can handle different exceptions differently. I would like to plug in those stratgies using my IoC container.
Example A:
Service A is supposed to download something every 30 sec. (polling), but the URL is malformed so a MalformedURLException is thrown. A looks up the error handling strategy for MalformedURLExcpetion and in this case the strategy will mean canceling the download and informing Service B (the supervisor) via a callback.
Example B:
Service A is supposed to download something, but the hostname cannot be resolved. Again an Exception is thrown (sorry don't know exact type now) and the corresponding strategy will be looked up: in this case the download should be stalled and retried at another time until a certain threshold is hit.
My problem now: How should I implement this dynamic lookup of error handling strategies and the strategies themselves? Is there a pattern for that?
Well, the easiest and straight forward solution would be tu use plain java try catchs, not that flexible, but often useful enough as error handling strategies does not change that often. Those exceptions you can not catch are declared on the method to may be thrown, and may be handled by your Object B.
If you wanna be more flexible. Create an interface for your service A with all the possible exceptions declared. Implement that interface with logic but without any error handling. Then you could create ErrorStrategy objects that implement the interface as well and delegate incoming calls to another implementation of that interface, BUT and this is the interesting part append some error handling strategy for one or more particular exceptions. Here is an example to make it more understandable.
public interface A {
void someMethod() throws IOException, MalformedURLException;
}
class AImpl implements A {
#Override
public void someMethod() throws IOException, MalformedURLException {
// here goes your business logic
}
}
class ErrorHandlerOne implements A {
#Override
public void someMethod() throws IOException {
try {
delegate.someMethod();
} catch (MalformedURLException e) {
// handle the exception
}
}
}
If you wanna be even more flexible, I would recommend to use AOP mechanisms instead of the simple delegation chain, that way you can easily plug-in and exchange your error handling strategies. If you use Spring and your Service A is a Spring-Bean you could easily use Springs build in AOP support. In that case the after throwing advice is what you looking for.
After throwing advice: Advice to be executed if a method exits by throwing an exception.
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterThrowing;
#Aspect
public class AfterThrowingExample {
#AfterThrowing(
pointcut="com.xyz.myapp.A.someOperation()"
throwing="ex")
public void doRecoveryActions(IOException ex) {
// ...
}
}
Keep it simple and use plain exceptions.
They are already meant to implement different error handling strategies: you can catch different exception and act accordingly. You can implement your own error handling scheme as long as exceptions remain, well, exceptional. Otherwise if it's really control flow, you should think about it differently.
Here is one in pseudo-code:
CannotDownloadException. When the download is realy not possible. Fatal error.
RetryDownlaodException. When the download is momentary not possible. Can implement retry logic.
The names are not so good, but it illustrates the principle.
class ServiceB {
private serviceA serviceA;
public download( URL url ) throws CannotDownloadException
{
try
{
serviceA.download( url );
}
catch( RetryDownloadException ex )
{
// you could have here something more elaborated that would
// perform a retry strategy based on a configuration (e.g. the number of retry,
// or the interval between retry)
try
{
sleep( 10 sec );
serviceA.download( url );
}
catch( RetryDownloadException ex )
{
throw new CannotDownloadException();
}
}
}
}
class ServiceA {
public download( URL url ) throws DownloadException
{
try
{
if( ! url.isValid() )
throws new CannotDownloadException();
serviceA.download( url );
}
catch( ConnectionException ex )
{
throw new RetryDownloadException();
}
}
}
Try Observer pattern. In general, your ServiceA should have methods like addFirstTypeExceptionsListener (ServiceListener l) addSecondTypeExceptionsListener (ServiceListener l)
or addExceptionListener (ServiceListener l, ExceptionTypeEnum type).
Your ServiceB then should implement ServiceListener interface which will probably have method like handleException (Exception e);
If we abstract away from your question then it's a bad practice to use exceptions for flow control.

Categories

Resources