Best way to handle MultipartFile on Spring Boot? [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 2 years ago.
Improve this question
I am using Spring Boot 2 and spring-boot-starter-web I have a controller where I receive file and string id
#PostMapping(
value = "/attachment/{applicationId}", consumes = {"multipart/form-data"})
public ResponseEntity attachment(#RequestParam("file") MultipartFile file, #PathVariable String applicationId) {
This project just persist the file into mongo data, so the service just create ths document and persist it
I would like to add some validation to MultipartFile File, like size file, extension file and virus scan.
I was thinking on add a HandlerInterceptor class to intercept the request, make the validation and then continue if I get success or just decline the transaction.
or I can adding Service Class to do the same
but what option is the most elegant or the best way to do that??

I personally prefer this way.
In the very first line of your controller, call the validation method like validateUploadedFile(file) and perform the needed validation.
The validation would look something like this.
private void validateUploadedFile(MultipartFile file) {
validateExtension(file);
validateFileSize(file);
}
private void validateExtension(MultipartFile file) {
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
if (!"png".equals(extension) && !"jpeg".equals(extension) && !"jpg".equals(extension)) {
throw new InvalidFileExtensionException("Only jpg/jpeg and png files are accepted");
}
}
private void validateFileSize(MultipartFile file){
if (file.getSize() >= MAXIMUM_FILE_SIZE_ALLOWED) {
throw new BusinessException("File size cannot be greater than 5 Mb");
}
}
PS: The FilenameUtils class is from org.apache.commons.io I am only accepting files with extension jpg,jpeg and png.

Related

How to call a private method inside the controller? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 days ago.
Improve this question
I have a file (suppose x.java) where I have a public function:
private Response getResponse(Long id, Long digit)
{
// do Something
}
And I need to call this function inside the Controller file (suppose y.java). My question is on how to call this method in Spring Boot?
Expected:
#GetMapping(path = "/demo")
Response getResponseResult(Long id,Long digit) throws Exception
{
//Return the private method
}
When it comes to public functions I can create an object of X and do x.getResponse(id,digit), but I am not sure on how to approach this when the access modifier function in x.java is private.

Patch in SpringBoot [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I must create in SpringBoot this request at PATCH:
{
link: string
}
I try create my function like this:
#PatchMapping
public void updateMovie(#RequestBody String link)
but my request is invalid and in swagger looks like this:
"string"
You should create DTO (Data Transfer Object) with field String link in it. Then use it as request body.
Something like this:
public class LinkDto {
private String link;
}
And then your controller endpoint:
#PatchMapping
public void updateMovie(#RequestBody LinkDto link)

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()));
}
}

How to send request parameters to business logic [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 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.

Categories

Resources