diff --git a/README.md b/README.md index 89a9d4f..bcf1594 100644 --- a/README.md +++ b/README.md @@ -117,3 +117,10 @@ lorem.getCountry(); ``` Generates a country name +#### Custom Category + +```java +lorem.getCustomValue("nouns"); +``` +Generates a random value from the seeded file value passed to the Lorem constructor. +If the category is not loaded `CategoryNotExist` exception will be thrown \ No newline at end of file diff --git a/src/main/java/com/thedeanda/lorem/Lorem.java b/src/main/java/com/thedeanda/lorem/Lorem.java index cfbae50..4fe2d1c 100644 --- a/src/main/java/com/thedeanda/lorem/Lorem.java +++ b/src/main/java/com/thedeanda/lorem/Lorem.java @@ -1,5 +1,7 @@ package com.thedeanda.lorem; +import com.thedeanda.lorem.exceptions.CategoryNotExist; + import java.time.Duration; import java.time.LocalDateTime; @@ -76,4 +78,5 @@ public interface Lorem { public LocalDateTime getFutureDate(Duration maxDurationFromNow); + public String getCustomValue(String category) throws CategoryNotExist; } \ No newline at end of file diff --git a/src/main/java/com/thedeanda/lorem/LoremIpsum.java b/src/main/java/com/thedeanda/lorem/LoremIpsum.java index e74d16f..9ed57be 100644 --- a/src/main/java/com/thedeanda/lorem/LoremIpsum.java +++ b/src/main/java/com/thedeanda/lorem/LoremIpsum.java @@ -1,31 +1,37 @@ package com.thedeanda.lorem; +import com.thedeanda.lorem.exceptions.CategoryNotExist; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.time.Duration; import java.time.LocalDateTime; -import java.time.temporal.ChronoUnit; -import java.time.temporal.Temporal; import java.util.ArrayList; import java.util.List; import java.util.Random; +import java.util.Map; +import java.util.HashMap; /** * The MIT License (MIT) - * + * * Copyright (c) 2015 Miguel De Anda - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -33,14 +39,14 @@ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. - * + * * @author mdeanda - * + * */ public class LoremIpsum implements Lorem { /* * this command was useful: - * + * * cat lorem.txt | sed -e 's/[,;.]//g' | sed -e 's/ /\n/g' | sed -e \ * 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/' | sort | \ * uniq > lorem.txt.2 @@ -57,6 +63,7 @@ public class LoremIpsum implements Lorem { private List stateFull; private List cities; private List countries; + private Map> customCategories; private String[] URL_HOSTS = new String[] { "https://www.google.com/#q=%s", "http://www.bing.com/search?q=%s", @@ -77,14 +84,22 @@ public static LoremIpsum getInstance() { public LoremIpsum() { this(new Random()); } - + public LoremIpsum(Long seed) { this(seed == null ? new Random() : new Random(seed)); } + public LoremIpsum(Map customCategToFile){ + this(new Random(), customCategToFile); + } + public LoremIpsum(Random random) { + this(random, null); + } + + public LoremIpsum(Random random, Map customCategToFile){ this.random = random; - + words = readLines("lorem.txt"); maleNames = readLines("male_names.txt"); femaleNames = readLines("female_names.txt"); @@ -97,6 +112,19 @@ public LoremIpsum(Random random) { stateAbbr = readLines("state_abbr.txt"); stateFull = readLines("state_full.txt"); countries = readLines("countries.txt"); + + if(customCategToFile != null && !customCategToFile.isEmpty()){ + this.customCategories = loadCustomCategories(customCategToFile); + } + } + + private Map> loadCustomCategories(Map customCategToFile){ + Map> customCateg = new HashMap>(); + for(String key : customCategToFile.keySet()){ + List customList = readExternalFiles(customCategToFile.get(key)); + customCateg.put(key, customList); + } + return customCateg; } private List readLines(String file) { @@ -123,9 +151,33 @@ private List readLines(String file) { return ret; } + private List readExternalFiles(String filePath){ + List ret = new ArrayList(); + BufferedReader br = null; + try{ + Path path = Paths.get(filePath); + br = Files.newBufferedReader(path, StandardCharsets.UTF_8); + String line; + while((line = br.readLine()) != null){ + ret.add(line.trim()); + } + }catch(IOException ex){ + ex.printStackTrace(); + }finally { + if(br != null){ + try { + br.close(); + }catch (IOException ex){ + ex.printStackTrace(); + } + } + } + return ret; + } + /* * (non-Javadoc) - * + * * @see com.thedeanda.lorem.Lorem#getCity() */ @Override @@ -135,7 +187,7 @@ public String getCity() { /* * (non-Javadoc) - * + * * @see com.thedeanda.lorem.Lorem#getCountry() */ @Override @@ -145,7 +197,7 @@ public String getCountry() { /* * (non-Javadoc) - * + * * @see com.thedeanda.lorem.Lorem#getEmail() */ @Override @@ -162,7 +214,7 @@ public String getEmail() { /* * (non-Javadoc) - * + * * @see com.thedeanda.lorem.Lorem#getFirstName() */ @Override @@ -172,7 +224,7 @@ public String getFirstName() { /* * (non-Javadoc) - * + * * @see com.thedeanda.lorem.Lorem#getFirstNameMale() */ @Override @@ -182,7 +234,7 @@ public String getFirstNameMale() { /* * (non-Javadoc) - * + * * @see com.thedeanda.lorem.Lorem#getFirstNameFemale() */ @Override @@ -192,7 +244,7 @@ public String getFirstNameFemale() { /* * (non-Javadoc) - * + * * @see com.thedeanda.lorem.Lorem#getLastName() */ @Override @@ -202,7 +254,7 @@ public String getLastName() { /* * (non-Javadoc) - * + * * @see com.thedeanda.lorem.Lorem#getName() */ @Override @@ -212,7 +264,7 @@ public String getName() { /* * (non-Javadoc) - * + * * @see com.thedeanda.lorem.Lorem#getNameMale() */ @Override @@ -222,7 +274,7 @@ public String getNameMale() { /* * (non-Javadoc) - * + * * @see com.thedeanda.lorem.Lorem#getNameFemale() */ @Override @@ -232,7 +284,7 @@ public String getNameFemale() { /* * (non-Javadoc) - * + * * @see com.thedeanda.lorem.Lorem#getTitle(int) */ @Override @@ -242,7 +294,7 @@ public String getTitle(int count) { /* * (non-Javadoc) - * + * * @see com.thedeanda.lorem.Lorem#getTitle(int, int) */ @Override @@ -261,7 +313,7 @@ private int getCount(int min, int max) { /* * (non-Javadoc) - * + * * @see com.thedeanda.lorem.Lorem#getHtmlParagraphs(int, int) */ @Override @@ -278,7 +330,7 @@ public String getHtmlParagraphs(int min, int max) { /* * (non-Javadoc) - * + * * @see com.thedeanda.lorem.Lorem#getParagraphs(int, int) */ @Override @@ -303,7 +355,7 @@ public String getParagraphs(int min, int max) { /* * (non-Javadoc) - * + * * @see com.thedeanda.lorem.Lorem#getUrl() */ @Override @@ -322,7 +374,7 @@ private String getWords(int min, int max, boolean title) { /* * (non-Javadoc) - * + * * @see com.thedeanda.lorem.Lorem#getWords(int) */ @Override @@ -332,7 +384,7 @@ public String getWords(int count) { /* * (non-Javadoc) - * + * * @see com.thedeanda.lorem.Lorem#getWords(int, int) */ @Override @@ -366,7 +418,7 @@ private String getRandom(List list) { /* * (non-Javadoc) - * + * * @see com.thedeanda.lorem.Lorem#getPhone() */ @Override @@ -394,7 +446,7 @@ public String getPhone() { /* * (non-Javadoc) - * + * * @see com.thedeanda.lorem.Lorem#getStateAbbr() */ @Override @@ -404,7 +456,7 @@ public String getStateAbbr() { /* * (non-Javadoc) - * + * * @see com.thedeanda.lorem.Lorem#getStateFull() */ @Override @@ -414,7 +466,7 @@ public String getStateFull() { /* * (non-Javadoc) - * + * * @see com.thedeanda.lorem.Lorem#getZipCode() */ @Override @@ -442,4 +494,15 @@ public LocalDateTime getFutureDate(Duration maxDurationFromNow) { return result; } + @Override + public String getCustomValue(String categoryName) throws CategoryNotExist { + return getRandom(getCustomCategList(categoryName)); + } + + private List getCustomCategList(String categoryName) throws CategoryNotExist { + if(this.customCategories == null || !this.customCategories.containsKey(categoryName)){ + throw new CategoryNotExist(categoryName); + } + return this.customCategories.get(categoryName); + } } diff --git a/src/main/java/com/thedeanda/lorem/exceptions/CategoryNotExist.java b/src/main/java/com/thedeanda/lorem/exceptions/CategoryNotExist.java new file mode 100644 index 0000000..b4f79dd --- /dev/null +++ b/src/main/java/com/thedeanda/lorem/exceptions/CategoryNotExist.java @@ -0,0 +1,8 @@ +package com.thedeanda.lorem.exceptions; + +public class CategoryNotExist extends Exception{ + + public CategoryNotExist(String categoryName){ + super(categoryName + " category is not loaded"); + } +} diff --git a/src/test/java/lorem/LoremCustomCategoryTest.java b/src/test/java/lorem/LoremCustomCategoryTest.java new file mode 100644 index 0000000..d2844d7 --- /dev/null +++ b/src/test/java/lorem/LoremCustomCategoryTest.java @@ -0,0 +1,51 @@ +package lorem; + +import com.thedeanda.lorem.Lorem; +import com.thedeanda.lorem.LoremIpsum; +import com.thedeanda.lorem.exceptions.CategoryNotExist; +import org.junit.Before; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +import static org.junit.Assert.*; + +public class LoremCustomCategoryTest { + + private Lorem lorem; + + private final String CATEGORY_VALUE = "nouns"; + + @Before + public void init() { + Map customCategInput = new HashMap(); + customCategInput.put(CATEGORY_VALUE, "C:\\dev\\MyStuff\\open-source-contributions\\lorem\\src\\test\\resources\\nouns.txt"); + lorem = new LoremIpsum(customCategInput); + } + + @Test + public void testCustomValue() { + try { + String val = lorem.getCustomValue(CATEGORY_VALUE); + assertNotNull(val); + assertNotEquals("", val.trim()); + }catch (CategoryNotExist ex){ + + } + } + + @Test(expected = CategoryNotExist.class) + public void testException() throws CategoryNotExist { + lorem.getCustomValue("countries"); + } + + @Test + public void testWithSeed() throws CategoryNotExist { + Map customCategInput = new HashMap(); + customCategInput.put(CATEGORY_VALUE, "C:\\dev\\MyStuff\\open-source-contributions\\lorem\\src\\test\\resources\\nouns.txt"); + Lorem lorem = new LoremIpsum(new Random(99l), customCategInput); + assertEquals("development", lorem.getCustomValue(CATEGORY_VALUE)); + } +} diff --git a/src/test/resources/nouns.txt b/src/test/resources/nouns.txt new file mode 100644 index 0000000..8b70ec1 --- /dev/null +++ b/src/test/resources/nouns.txt @@ -0,0 +1,743 @@ +people +history +way +art +world +information +map +two +family +government +health +system +computer +meat +year +thanks +music +person +reading +method +data +food +understanding +theory +law +bird +literature +problem +software +control +knowledge +power +ability +economics +love +internet +television +science +library +nature +fact +product +idea +temperature +investment +area +society +activity +story +industry +media +thing +oven +community +definition +safety +quality +development +language +management +player +variety +video +week +security +country +exam +movie +organization +equipment +physics +analysis +policy +series +thought +basis +boyfriend +direction +strategy +technology +army +camera +freedom +paper +environment +child +instance +month +truth +marketing +university +writing +article +department +difference +goal +news +audience +fishing +growth +income +marriage +user +combination +failure +meaning +medicine +philosophy +teacher +communication +night +chemistry +disease +disk +energy +nation +road +role +soup +advertising +location +success +addition +apartment +education +math +moment +painting +politics +attention +decision +event +property +shopping +student +wood +competition +distribution +entertainment +office +population +president +unit +category +cigarette +context +introduction +opportunity +performance +driver +flight +length +magazine +newspaper +relationship +teaching +cell +dealer +finding +lake +member +message +phone +scene +appearance +association +concept +customer +death +discussion +housing +inflation +insurance +mood +woman +advice +blood +effort +expression +importance +opinion +payment +reality +responsibility +situation +skill +statement +wealth +application +city +county +depth +estate +foundation +grandmother +heart +perspective +photo +recipe +studio +topic +collection +depression +imagination +passion +percentage +resource +setting +ad +agency +college +connection +criticism +debt +description +memory +patience +secretary +solution +administration +aspect +attitude +director +personality +psychology +recommendation +response +selection +storage +version +alcohol +argument +complaint +contract +emphasis +highway +loss +membership +possession +preparation +steak +union +agreement +cancer +currency +employment +engineering +entry +interaction +mixture +preference +region +republic +tradition +virus +actor +classroom +delivery +device +difficulty +drama +election +engine +football +guidance +hotel +owner +priority +protection +suggestion +tension +variation +anxiety +atmosphere +awareness +bath +bread +candidate +climate +comparison +confusion +construction +elevator +emotion +employee +employer +guest +height +leadership +mall +manager +operation +recording +sample +transportation +charity +cousin +disaster +editor +efficiency +excitement +extent +feedback +guitar +homework +leader +mom +outcome +permission +presentation +promotion +reflection +refrigerator +resolution +revenue +session +singer +tennis +basket +bonus +cabinet +childhood +church +clothes +coffee +dinner +drawing +hair +hearing +initiative +judgment +lab +measurement +mode +mud +orange +poetry +police +possibility +procedure +queen +ratio +relation +restaurant +satisfaction +sector +signature +significance +song +tooth +town +vehicle +volume +wife +accident +airport +appointment +arrival +assumption +baseball +chapter +committee +conversation +database +enthusiasm +error +explanation +farmer +gate +girl +hall +historian +hospital +injury +instruction +maintenance +manufacturer +meal +perception +pie +poem +presence +proposal +reception +replacement +revolution +river +son +speech +tea +village +warning +winner +worker +writer +assistance +breath +buyer +chest +chocolate +conclusion +contribution +cookie +courage +dad +desk +drawer +establishment +examination +garbage +grocery +honey +impression +improvement +independence +insect +inspection +inspector +king +ladder +menu +penalty +piano +potato +profession +professor +quantity +reaction +requirement +salad +sister +supermarket +tongue +weakness +wedding +affair +ambition +analyst +apple +assignment +assistant +bathroom +bedroom +beer +birthday +celebration +championship +cheek +client +consequence +departure +diamond +dirt +ear +fortune +friendship +funeral +gene +girlfriend +hat +indication +intention +lady +midnight +negotiation +obligation +passenger +pizza +platform +poet +pollution +recognition +reputation +shirt +sir +speaker +stranger +surgery +sympathy +tale +throat +trainer +uncle +youth +time +work +film +water +money +example +while +business +study +game +life +form +air +day +place +number +part +field +fish +back +process +heat +hand +experience +job +book +end +point +type +home +economy +value +body +market +guide +interest +state +radio +course +company +price +size +card +list +mind +trade +line +care +group +risk +word +fat +force +key +light +training +name +school +top +amount +level +order +practice +research +sense +service +piece +web +boss +sport +fun +house +page +term +test +answer +sound +focus +matter +kind +soil +board +oil +picture +access +garden +range +rate +reason +future +site +demand +exercise +image +case +cause +coast +action +age +bad +boat +record +result +section +building +mouse +cash +class +nothing +period +plan +store +tax +side +subject +space +rule +stock +weather +chance +figure +man +model +source +beginning +earth +program +chicken +design +feature +head +material +purpose +question +rock +salt +act +birth +car +dog +object +scale +sun +note +profit +rent +speed +style +war +bank +craft +half +inside +outside +standard +bus +exchange +eye +fire +position +pressure +stress +advantage +benefit +box +frame +issue +step +cycle +face +item +metal +paint +review +room +screen +structure +view +account +ball +discipline +medium +share +balance +bit +black +bottom +choice +gift +impact +machine +shape +tool +wind +address +average +career +culture +morning +pot +sign +table +task +condition +contact +credit +egg +hope +ice +network +north +square +attempt +date +effect +link +post +star +voice +capital +challenge +friend +self +shot +brush +couple +debate +exit +front +function +lack +living +plant +plastic +spot +summer +taste +theme +track +wing +brain +button +click +desire +foot +gas +influence +notice +rain +wall +base +damage +distance +feeling +pair +savings +staff +sugar +target \ No newline at end of file