2022-07-27

Upgrade Spring Boot from 1.5.20.RELEASE to 2.7.2


as of: 20220727_pm070452, Still editing...

Stacks

From Spring Boot + Keycloak
To: Spring Boot + Keycloak + Spring Security 


Version

from: 1.5.20.RELEASE
to: 2.7.2


Changes

  1. pom.xml
  2. CSRF - default implementation of Spring Security
    1. JSP
  3. Controllers
  4. Services
    1. Repo
      1. Batch Save
      2. Batch Delete
      3. Delete
      4. FindOne
      5. Pageable
  5. application.properties









pom.xml

Added


<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>


<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-starter</artifactId>
<version>18.0.2</version>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-security-adapter</artifactId>
<version>18.0.2</version>
</dependency>


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>







<dependency>
<groupId>org.keycloak.bom</groupId>
<artifactId>keycloak-adapter-bom</artifactId>
<version>${version.keycloak-adapter-bom}</version>
<type>pom</type>
</dependency>















Modified

from:
  <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.20.RELEASE</version>
</parent>

to:
  <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.2</version>
</parent>

from:

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Edgware.SR5</spring-cloud.version>
</properties>

to:

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<start-class>com.tiongnam.sfa.cdr.MainClass</start-class>
<spring-cloud.version>2021.0.3</spring-cloud.version>
<version.keycloak-adapter-bom>18.0.2</version.keycloak-adapter-bom>
</properties>





from:

<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-adapter</artifactId>
<version>4.5.0.Final</version>
</dependency>


to:

<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-adapter</artifactId>
<version>18.0.2</version>
</dependency>


















CSRF - default implementation of Spring Security




Added header into ajax post request

, headers: {"${_csrf.headerName}": '${_csrf.token}'}

Added spring security tag within POST form:

<sec:csrfInput />


or


turn off csrf checking


protected void configure(HttpSecurity http) throws Exception {

org.springframework.security.config.annotation.web.builders.HttpSecurity http.csrf().disable();

...
...

































Controllers:


Changed

From:
org.keycloak.KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal

To:
java.security.Principal principal











Services

Batch Save

Changed

From:
repo.save(batchList)

To:
repo.saveAll(batchList);



findOne

From:
repo.findOne(new Long("1"));


To:
repo.getReferenceById(new Long("1"));



Delete


From:
delete(entity.getId());

To:
deleteById(entity.getId());







Pageable


From:
Pageable page_req = new PageRequest(index,reqData.getLength(), orderBy(reqData), reqData.getOrder().getData());

To:
Pageable page_req = PageRequest.of(index, reqData.getLength(), orderBy(reqData), reqData.getOrder().getData());










application.properties


Added

server.tomcat.max-http-form-post-size
server.tomcat.max-swallow-size

Changed


server.contextPath

to

server.servlet.context-path






spring.http.multipart.max-file-size

to

spring.servlet.multipart.max-file-size



spring.http.multipart.max-request-size

to

spring.servlet.multipart.max-request-size









keycloak.securityConstraints[0].authRoles[0]=read-only-common
keycloak.securityConstraints[0].securityCollections[0].patterns[0]=/welcome
keycloak.securityConstraints[0].securityCollections[0].patterns[1]=/logout
keycloak.securityConstraints[0].securityCollections[0].patterns[2]=/dashboard
keycloak.securityConstraints[0].securityCollections[0].patterns[3]=/web/getDashboard



to



@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests()
.antMatchers("/vendor/**", "/css/**", "/js/**", "/img/**").permitAll()
.antMatchers("/upload").authenticated()
.antMatchers("/formd/**", "/module1/**", "/maintenance/**").authenticated()
.anyRequest().authenticated()
;
}













2022-07-21

ajax, upload file, json string, Spring Controller, DTO

 



Googled: json to dto spring boot controller




Resolved by follow the example on: 

Spring Boot controller - Upload Multipart and JSON to DTO




thread solution at: https://stackoverflow.com/a/49993072


Ajax Javascript
formData.append( 'dtoName', new Blob([JSON.stringify(dtoJavascriptObject)], {
type: "application/json"
}));

Spring Controller parameter

@RequestPart ManualGenerateCsv dtoName






couldn't parse json attribute to java object attribute.

 







private boolean isRequiredFtpToSSS;

public void setRequiredFtpToSSS(boolean isRequiredFtpToSSS) {
this.isRequiredFtpToSSS = isRequiredFtpToSSS;
}

