Sunday, April 12, 2020

Hibernate Date, TimeStamp and Time

In this post I'll demonstrate different between Hibernate Date, Time and TimeStamp with Microsoft SQL Server database. For this demonstration I will use code base of "Spring Boot REST API with SQLServer 2019" post. Git code base for the initialization of the project can find in GIT CODE base.

Prerequisites 
  1. You should have install java 1.8 or above.
  2. You should have Eclipse installed in your PC.
  3. Your PC should setup Maven installed and configured.
  4. MS SQL server need to be installed. 


Modify Model class 

For this demonstration I will add three parameters to out model class "Book". Those three parameters will map to respective columns in "BOOKS" table which store TIMESTAMP, DATE and TIME.

@Temporal(TemporalType.TIMESTAMP)
private Date timeStamp;
@Temporal(TemporalType.DATE)
private Date date;
@Temporal(TemporalType.TIME)
private Date time;

I have added above three parameters and relevant geter/setter methods.We can define the preferred mapping with the @Temporal annotation. As you can see in above code, it takes a TemporalType enum as a value. The enum allows you to select the SQL type (DATE, TIME or TIMESTAMP) which you want to use.

Modify Service class 

Then lets update the service method of setDateTime which set values for book objects time, date and time stamp. 

private void setDateTime(Book book){
   Date date= Calendar.getInstance().getTime();
   book.setTimeStamp(date);
   book.setDate(date);
   book.setTime(date);
}

Then call this setDateTime method from saving method of Book saveBookInJSON method. 





Run the application

In order to run first we have to perform maven install command and then we can run the application


Go to run debug configuration and add following command 

spring-boot:run




Then run the application  by click on Run button


After successful execution you should be able to see similar output as show below.




Lets Test the application 


Then lets add new Book in to API


curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d "{ \"isbmNumber\":\"9999\", \"name\":\"How to develop API\", \"description\":\"sample book\", \"auther\":\"Nirmal Balasooriya \" }" http://localhost:8080/saveOrUpdate

  
For this one following output will return


{"code":"1","desc":"Book save successful","t":"9999"}

If you check the database then you could see the saved data in the database as show in below.

Saved details in the Database.

As you can see in the database Date, Time and TimeStamp values can be see as show below.

time          :  17:45:28.6600000
date          2020-04-12
timestamp :  2020-04-12 17:45:28.6590000

You can be find updated code base in following GIT HUB location.

Monday, April 6, 2020

Upload Large Files in JBoss EAP - Resolve UT000020: Connection terminated as request was larger than 10485760

In this post I will demonstrate how to resolve "UT000020: Connection terminated as request was larger than 10485760". This error because of the file that we going to upload exceeds maximum size allowed in default configuration (10MB) on JBoss EAP. For demonstration purposes I will use JackRabbit post code.

For the testing purposes I have added new Image (LARGE.JPG) in to resource folder and if you try to execute following command in browser you will hit an error.

http://localhost:9090/uploadResource/large

2020-04-06 19:41:40.693 ERROR 21016 --- [nio-9090-exec-1] o.s.boot.web.support.ErrorPageFilter     : Forwarding to error page from request [/uploadResource/large] due to exception [org.apache.http.NoHttpResponseException: localhost:8080 failed to respond]

javax.jcr.RepositoryException: org.apache.http.NoHttpResponseException: localhost:8080 failed to respond
at org.apache.jackrabbit.spi2davex.RepositoryServiceImpl$BatchImpl.start(RepositoryServiceImpl.java:634) ~[jackrabbit-spi2dav-2.19.3.jar:2.19.3]
at org.apache.jackrabbit.spi2davex.RepositoryServiceImpl$BatchImpl.access$600(RepositoryServiceImpl.java:569) ~[jackrabbit-spi2dav-2.19.3.jar:2.19.3]


Exception in the Spring-Boot application


Also if you check in JBoss log you should be see following exception.

19:41:40,712 ERROR [org.apache.jackrabbit.server.util.HttpMultipartPost] (default task-15) Error while processing multipart.: org.apache.commons.fileupload.FileUploadBase$IOFileUploadException: Processing of multipart/form-data request failed. UT000020: Connection terminated as request was larger than 10485760
        at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:351)
        at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:115)
        at org.apache.jackrabbit.server.util.HttpMultipartPost.extractMultipart(HttpMultipartPost.java:76)
        at org.apache.jackrabbit.server.util.HttpMultipartPost.<init>(HttpMultipartPost.java:51)
        at org.apache.jackrabbit.server.util.RequestData.<init>(RequestData.java:36)
        at org.apache.jackrabbit.server.remoting.davex.JcrRemotingServlet.doPost(JcrRemotingServlet.java:416)
        at org.apache.jackrabbit.webdav.server.AbstractWebdavServlet.execute(AbstractWebdavServlet.java:372)
        at org.apache.jackrabbit.webdav.server.AbstractWebdavServlet.service(AbstractWebdavServlet.java:308)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
        at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
        at 


