<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Groovy &#8211; My Shitty Code</title>
	<atom:link href="https://myshittycode.com/tag/groovy/feed/" rel="self" type="application/rss+xml" />
	<link>https://myshittycode.com</link>
	<description>Embracing the Messiness in Search of Epic Solutions</description>
	<lastBuildDate>Fri, 06 Jan 2023 16:25:59 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.1</generator>

<image>
	<url>https://myshittycode.com/wp-content/uploads/2022/04/cropped-icon-32x32.png</url>
	<title>Groovy &#8211; My Shitty Code</title>
	<link>https://myshittycode.com</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">205304208</site>	<item>
		<title>Groovy: Handling Byte Order Marks When Reading a File</title>
		<link>https://myshittycode.com/2018/08/28/groovy-java-handling-byte-order-marks-when-reading-a-file/</link>
					<comments>https://myshittycode.com/2018/08/28/groovy-java-handling-byte-order-marks-when-reading-a-file/#respond</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Wed, 29 Aug 2018 02:11:37 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=1087</guid>

					<description><![CDATA[<p>PROBLEM Given a file with the following content:- When reading the file:- &#8230; the following values are printed:- Even though the value is trimmed, there is still a leading space in front of text. A further inspection reveals the leading space is not a regular space:- SOLUTION Some editors prepend a special Unicode character called [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2018/08/28/groovy-java-handling-byte-order-marks-when-reading-a-file/">Groovy: Handling Byte Order Marks When Reading a File</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">PROBLEM</h2>



<p>Given a file with the following content:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
10,20
</pre></div>


<p>When reading the file:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; title: ; notranslate">
def inputStream = new FileInputStream(&#039;test.csv&#039;)
def value = inputStream.text.trim()

println &quot;|${value}|&quot;
</pre></div>


<p>&#8230; the following values are printed:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
| 10,20|
</pre></div>


<p>Even though the value is trimmed, there is still a leading space in front of text.</p>



<p>A further inspection reveals the leading space is not a regular space:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; title: ; notranslate">
// first character is not a space
assert value.charAt(0) != (char) &#039; &#039;

// ASCII value: 65279 vs 32
assert (int) value.charAt(0) != (int) ((char) &#039; &#039;).charValue()
</pre></div>


<h2 class="wp-block-heading">SOLUTION</h2>



<p>Some editors prepend a special Unicode character called a byte order mark (BOM) to the file.</p>



<p>The simplest way to remove this special character is to leverage Apache Commons IO&#8217;s <strong>BOMInputStream</strong>:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; highlight: [1]; title: ; notranslate">
def inputStream = new BOMInputStream(new FileInputStream(&#039;test.csv&#039;))
def value = inputStream.text.trim()

println &quot;|${value}|&quot;
</pre></div>


<p>&#8230; and now, the values are printed correctly:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
|10,20|
</pre></div><p>The post <a rel="nofollow" href="https://myshittycode.com/2018/08/28/groovy-java-handling-byte-order-marks-when-reading-a-file/">Groovy: Handling Byte Order Marks When Reading a File</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2018/08/28/groovy-java-handling-byte-order-marks-when-reading-a-file/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1087</post-id>	</item>
		<item>
		<title>Spring Security: Propagating Security Context to Spawned Threads</title>
		<link>https://myshittycode.com/2018/03/09/spring-security-propagating-security-context-to-spawned-threads/</link>
					<comments>https://myshittycode.com/2018/03/09/spring-security-propagating-security-context-to-spawned-threads/#respond</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Sat, 10 Mar 2018 03:09:49 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Spring Security]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=1068</guid>

					<description><![CDATA[<p>PROBLEM Let&#8217;s assume we have the following Parent class&#8230; &#8230; and Child class&#8230; Let&#8217;s also assume the user has successfully logged in and Spring Security has set up the user authentication info. The Parent will spawn a new thread (through @Async) to run Child. When invoking the Parent, this is what we see:- The Child, [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2018/03/09/spring-security-propagating-security-context-to-spawned-threads/">Spring Security: Propagating Security Context to Spawned Threads</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">PROBLEM</h2>



<p>Let&#8217;s assume we have the following <b>Parent</b> class&#8230;</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; title: ; notranslate">
@Service
class Parent {
    @Autowired
    Child child

    void run() {
        println &quot;Parent: ${SecurityContextHolder.context.authentication?.principal}&quot;

        child.run()

        println &quot;Parent: Done&quot;
    }
}
</pre></div>


<p>&#8230; and <b>Child</b> class&#8230;</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; title: ; notranslate">
@Service
class Child {
    @Async
    void run() {
        Thread.sleep(500)
        println &quot;Child: ${SecurityContextHolder.context.authentication?.principal}&quot;
    }
}
</pre></div>


<p>Let&#8217;s also assume the user has successfully logged in and Spring Security has set up the user authentication info.</p>



<p>The <b>Parent</b> will spawn a new thread (through <b>@Async</b>) to run <b>Child</b>.</p>



<p>When invoking the <b>Parent</b>, this is what we see:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
Parent: USER_PRINCIPAL
Parent: Done
Child: null
</pre></div>


<p>The <b>Child</b>, for some reason, doesn&#8217;t get the receive the user authentication info.</p>



<h2 class="wp-block-heading">SOLUTION</h2>



<p>By default, <b>SecurityContextHolder</b> uses <b>MODE_THREADLOCAL</b> to store the user authentication info. As a result, this info is not accessible to methods outside the current execution thread.</p>



<p>To fix this, configure <b>SecurityContextHolder</b> to use <b>MODE_INHERITABLETHREADLOCAL</b> to pass the user authentication info to other spawned threads.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; highlight: [5]; title: ; notranslate">
@Configuration
@EnableAsync
class AppConfig {
    AppConfig() {
        SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL)
    }
}
</pre></div>


<p>When invoking the <b>Parent</b> again, now the <b>Child</b> will also receive the user authentication object:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
Parent: USER_PRINCIPAL
Parent: Done
Child: USER_PRINCIPAL
</pre></div>


<p></p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2018/03/09/spring-security-propagating-security-context-to-spawned-threads/">Spring Security: Propagating Security Context to Spawned Threads</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2018/03/09/spring-security-propagating-security-context-to-spawned-threads/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1068</post-id>	</item>
		<item>
		<title>JEE Security: Preventing Clickjacking Attacks</title>
		<link>https://myshittycode.com/2017/08/31/jee-security-preventing-clickjacking-attacks/</link>
					<comments>https://myshittycode.com/2017/08/31/jee-security-preventing-clickjacking-attacks/#respond</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Thu, 31 Aug 2017 15:03:05 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Spring Boot]]></category>
		<category><![CDATA[Spring Security]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=1066</guid>

					<description><![CDATA[<p>PROBLEM Clickjacking is an attack that tricks the users to perform unintended actions&#8230; see OWASP&#8217;s Testing for Clickjacking (OTG-CLIENT-009) SOLUTION To prevent clickjacking attacks, the app must set X-FRAME-OPTIONS header with an appropriate value:- If set correctly, the HTTPS response should show X-FRAME-OPTIONS header:- There are several ways to set this header. Solution 1: Using [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2017/08/31/jee-security-preventing-clickjacking-attacks/">JEE Security: Preventing Clickjacking Attacks</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">PROBLEM</h2>



<p>Clickjacking is an attack that tricks the users to perform unintended actions&#8230; see <a href="https://www.owasp.org/index.php/Testing_for_Clickjacking_(OTG-CLIENT-009)" target="_blank" rel="noopener">OWASP&#8217;s Testing for Clickjacking (OTG-CLIENT-009)</a></p>



<h2 class="wp-block-heading">SOLUTION</h2>



<p>To prevent clickjacking attacks, the app must set X-FRAME-OPTIONS header with an appropriate value:-</p>



<ul class="wp-block-list">
<li><b>DENY</b>: this denies any domain using the page as an iFrame source. This is the best option.</li>



<li><b>SAMEORIGIN</b>: this allows pages within the same domain to use other application pages as iFrame sources.</li>



<li><b>ALLOW-FROM [whitelisted domains]</b>: this declares a list of domains that are allowed to include the pages as iFrame sources.</li>
</ul>



<p>If set correctly, the HTTPS response should show X-FRAME-OPTIONS header:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; highlight: [9]; title: ; notranslate">
➜  ~ curl -i -k https://localhost:8443/
HTTP/1.1 200
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
X-Frame-Options: DENY
X-Application-Context: application:local:8443
Set-Cookie: JSESSIONID=04ADDAF886A20AA561021E869E980BCC; Path=/; Secure; HttpOnly
Content-Type: text/html;charset=UTF-8
Content-Language: en-US
Content-Length: 631
Date: Thu, 31 Aug 2017 14:56:57 GMT
</pre></div>


<p>There are several ways to set this header.</p>



<h3 class="wp-block-heading">Solution 1: Using a servlet filter</h3>



<p>You may create a servlet filter that sets X-FRAME-OPTIONS in the response header.</p>



<p>Here&#8217;s an example using web.xml-less Spring Boot:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; highlight: [12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35]; title: ; notranslate">
@SpringBootApplication
class Application extends SpringBootServletInitializer {
    static void main(String&#x5B;] args) {
        SpringApplication.run(Application, args)
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Application)
    }

    @Bean
    FilterRegistrationBean clickjackingPreventionFilter() {
        return new FilterRegistrationBean(
                urlPatterns: &#x5B;&#039;/**&#039;],
                filter: new Filter() {
                    @Override
                    void init(final FilterConfig filterConfig) throws ServletException {
                    }

                    @Override
                    void doFilter(final ServletRequest servletRequest,
                                  final ServletResponse servletResponse,
                                  final FilterChain filterChain) throws IOException, ServletException {
                        final HttpServletResponse response = (HttpServletResponse) servletResponse
                        response.addHeader(&#039;X-FRAME-OPTIONS&#039;, &#039;DENY&#039;)
                        filterChain.doFilter(servletRequest, servletResponse)
                    }

                    @Override
                    void destroy() {
                    }
                }
        )
    }
}
</pre></div>


<h3 class="wp-block-heading">Solution 2: Using Spring Security</h3>



<p>Spring Security provides a very easy way to set the X-FRAME-OPTIONS header:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; highlight: [7]; title: ; notranslate">
@Configuration
@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.
                headers().frameOptions().deny().
                and().
                authorizeRequests().
                antMatchers(&#039;/**&#039;).permitAll()
    }
}
</pre></div><p>The post <a rel="nofollow" href="https://myshittycode.com/2017/08/31/jee-security-preventing-clickjacking-attacks/">JEE Security: Preventing Clickjacking Attacks</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2017/08/31/jee-security-preventing-clickjacking-attacks/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1066</post-id>	</item>
		<item>
		<title>JEE Security: Disabling HTTP OPTIONS method</title>
		<link>https://myshittycode.com/2017/08/31/jee-security-disabling-http-options-method/</link>
					<comments>https://myshittycode.com/2017/08/31/jee-security-disabling-http-options-method/#comments</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Thu, 31 Aug 2017 14:37:04 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Spring Boot]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=1062</guid>

					<description><![CDATA[<p>PROBLEM HTTP OPTIONS method is used to provide a list of methods that are supported by the web server. For example, the following shows both GET and HEAD are allowed on the given link:- Enabling OPTIONS may increase the risk of cross-site tracing (XST)&#8230; see OWASP&#8217;s Test HTTP Methods (OTG-CONFIG-006). SOLUTION There are several ways [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2017/08/31/jee-security-disabling-http-options-method/">JEE Security: Disabling HTTP OPTIONS method</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">PROBLEM</h2>



<p>HTTP OPTIONS method is used to provide a list of methods that are supported by the web server.</p>



<p>For example, the following shows both GET and HEAD are allowed on the given link:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; highlight: [11]; title: ; notranslate">
➜  ~ curl -i -k -X OPTIONS https://localhost:8443/
HTTP/1.1 200
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
X-Frame-Options: DENY
X-Application-Context: application:local:8443
Allow: GET,HEAD
Content-Length: 0
Date: Thu, 31 Aug 2017 14:07:21 GMT
</pre></div>


<p>Enabling OPTIONS may increase the risk of cross-site tracing (XST)&#8230; see <a href="https://www.owasp.org/index.php/Testing_for_HTTP_Methods_and_XST_(OWASP-CM-008)" target="_blank" rel="noopener">OWASP&#8217;s Test HTTP Methods (OTG-CONFIG-006)</a>.</p>



<h2 class="wp-block-heading">SOLUTION</h2>



<p>There are several ways to disable OPTIONS method.</p>



<h3 class="wp-block-heading">Solution 1: Using web.xml</h3>



<p>If your app has <b>web.xml</b>, you may add the following snippet:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; highlight: [5,6,7,8,9,10,11,12,13]; title: ; notranslate">
&lt;!--?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?--&gt;
&lt;web-app xmlns=&quot;http://xmlns.jcp.org/xml/ns/javaee&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemalocation=&quot;http://xmlns.jcp.org/xml/ns/javaee
		 http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd&quot; metadata-complete=&quot;true&quot; version=&quot;3.1&quot;&gt;

    &lt;security-constraint&gt;
        &lt;web-resource-collection&gt;
            &lt;web-resource-name&gt;restricted methods&lt;/web-resource-name&gt;
            &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
            &lt;http-method&gt;OPTIONS&lt;/http-method&gt;
        &lt;/web-resource-collection&gt;
        &lt;auth-constraint&gt;
        &lt;/auth-constraint&gt;
    &lt;/security-constraint&gt;

    &lt;!-- Other configurations --&gt;
&lt;/web-app&gt;
</pre></div>


<h3 class="wp-block-heading">Solution 2: Using Spring Boot</h3>



<p>If you are using Spring Boot, there isn&#8217;t any option to mimic the above configuration programmatically.</p>



<p>However, you still can use <b>web.xml</b> in conjunction with Spring Boot by setting <b>metadata-complete</b> to <b>false</b> and use servlet version 3.0 or higher:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; highlight: [3]; title: ; notranslate">
&lt;!--?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?--&gt;
&lt;web-app xmlns=&quot;http://xmlns.jcp.org/xml/ns/javaee&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemalocation=&quot;http://xmlns.jcp.org/xml/ns/javaee
		 http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd&quot; metadata-complete=&quot;false&quot; version=&quot;3.1&quot;&gt;

    &lt;security-constraint&gt;
        &lt;web-resource-collection&gt;
            &lt;web-resource-name&gt;restricted methods&lt;/web-resource-name&gt;
            &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
            &lt;http-method&gt;OPTIONS&lt;/http-method&gt;
        &lt;/web-resource-collection&gt;
        &lt;auth-constraint&gt;
    &lt;/auth-constraint&gt;&lt;/security-constraint&gt;
&lt;/web-app&gt;
</pre></div>


<h3 class="wp-block-heading">Solution 3: Using Spring Security</h3>



<p>If you don&#8217;t want to use <b>web.xml</b>, you may configure Spring Security to disable OPTIONS method on all URIs:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; highlight: [7]; title: ; notranslate">
@Configuration
@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.authorizeRequests().
                antMatchers(HttpMethod.OPTIONS, &#039;/**&#039;).denyAll().
                antMatchers(&#039;/**&#039;).permitAll()
    }
}
</pre></div>


<p>Now, when trying to hit the same link with OPTIONS method, the app will return 403 Forbidden:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; highlight: [2]; title: ; notranslate">
➜  ~ curl -i -k -X OPTIONS https://localhost:8443/
HTTP/1.1 403
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
X-Frame-Options: DENY
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Thu, 31 Aug 2017 14:26:51 GMT
</pre></div><p>The post <a rel="nofollow" href="https://myshittycode.com/2017/08/31/jee-security-disabling-http-options-method/">JEE Security: Disabling HTTP OPTIONS method</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2017/08/31/jee-security-disabling-http-options-method/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1062</post-id>	</item>
		<item>
		<title>Groovy: Copying Properties Between Two Beans</title>
		<link>https://myshittycode.com/2017/06/23/groovy-copying-properties-between-two-beans/</link>
					<comments>https://myshittycode.com/2017/06/23/groovy-copying-properties-between-two-beans/#comments</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Fri, 23 Jun 2017 14:04:28 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[Groovy]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=1053</guid>

					<description><![CDATA[<p>PROBLEM Given two beans&#8230; There are several ways to copy properties from one bean to another:- SOLUTION Groovy provides a helper class to solve this problem called InvokerHelper. The advantage of using this is there&#8217;s no need to import yet another dependency and it still allows us to keep our code concise. Scenario 1: Both [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2017/06/23/groovy-copying-properties-between-two-beans/">Groovy: Copying Properties Between Two Beans</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">PROBLEM</h2>



<p>Given two beans&#8230;</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; title: ; notranslate">
class A {
    String name
    LocalDateTime localDateTime
}

class B {
    String name
    LocalDateTime localDateTime
}
</pre></div>


<p>There are several ways to copy properties from one bean to another:-</p>



<ul class="wp-block-list">
<li>The most rudimentary way is to &#8220;get&#8221; each property from one bean and &#8220;set&#8221; it on another bean, which is VERY verbose and stupid.</li>



<li>Another way is to leverage utilities such as <b>BeanUtils</b> provided by either Apache Commons or Spring. While both libraries are called <b>BeanUtils</b>, they behave slightly different from one another.</li>



<li>Write home-grown reflection function&#8230; and now you have two problems: 1) it may not handle edge cases properly and 2) no one understands your implementation.</li>
</ul>



<h2 class="wp-block-heading">SOLUTION</h2>



<p>Groovy provides a helper class to solve this problem called <b>InvokerHelper</b>. The advantage of using this is there&#8217;s no need to import yet another dependency and it still allows us to keep our code concise.</p>



<h3 class="wp-block-heading">Scenario 1: Both beans have exact properties</h3>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; title: ; notranslate">
class MySpec extends Specification {
    class A {
        String name
        LocalDateTime localDateTime
    }

    class B {
        String name
        LocalDateTime localDateTime
    }

    def &quot;given a and b with same exact properties, should copy all properties&quot;() {
        given:
        def a = new A(name: &#039;name&#039;,
                      localDateTime: LocalDateTime.now())
        def b = new B()

        when:
        InvokerHelper.setProperties(b, a.properties)

        then:
        b.name == a.name
        b.localDateTime == a.localDateTime
    }
}
</pre></div>


<h3 class="wp-block-heading">Scenario 2: Source bean has additional properties</h3>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; title: ; notranslate">
class MySpec extends Specification {
    class A {
        String name
        LocalDateTime localDateTime
        Integer extra1
        Boolean extra2
    }

    class B {
        String name
        LocalDateTime localDateTime
    }

    def &quot;given a has additional properties than b, should ignore additional properties&quot;() {
        given:
        def a = new A(name: &#039;name&#039;,
                      localDateTime: LocalDateTime.now(),
                      extra1: 1,
                      extra2: true)
        def b = new B()

        when:
        InvokerHelper.setProperties(b, a.properties)

        then:
        b.name == a.name
        b.localDateTime == a.localDateTime
    }
}
</pre></div>


<h3 class="wp-block-heading">Scenario 3: Destination bean has additional properties</h3>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; title: ; notranslate">
class MySpec extends Specification {
    class A {
        String name
        LocalDateTime localDateTime
    }

    class B {
        String name
        LocalDateTime localDateTime
        Integer extra1
        Boolean extra2
    }

    def &quot;given b has additional properties than a, should set additional properties as null&quot;() {
        given:
        def a = new A(name: &#039;name&#039;,
                      localDateTime: LocalDateTime.now())
        def b = new B()

        when:
        InvokerHelper.setProperties(b, a.properties)

        then:
        b.name == a.name
        b.localDateTime == a.localDateTime
        b.extra1 == null
        b.extra2 == null
    }
}
</pre></div>


<h3 class="wp-block-heading">Scenario 4: Same property but different data type from each bean</h3>



<p>The short answer is don&#8217;t do it. It&#8217;s not worth the hassle and confusion.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; title: ; notranslate">
class MySpec extends Specification {
    class A {
        String number
    }

    class B {
        Integer number
    }

    def &quot;given same property name but different data type, should go bat shit crazy&quot;() {
        given:
        def a = new A(number: &#039;0&#039;)
        def b = new B()

        when:
        InvokerHelper.setProperties(b, a.properties)

        then:
        b.number == 48 // ASCII value for character &#039;0&#039;
    }

    def &quot;given same property name but different data type, should go bat shit crazy again&quot;() {
        given:
        def a = new A(number: &#039;10&#039;)
        def b = new B()

        when:
        InvokerHelper.setProperties(b, a.properties)

        then:
        thrown ClassCastException // because there&#039;s no ASCII value for character &#039;10&#039;
    }
}
</pre></div><p>The post <a rel="nofollow" href="https://myshittycode.com/2017/06/23/groovy-copying-properties-between-two-beans/">Groovy: Copying Properties Between Two Beans</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2017/06/23/groovy-copying-properties-between-two-beans/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1053</post-id>	</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Lazy Loading (feed)
Database Caching using Disk

Served from: myshittycode.com @ 2026-02-19 21:37:06 by W3 Total Cache
-->