Since your attribute name: isRequiredFtpToSSS
Due to jackson is expecting: setIsRequiredFtpToSSS
But there has no "is for the auto generated setter: setRequiredFtpToSSS





So u have to add this.

@JsonProperty("isRequiredFtpToSSS")
private boolean isRequiredFtpToSSS;


















Jackson JSON parsing from string to date.

 









@JsonFormat(pattern = "yyyy-MMM-dd")
private Date dateFrom;





not sure if were causing by:
MethodArgumentConversionNotSupportedException when I try to map json string onto java domain class in Spring controller's method






jquery 3.3.1 change checkbox checked

 







Found: 
Make checkbox value checked with jQuery or JavaScript
but seems not the same case.



the one i'm using.

$("#chkHasDateTo").prop('checked', dto.hasDateTo);



But i remember there are more elegant way to do the same thing....

Jquery Datepicker: click on a checkbox, then open/pop datepicker of a textbox.

 


click on a checkbox, then open/pop datepicker of a textbox.



if($("#chkHasDateTo").is(":checked")){
$( "#dateTo" ).trigger( "select" );
$( "#dateTo" ).trigger( "focus" );
}

















2022-07-13

全 #Lesley [Legend V] #MVP 7.7/6 4 6 | $13383 202206142025

 




全 #Lesley [Legend V] #MVP 7.7/6 4 6 | $13383 202206142025 https://youtu.be/tnp0nELuY8Q via @YouTube #MLBB 



Java does new instance consume many memory

 







Found: https://stackoverflow.com/a/258150

Measurement methods

You can use Instrumentation.getObjectSize() to obtain an estimate of the storage consumed by an object.








eclipse maven "JUnit" "javaagent"

refer to: https://www.blogger.com/blog/post/edit/10648886/7778852398276118981





















eclipse maven "JUnit" "javaagent"

 


eclipse maven "JUnit" "javaagent"








Found this:

https://stackoverflow.com/a/35775792

You can use ea-agent-loader

With it loading an agent in runtime will look like:

public class HelloAgentWorld
{
    public static class HelloAgent
    {
        public static void agentmain(String agentArgs, Instrumentation inst)
        {
            System.out.println(agentArgs);
            System.out.println("Hi from the agent!");
            System.out.println("I've got instrumentation!: " + inst);
        }
    }

    public static void main(String[] args)
    {
        AgentLoader.loadAgentClass(HelloAgent.class.getName(), "Hello!");
    }
}

全 #Rafaela [Epic I] #MVP 9.6/4 3 21 | $8313 202205281332 https://youtu.be/jUNpF3a8HPI via @YouTube #MLBB

 


全 #Rafaela [Epic I] #MVP 9.6/4 3 21 | $8313 202205281332 https://youtu.be/jUNpF3a8HPI via @YouTube #MLBB 




2022-07-12

eclipse added hotkey for svn actions are not working.


It may be due to this breaking change in Eclipse 3.6:

http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.platform.doc.isv/porting/3.6/incompatibilities.html?view=co#objectContribution

EDIT:

Looks like it definitely is. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=309074. Here's the fix:

In the "Customize Perspective" dialog, go to the "Command Groups Availability" tab and check "Team" and "SVN".

