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

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.

Related

Best way to handle MultipartFile on Spring Boot? [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 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.

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!

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.

We know we cant create object of interface but then how do we create object of Statement or PrepareStatement in jdbc? [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 8 years ago.
Improve this question
Connection con = DriverManager.getConnection(url+db,username,password);
Statement st = con.createStatement();
The object created is of a class implementing that interface. The actual class depends on the driver.
Both getConnection() and createStatement() are factory methods. You can write code that uses the interfaces, but the actual classes are what implements the functionality for that particular database.
A (not true) implementation of DriverManager.getConnection() would be as follows:
public Connection getConnection(String url, String username, String password) {
if(url.startsWith("jdbc:mysql:") // We have MySQL
return new MySQLConnection();
else if(url.startsWith("SomethingElse")
return new OtherConnection();
}
In reality, the actual class is loaded dynamically, so it doesn't need to be in the compile time classpath. The proper class is loaded (or an error is thrown if a suitable one isn't found) and returned. From therefore on, the MySQLConnection class will return a MySQLStatement and so forth.
You could write code this way:
MySQLConnection con = (MySQLConnection)DriverManager.getConnection(url, user, pass);
But that would make your code database specific. In some cases this is warranted, if the MySQLConnection class allowed for some functionality that isn't in the Connection interface, but in most cases you just want to deal with the java.sql.Connection interface and not care about which database is actually being used.

Categories

Resources