Exception in JBoss EAP

The main reason for this exception is we are trying to upload a file which size is larger than the default allowed size in JBoss.

Lets see how we can configure to allow JBoss to configure it for 100MB file.
First You have to log in to JBoss EAP admin console(http://127.0.0.1:9990/console/App.html#home) using username and password.

Then navigate to Configuration page and then click on "SubSystems" in left panel then click on "Web/HTTP - Undertow". Then Click on  view button on "HTTP". Please refer to below image.




Then you should able to view similar page to below figure. Then click on "HTTP SERVER" Tab and click on View button as show in below figure.



Then click on "HTTP Listener" in right side panel and then click on Edit button as show in below figure.



Then find the parameter name "Max post size" and set value as "104857600" (this is in byte value) which equal to 100 MB. Then Click save button and re-lode the server.

After that change if you try to upload large file by following URL it will get sucess.

http://localhost:9090/uploadResource/large

You could see following output on web browser.

{"code":"1","desc":"Resource Added Successfully","t":null}


also if you try to access that image using following URL you should be able to see uploaded image.




Code base for this can be found in following GITHUB location

Friday, April 3, 2020

Non-blocking I/O(NIO) File handling operations

In this post I will list down some of common file operations which encounter in day today basis when working. Following are required to run the provided project shared at end of the post.

Prerequisites 
  1. You should have install java 1.8 or above.
  2. You should have Eclipse installed in your PC.
  3. Your PC should setup Maven installed and configured.


Create Files

For this one also we can use Files.createFile method in java.nio.file.Files class. For this method we need to provide Path object of new file.  Note that this method will throw java.nio.file.FileAlreadyExistsException when file already existing. As you can see sample code in createFile() method.


String parentFolderPath="C:\\JAVA8_FILE_HANDLING\\src\\main\\resources\\PARENT_FOLDER\\";

File newFile= new File(parentFolderPath+"Test.txt");

if(!newFile.exists())
    Files.createFile(newFile.toPath());

System.out.println("Newly created file exists :: "+newFile.exists());



List everything in a folder
For listing of folder we can useFiles.list method in java.nio.file.Files class. For that method we can pass the folder path which we need to list down. Note that this list method will throw IOException so we have to handle it in our code. You can see sample code in listDownAllFilesAndFolder() method.

String parentFolderPath=
"C:\\JAVA8_FILE_HANDLING\\src\\main\\resources\\PARENT_FOLDER\\";

List fileList = Files.list(Paths.get(parentFolderPath)).collect(Collectors.toList());

fileList.forEach(System.out::println);



Search file in a folder
For this one also we can use Files.list method in java.nio.file.Files class with Filter functionality. As you can see sample code in SearchFilesInFolder() method.

String parentFolderPath=
"C:\\JAVA8_FILE_HANDLING\\src\\main\\resources\\PARENT_FOLDER\\";

String fileToSearch="srilanka";


List fileList = Files.list(Paths.get(parentFolderPath))
        .filter(path -> new File(path.toString()).getName().startsWith(fileToSearch))
        .collect(Collectors.toList());

fileList.forEach(System.out::println);



Read Property File Line by Line

For this one also we can use Files.lines method in java.nio.file.Files class and with help of Stream we can put all lines in to List as show in below example. As you can see sample code in readPropertyFileLineByLine() method.


String fileName = 
"C:\\JAVA8_FILE_HANDLING\\src\\main\\resources\\PARENT_FOLDER\\SampleProperty-2020-04-04.properties";


List<String> list = new ArrayList<>();
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
    
    list = stream
            .collect(Collectors.toList());} 
catch (IOException e) {
    e.printStackTrace();
}

list.forEach(System.out::println);



Moving Files and Folders

For this one also we can use Files.move method in java.nio.file.Files class and for this method we need to provide source path and destination path. For this method we can pass optional parameter which we can say to program whether we need to override existing files in destination folder. One most important thing in this method is it will remove all the items inside source folder and source folder it self as well. As you can see sample code in moveFilesAndFolders() method. 


String parentFolderPath="C:\\JAVA8_FILE_HANDLING\\src\\main\\resources\\PARENT_FOLDER\\";

String destFolderPath="C:\\JAVA8_FILE_HANDLING\\src\\main\\resources\\OUTPUT\\";

Files.move(Paths.get(parentFolderPath),Paths.get(destFolderPath)
, StandardCopyOption.REPLACE_EXISTING);

List fileList = Files.list(Paths.get(destFolderPath)).collect(Collectors.toList());

fileList.forEach(System.out::println);