In Eclipse Mars.2 (4.5.2) this is under Window->Perspective->Customize Perspective... dialog, "Action Set Availability" tab. (Try to restart Eclipse if it doesn't work after you change it). Customize Perspective dialog screenshot







Right click on current perspective:




Click on Customize...

Click on "Action Set Availability"



From Available action sets column:



Tick / Check the SVN checkbox, then Apply and Close.

Tested without restart eclipse, the hot key is working now.

























2022-07-06

Resolved - @PreUpdate not working in JUnit test.

 



javax.persistence.PreUpdate





object need to be "dirty" to trigger...


obj.setColumn01("text");
repo.save(obj);


then make obj "dirty" before save to trigger @PreUpdate


obj.setColumn01("new text);
repo.save(obj);




Solution

As you said, the callback method is called the second time, if the entity is detached or fetched again from DB.

I cannot explain it exactly, but can think of the scenario described here, when no dirty fields are identified before the second save() call and thus the @PreUpdate callback not called. Or it may be simply a bug within your version of EclipseLink.

2022-07-01

Setup local Keycloak for development

 




https://stackoverflow.com/a/72600716






Keycloak 18.0.2 doesn't required "/auth" as endpoint


new config:

keycloak.auth-server-url=http://localhost:8080

would be enough




We are sorry... page not found... error


Mandatory Config in Keycloak



while hitting we are sorry page not found error

was using http://localhost:8080/auth for keycloak.auth-server



while testing with https://www.keycloak.org/app/

hit error if didn't fill: https://www.keycloak.org/app/
to:

Root URL: https://www.keycloak.org/app/




If config below never in place, will trigger error: Invalid parameter: redirect_uri


Valid Redirect URIs: *








Respective Keycloak role in Spring Boot authRole config

 





keycloak.securityConstraints[0].authRoles[0]=xyz





Respective config in Keycloak (18.0.2)

In user Role mappings:





Different of SVNs

 SVN




Getting(install) SVN feature from
Eclipse Marketplace... VS  Install New Software






Eclipse Marketplace...





Install New Software

http://subclipse.tigris.org/update_1.6.x







subclipse.tigris.org no longer available...

 

http://subclipse.tigris.org/update_1.10.x
http://subclipse.tigris.org/update_1.6.x

above are not reachable...








Found a post telling to get from Eclipse Marketplace

Help > Eclipse Marketplace...





But during installation, but still retrieve resource from:












2022-06-10

"Spring" JPA "native query" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1

 


"Spring" JPA "native query" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1



Exception Snippet:

java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(ArrayList.java:659)
at java.util.ArrayList.get(ArrayList.java:435)
at org.springframework.data.repository.query.ResultProcessor$ProjectingConverter.toMap(ResultProcessor.java:278)
at org.springframework.data.repository.query.ResultProcessor$ProjectingConverter.getProjectionTarget(ResultProcessor.java:266)
at org.springframework.data.repository.query.ResultProcessor$ProjectingConverter.convert(ResultProcessor.java:253)
at org.springframework.data.repository.query.ResultProcessor$ChainingConverter$1.convert(ResultProcessor.java:201)
at org.springframework.data.repository.query.ResultProcessor$ChainingConverter.convert(ResultProcessor.java:212)
...

Throw error with:

List<Map<String, Object>> getNativeQueryList();

or

List<Tuple> getNativeQueryList();

Work around with:

List<Object[]> getNativeQueryList();






JUnit test - Caused by: javax.persistence.RollbackException: Transaction marked as rollbackOnly

 

Exception snippet:

12:02:34.849|WARN |Caught exception while allowing TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener@1a84f40f] to process 'after' execution for test: method [public void test.com.tiongnam.repositories.TestInvoicePackageRepo.testListPossiblePackageWithInvoiceIdAndSummary()], instance [test.com.tiongnam.repositories.TestInvoicePackageRepo@ca2cd5e], exception [java.lang.IndexOutOfBoundsException: Index: 1, Size: 1]|main|org.springframework.test.context.TestContextManager
org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:526)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730)
at org.springframework.test.context.transaction.TransactionContext.endTransaction(TransactionContext.java:128)
at org.springframework.test.context.transaction.TransactionalTestExecutionListener.afterTestMethod(TransactionalTestExecutionListener.java:227)
at org.springframework.test.context.TestContextManager.afterTestMethod(TestContextManager.java:319)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:94)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
...
Caused by: javax.persistence.RollbackException: Transaction marked as rollbackOnly
at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:58)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517)
... 26 common frames omitted





@Rollback(false)
MyJUnitTestClass


Calling a @Transactional Repo



change
@Rollback(true)






2022-05-31

Alternative - Error Code: 1093. You can't specify target table 'YOUR_TABLE' for update in FROM clause

 




Error Code: 1093. You can't specify target table 'YOUR_TABLE' for update in FROM clause



UPDATE YOUR_TABLE SET columnA = 'def' WHERE id IN (SELECT id AS MMID FROM YOUR_TABLE WHERE columnA = 'abc');



UPDATE YOUR_TABLE SET columnA = 'def' WHERE id IN ( SELECT MMID FROM ( SELECT id AS MMID FROM YOUR_TABLE WHERE columnA = 'abc' ) AS YOUR_ALIAS );



2022-04-20

JasperReport, always get blank PDF?

 
line below with new JREmptyDataSource() will get pdf as per expected.

jasperPrint = JasperFillManager.fillReport(report, jrParam, new JREmptyDataSource());



vs

where as using static _DATA_SOURCE_EMPTY, will always get blank pdf.

private static JREmptyDataSource _DATA_SOURCE_EMPTY = new JREmptyDataSource();

...
jasperPrint = JasperFillManager.fillReport(report, jrParam, _DATA_SOURCE_EMPTY);
...










Google Referrals