<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by dsrini.os on Medium]]></title>
        <description><![CDATA[Stories by dsrini.os on Medium]]></description>
        <link>https://medium.com/@dsrini.os?source=rss-c94f3e6a9feb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*eXVEcu_UPPxe0z5dO-JAwQ.png</url>
            <title>Stories by dsrini.os on Medium</title>
            <link>https://medium.com/@dsrini.os?source=rss-c94f3e6a9feb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 03:14:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dsrini.os/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Unit tests with Mocha, chai, sinon, proxyquire (with babel) config]]></title>
            <link>https://medium.com/@dsrini.os/unit-tests-with-mocha-chai-sinon-proxyquire-with-babel-config-a169ab960d2a?source=rss-c94f3e6a9feb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a169ab960d2a</guid>
            <dc:creator><![CDATA[dsrini.os]]></dc:creator>
            <pubDate>Sat, 11 Mar 2023 00:04:20 GMT</pubDate>
            <atom:updated>2023-03-11T00:04:20.740Z</atom:updated>
            <content:encoded><![CDATA[<p>Unit tests are primary, and for mocha to run ES6 code, it requires the babel config which one can specify as below,</p><pre>{<br>  &quot;spec&quot;: &quot;test/**/*.test.js&quot;,<br>  &quot;recursive&quot;: true,<br>  &quot;reporter&quot;: &quot;spec&quot;,<br>  &quot;require&quot;: [&quot;<a href="http://twitter.com/babel/register">@babel/register</a>&quot;, &quot;test/common&quot;]<br>}</pre><p>The above config in .moharc.json does specify that mocha requires babel. Don’t forget to install babel/register (for babel 7 as follows)</p><pre><a href="http://twitter.com/babel/register">npm install --save-dev @babel/register</a> (or)<br>yarn add -D <a href="http://twitter.com/babel/register">@babel/register</a></pre><p>The above mocha config also specifies any common scripts to run before executing the tests, a sample is as below —</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a169ab960d2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JCache with EhCache provider in Spring boot 2]]></title>
            <link>https://medium.com/@dsrini.os/jcache-with-ehcache-provider-in-spring-boot-2-4598d968af2d?source=rss-c94f3e6a9feb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4598d968af2d</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[ehcache]]></category>
            <dc:creator><![CDATA[dsrini.os]]></dc:creator>
            <pubDate>Thu, 20 Feb 2020 23:02:38 GMT</pubDate>
            <atom:updated>2020-02-20T23:02:38.079Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7GzBQH-dRndhWGJBxoEDwA.png" /></figure><p>JCache eases cache maintenance and is an unified approach when compared with Spring Cache and so. There are lot of articles on Spring cache owing to its longevity, but JCache being a successor, not many articles discusses in detail. Also, with EHCache 3 Java config is recommended when compared with the previous xml config.</p><p>Simply annotate the class with defaults for cache</p><pre>@CacheDefaults(cacheName = &quot;user&quot;)<br>public class UserService {</pre><p>To cache an object, simply annotate with CacheResult. If you have a key, please provide as below</p><pre>@CacheResult<br>public User getUserById(<br> @CacheKey final long userId,<br> final String particulars) throws ResourceNotFoundException {</pre><p>To remove an object from cache, simply annotate with CacheRemove.</p><pre>@CacheRemove<br>public void update(<br> @CacheKey final long userId,<br> final User user) throws ResourceNotFoundException {</pre><p>One can update the cache values using CachePut annotation,</p><pre>@CachePut(afterInvocation = false)<br> public void refreshCache(<br> @CacheKey final String userToken,<br> @CacheValue final UserToken token) {</pre><p>One catch with Caching and Spring / Spring boot application is that one cannot call the method in the same class to do cache updates. One will have to return to different class to have cache updates,</p><pre>//RemoteUser &lt;- Different from UserService file<br>public void updateUser(final long userId) {<br> //call to update user object<br> userService.update(userId, userObj);<br> // user updates, then call refresh cache<br> userService.refreshCache();</pre><p>EHCache config is detailed <a href="https://www.ehcache.org/documentation/3.8/getting-started.html">here.</a> To configure JCache with EHCache on Spring boot 2,</p><pre>@Configuration<br>@EnableCaching<br>public class CacheConfig extends CachingConfigurerSupport {<br><br>    private final Environment environment;<br><br>    public CacheConfig(Environment environment) {<br>        this.environment = environment;<br>    }<br><br>    /**<br>     * Return the class loader to use to retrieve the CacheManager from the Caching<br>     * Provider<br>     *<br>     * @return class loader to use<br>     */<br>    private ClassLoader getClassLoader() {<br>        return this.getClass().getClassLoader();<br>    }<br>    @Bean<br>    @Override<br>    public org.springframework.cache.CacheManager cacheManager() {<br>        return new JCacheCacheManager(createEhCacheManager());<br>    }<br><br>    private CacheManager createEhCacheManager() {<br>        EhcacheCachingProvider provider = getCachingProvider();<br>        DefaultConfiguration configuration = new DefaultConfiguration(getCacheConfigurations(), getClassLoader());<br>        return getCacheManager(provider, configuration);<br>    }<br><br>    private EhcacheCachingProvider getCachingProvider() {<br>        return (EhcacheCachingProvider) Caching.getCachingProvider();<br>    }</pre><pre>private Map&lt;String, CacheConfiguration&lt;?, ?&gt;&gt; getCacheConfigurations() {<br>  Map&lt;String, org.ehcache.config.CacheConfiguration&lt;?, ?&gt;&gt; caches = new HashMap&lt;&gt;();<br>  <br>  CacheConfiguration&lt;Object, Object&gt; userCache = CacheConfigurationBuilder<br>    .newCacheConfigurationBuilder(Object.class,<br>      Object.class,<br>      ResourcePoolsBuilder.newResourcePoolsBuilder()<br>        .heap(this.getUserMaxEntries(), EntryUnit.ENTRIES)<br>        .offheap(this.getUserOffHeap(), MemoryUnit.MB))<br>    .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(this.getUserTimeToLive())) //ttl config<br>    .withService(getCacheEventListener())<br>    .build();<br>    <br>  caches.put(&quot;user&quot;, userCache);</pre><pre>return caches;<br> }</pre><p>The EHcache events could be registered as follows,</p><pre>private DefaultCacheEventListenerConfiguration getCacheEventListener() {<br> EventType[] events = {<br> EventType.CREATED,<br> EventType.EVICTED,<br> EventType.EXPIRED,<br> EventType.REMOVED,<br> EventType.UPDATED };<br> Set&lt;EventType&gt; listenerEvents = new HashSet&lt;&gt;(Arrays.asList(events));</pre><pre> return new DefaultCacheEventListenerConfiguration(listenerEvents, EventLogger.class);</pre><pre> }</pre><p>The Event logger could be customized based on ehcache implementation, a sample is as below,</p><pre>@Component<br>public class EventLogger implements CacheEventListener&lt;Object, Object&gt; {</pre><pre> @Override<br> public void onEvent(<br> CacheEvent&lt;? extends Object, ? extends Object&gt; event) {<br> log.info(“Event: “<br> + event.getType()<br> + “ Key: “<br> + event.getKey()<br> + “ old value: “<br> + event.getOldValue()<br> + “ new value: “<br> + event.getNewValue());<br> }</pre><pre>}</pre><p>Hope the detailed config helps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4598d968af2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Completable Future — Java8]]></title>
            <link>https://medium.com/@dsrini.os/completable-future-java8-6b18d1f10847?source=rss-c94f3e6a9feb------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b18d1f10847</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[dsrini.os]]></dc:creator>
            <pubDate>Thu, 20 Feb 2020 19:24:15 GMT</pubDate>
            <atom:updated>2020-02-20T19:24:15.026Z</atom:updated>
            <content:encoded><![CDATA[<h3>Completable Future — Java8</h3><p>Probably you are aware that executing assynchronous code is easier with Java 8. Completable future provides a way to run tasks in async mode. The following sample piece of code illustrates a non-blocking execution of a batch process with a fixed thread pool.</p><pre>public class BatchProcess {<br><br>    private static String longProcess(<br>            int i) {<br>        try {<br>            if (i % 2 == 0)<br>                TimeUnit.SECONDS.sleep(1);<br>            else<br>                TimeUnit.SECONDS.sleep(2);<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br>        return new StringBuilder(&quot;Completed &quot;)<br>                        .append(i)<br>                        .toString();<br>    }<br><br>    private static CompletableFuture&lt;String&gt; createCF(<br>            final int looper,<br>            final Executor executor) {<br>        return CompletableFuture<br>                    .supplyAsync(<br>                        () -&gt; longProcess(looper), executor);<br>    }<br><br>    public static List&lt;String&gt; batchprocess() <br>            throws InterruptedException, ExecutionException {<br>        List&lt;CompletableFuture&lt;String&gt;&gt; ret = new ArrayList&lt;&gt;();<br>        ExecutorService exec = Executors.newFixedThreadPool(8);<br><br>        IntStream.range(1, 25)<br>            .forEach(i -&gt; ret.add(createCF(i, exec)));<br><br>        Optional&lt;List&lt;String&gt;&gt; results = Optional.empty();<br><br>        CompletableFuture&lt;Void&gt; all = <br>                CompletableFuture.allOf(<br>                        ret.toArray(<br>                            new CompletableFuture[ret.size()]));<br><br>        CompletableFuture&lt;List&lt;String&gt;&gt; resultsFuture = <br>            all.thenApply((<br>                    aVoid) -&gt; {<br>                exec.shutdown();<br>                return ret<br>                        .stream()<br>                        .map(future -&gt; future.join())<br>                        .collect(Collectors.toList());<br>            });<br><br>        results = Optional.of(resultsFuture.join());<br><br>        return results.get();<br>    }<br><br>    public static void main(String args[]) <br>            throws InterruptedException, ExecutionException {<br>        LocalDateTime start = LocalDateTime.now();<br><br>        System.out.println(batchprocess());<br>        System.out.println(<br>                &quot;Exec time:&quot; <br>                    + ChronoUnit.SECONDS.between(<br>                            start, LocalDateTime.now()));<br>    }<br>}</pre><p>All completable futures could be combined using allOf. But, this returns Void completable future which could be used to complete the flow,</p><pre>CompletableFuture&lt;Void&gt; all = <br>                CompletableFuture.allOf(<br>                        ret.toArray(<br>                            new F[ret.size()]));</pre><p>When passing custom executors, don’t forget to shutdown the executor —</p><pre>exec.shutdown();</pre><p>You could apply various functions <em>CompletableFuture</em></p><blockquote>join — Returns result value/ throws exception<br>complete — Completes if not completed <br>thenApply, thenAccept, thenCombine, thenCompose, thenRun— Apply new completion stages with stage result<br>whenComplete — new stage with stage result/throwable<br>supplyAsync — asynchronous task completion using forkjoin common pool<br>supplyAsync(supplier, executor) — asynchronous task completion using custom executor</blockquote><p>Oracle docs <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html">link</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b18d1f10847" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Babel 7 env based settings]]></title>
            <link>https://medium.com/@dsrini.os/babel-7-env-based-settings-843501d40dc1?source=rss-c94f3e6a9feb------2</link>
            <guid isPermaLink="false">https://medium.com/p/843501d40dc1</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[babel]]></category>
            <category><![CDATA[babeljs]]></category>
            <dc:creator><![CDATA[dsrini.os]]></dc:creator>
            <pubDate>Thu, 20 Jun 2019 21:26:14 GMT</pubDate>
            <atom:updated>2019-06-20T21:26:14.733Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://babeljs.io/docs/en/configuration">Configure Babel · Babel</a></p><p>Though babel provides the env based configuration; not a lot is clear until you could see an example</p><pre>module.exports = {<br>  env: {<br>    test: {<br>      plugins: [<br>        [<br>          require.resolve(&quot;babel-plugin-module-resolver&quot;),<br>          {<br>            root: [&quot;.&quot;, &quot;src&quot;],<br>            alias: {<br>              src: &quot;src&quot;,<br>              test: &quot;test&quot;,<br>            },<br>            loglevel: &quot;verbose&quot;<br>          }<br>        ]<br>      ]<br>    }<br>  },<br>  plugins: [<br>    &quot;babel-plugin-lodash&quot;,<br>    [&quot;<a href="http://twitter.com/babel/plugin-proposal-class-pro">@babel/plugin-proposal-class-pro</a>perties&quot;, { loose: true }]<br>  ],<br>  presets: [&quot;<a href="http://twitter.com/babel/preset-env">@babel/preset-env</a>&quot;]<br>};</pre><p>In the above example, I have used the babel module resolver for test purposes and you could specify this env property either using NODE_ENV or BABEL_ENV in the package scripts</p><pre>&quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;SET NODE_ENV=test&amp;&amp; mocha &quot;<br>}</pre><p>In windows the SET env property sets based on the total property value. If you have a space between “NODE_ENV=test &amp;&amp;” a space is used in the env as well, so beware of it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=843501d40dc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Natural Ordering of js files in gulp]]></title>
            <link>https://medium.com/@dsrini.os/natural-ordering-of-js-files-in-gulp-cecdacd86fe3?source=rss-c94f3e6a9feb------2</link>
            <guid isPermaLink="false">https://medium.com/p/cecdacd86fe3</guid>
            <category><![CDATA[gulp]]></category>
            <dc:creator><![CDATA[dsrini.os]]></dc:creator>
            <pubDate>Fri, 31 May 2019 21:20:27 GMT</pubDate>
            <atom:updated>2019-05-31T21:27:02.580Z</atom:updated>
            <content:encoded><![CDATA[<p>Though gulp-order, gulp-sort orders the files and one can provide their own compare function, neither works for natural order of files based on the folder or directory structure. For which I had to do the following —</p><pre>const gulp = require(‘gulp’);<br>const rename = require(‘gulp-rename’);<br>const replace = require(‘gulp-replace’);<br>const exec = require(‘gulp-exec’);</pre><pre>const jsFilesText = ‘jsFilesText.txt’;</pre><pre>const jsFiles = [‘src_1/**/*.js’, ‘src_1/**/*.js’, ‘src_3/**/*.js’];</pre><pre>function fileList() {<br> const locs = jsFiles.map((eachLoc) =&gt; `${eachLoc.replace(/\*\*\//g, “”)}`);<br> let listFiles = locs.map((eachLoc) =&gt; `dir /s /b ${eachLoc.replace(/\//g, “\\\\”)}`);<br> listFiles = listFiles.join(‘ &amp;&amp; ‘);</pre><pre>return gulp.src(‘some_root_file’, {<br> allowEmpty: true<br> })<br> .pipe(exec(`${listFiles}`, {<br> pipeStdout: true,<br> customTemplatingThing: “test”<br> }))<br> .pipe(exec.reporter({<br> err: false,<br> stderr: false,<br> stdout: false<br> }))<br> .pipe(rename(jsFilesText))<br> .pipe(replace(‘\\’, ‘/’))<br> .pipe(gulp.dest(‘./’));</pre><p>The above generates the list of files based on folder / directory structure order. Now, one could minimize those files using —</p><pre>const order = require(‘gulp-order’);<br>const gulpif = require(‘gulp-if’);<br>const concat = require(‘gulp-concat’);<br>const print = require(‘gulp-print’).default;<br>const uglify = require(‘gulp-uglify’);</pre><pre>const distFolder // provide folder<br>const jsUglifyOptions // provide options</pre><pre>const jsIgnoreFiles = [‘!src_1/**/*bundle*.js’, ‘!src2/**/*.min.js’];<br>const isProduction = process.env.NODE_ENV ? process.env.NODE_ENV.trim() === ‘production’ : false;</pre><pre>function minimize() {<br> let listFiles = fs.readFileSync(jsFilesText, “utf-8”);<br> let files = listFiles.split(‘\r\n’);<br> let totalFiles = jsFiles.concat(jsIgnoreFiles);</pre><pre>return gulp.src(totalFiles)<br> .pipe(order(files, {<br> base: “.”<br> }))<br> .pipe(gulpif(!isProduction, print()))<br> .pipe(concat(‘dist.js’))<br> .pipe(gulp.dest(`${distFolder}`))<br> .pipe(gulpif(isProduction, rename(‘dist.min.js’)))<br> .pipe(gulpif(isProduction, uglify(jsUglifyOptions)))<br> .pipe(gulpif(isProduction, gulp.dest(`${distFolder}`)));<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cecdacd86fe3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>