{"id":1178,"date":"2020-12-16T10:50:24","date_gmt":"2020-12-16T10:50:24","guid":{"rendered":"https:\/\/blog.samarthya.me\/wps\/?p=1178"},"modified":"2020-12-16T10:50:25","modified_gmt":"2020-12-16T10:50:25","slug":"fortune-v1-0","status":"publish","type":"post","link":"https:\/\/blog.samarthya.me\/wps\/2020\/12\/16\/fortune-v1-0\/","title":{"rendered":"Fortune v1.0"},"content":{"rendered":"\n<p>In one of recent discussions <code>with  Mr. X<\/code> I was asked about my approach to solving the Linux cookie problem<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>A random quote <\/li><li>Repository will be a text file<\/li><li>Each quote will be segregated by a <code>'%'<\/code><\/li><li>Can be multiline.<\/li><\/ol>\n\n\n\n<p>I always believe in incremental steps so here is what I could think of<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Read the File for the DB<\/li><li>Parse each line and merge or drop as required for <code>'%<\/code>&#8216;.<\/li><li>randomization can be an external factor &#8211; but that is step 2.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Read DB<\/h2>\n\n\n\n<p>The final class looks like something below<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class FortuneTeller {\n    private final Logger logger = Logger.getLogger(FortuneTeller.class.getName());\n\n    private List&lt;String> allData = new LinkedList&lt;String>();\n\n    public FortuneTeller(File dbFile) {\n        this.dbFile = dbFile;\n    }\n\n    private File dbFile;\n\n    public FortuneTeller() {\n        this(null);\n        logger.log(Level.WARNING, \"empty initialization\");\n    }\n\n    public void populateDB() {\n        this.populateDB(this.dbFile);\n    }\n\n    \/**\n     * Read the complete data.\n     * @param localFile\n     *\/\n    public void populateDB(File localFile) {\n        if (localFile == null ){\n            throw new IllegalArgumentException(\"NO FILE SPECIFIED: file name is invalid\");\n        }\n\n        if ( localFile.exists()) {\n            System.out.println( \" File found \");\n            try {\n                \/**\n                 * https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/nio\/file\/Files.html\n                 *\/\n                List&lt;String> allLines = Files.readAllLines(localFile.toPath()).stream().collect(Collectors.toList());\n\n                StringBuffer sb = new StringBuffer();\n\n                for (String str: allLines) {\n\n                    if (str.compareTo(\"%\") != 0) {\n                        sb.append(str);\n\n                        if (allLines.indexOf(str) == allLines.size() - 1) {\n                            allData.add(sb.toString() +\"\\n\");\n                            break;\n                        } else {\n                            sb.append(\"\\n\");\n                            continue;\n                        }\n                    } else {\n                        allData.add(sb.toString());\n                        sb.setLength(0);\n                    }\n                }\n                return;\n            } catch (IOException e) {\n                throw new InternalError(\"something went wrong\");\n            }\n        } else {\n            System.out.println(\"file not found: \" + localFile.getPath());\n        }\n    }\n\n    public String myFortune(int index) {\n        if (allData.size() == 0) {\n            System.out.println(\"no data in the system\");\n            throw new InternalError(\"no data in the system\");\n        }\n        return allData.get(index%allData.size()).toString();\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">DB population: <code>populateDB<\/code><\/h3>\n\n\n\n<div class=\"wp-block-group\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<pre class=\"wp-block-code\"><code>public void populateDB(File localFile) {\n        if (localFile == null ){\n            throw new IllegalArgumentException(\"NO FILE SPECIFIED: file name is invalid\");\n        }\n\n        if ( localFile.exists()) {\n            System.out.println( \" File found \");\n            try {\n                List&lt;String> allLines = Files.readAllLines(localFile.toPath()).stream().collect(Collectors.toList());\n\n                StringBuffer sb = new StringBuffer();\n\n                for (String str: allLines) {\n\n                    if (str.compareTo(\"%\") != 0) {\n                        sb.append(str);\n\n                        if (allLines.indexOf(str) == allLines.size() - 1) {\n                            allData.add(sb.toString() +\"\\n\");\n                            break;\n                        } else {\n                            sb.append(\"\\n\");\n                            continue;\n                        }\n                    } else {\n                        allData.add(sb.toString());\n                        sb.setLength(0);\n                    }\n                }\n                return;\n            } catch (IOException e) {\n                throw new InternalError(\"something went wrong\");\n            }\n        } else {\n            System.out.println(\"file not found: \" + localFile.getPath());\n        }\n    }<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\"><li>If the file-argument is null Throw <code>illegalArgumentException<\/code><\/li><li>Read all the files &#8216;no explicit` skipping<\/li><\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>Files.readAllLines(localFile.toPath()).stream().collect(Collectors.toList());<\/code><\/pre>\n\n\n\n<p>Once the Lines are read &#8211; time to parse each line and<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Drop all &#8216;<code>%<\/code>&#8216;<\/li><li>All lines terminated by &#8216;<code>%<\/code>&#8216; will be joined by a new line character.<\/li><\/ul>\n\n\n\n<pre id=\"block-7532ed31-ce52-4acb-bd63-42d61f75bc50\" class=\"wp-block-code\"><code>for (String str: allLines) {\n\n    if (str.compareTo(\"%\") != 0) {\n        sb.append(str);\n\n        if (allLines.indexOf(str) == allLines.size() - 1) {\n            allData.add(sb.toString() + \"\\n\");\n            break;\n        } else {\n            sb.append(\"\\n\");\n            continue;\n        }\n    } else {\n        allData.add(sb.toString());\n        sb.setLength(0);\n    }\n}<\/code><\/pre>\n\n\n\n<p>Iterate through all the Lines read, and if the line is not just &#8216;<code>%<\/code>&#8216; we can append the next line.<\/p>\n<\/div><\/div>\n\n\n\n<p>At the end of the loop we will have <code>allData<\/code> populated with all the contents.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public String myFortune(int index) {\n        if (allData.size() == 0) {\n            System.out.println(\"no data in the system\");\n            throw new InternalError(\"no data in the system\");\n        }\n        return allData.get(index % allData.size()).toString();\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Fortune.DB<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>My life is simple\n%\nLife is easier when you have the right set of people around you,\nas friends and family to help you enjoy the moment.\n   - Saurabh\n%\nS\n%\nLife is never that simple<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Test &#8211; JUNIT<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>public class FortuneTellerTest {\n\n    private final FortuneTeller ft = new FortuneTeller();\n\n    @Test\n    void testFT() {\n        IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> ft.populateDB(null));\n        assertEquals(ex.getMessage(), \"NO FILE SPECIFIED: file name is invalid\");\n    }\n\n    @Test\n    void readLocal() {\n        ft.populateDB(new File(\"\/Users\/ss670121\/sourcebox\/learn\/golang\/exercism\/java\/MissingNumber\/src\/test\/resources\/fortune.txt\"));\n        assertEquals(ft.myFortune(0), \"My life is simple\\n\");\n        assertEquals(ft.myFortune(1), \"Life is easier when you have the right set of people around you,\\n\" +\n                \"as friends and family to help you enjoy the moment.\\n\" +\n                \"   - Saurabh\\n\");\n        assertEquals(ft.myFortune(2), \"S\\n\");\n        assertEquals(ft.myFortune(3), \"Life is never that simple\\n\");\n    }\n\n}\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>In one of recent discussions with Mr. X I was asked about my approach to solving the Linux cookie problem A random quote Repository will be a text file Each quote will be segregated by a &#8216;%&#8217; Can be multiline. I always believe in incremental steps so here is what I could think of Read [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"image","meta":{"_exactmetrics_skip_tracking":false,"_exactmetrics_sitenote_active":false,"_exactmetrics_sitenote_note":"","_exactmetrics_sitenote_category":0,"footnotes":""},"categories":[120,34],"tags":[129,121,130],"class_list":["post-1178","post","type-post","status-publish","format-image","hentry","category-java","category-technical","tag-fortune","tag-java","tag-query","post_format-post-format-image"],"_links":{"self":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts\/1178","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/comments?post=1178"}],"version-history":[{"count":0,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts\/1178\/revisions"}],"wp:attachment":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/media?parent=1178"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/categories?post=1178"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/tags?post=1178"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}