List of usage examples for java.util Deque pop
E pop();
From source file:io.jmnarloch.spring.cloud.zuul.trie.AbstractTrie.java
private T put(N root, String key, T value) { N node = root;/*from w w w.j a v a2s .c om*/ final Deque<N> stack = new LinkedList<N>(); stack.push(node); N next; int index = 0; while (index < key.length()) { final char c = getChar(key, index); next = node.getNext(c); if (next == null) { next = createTrieNode(); node.setNext(c, next); } node = next; stack.push(node); index++; } final boolean replaced = node.hasValue(); final T old = node.getValue(); node.setValue(value); if (replaced) { return old; } while (!stack.isEmpty()) { node = stack.pop(); node.setSize(node.getSize() + 1); } return null; }
From source file:de.escalon.hypermedia.hydra.serialize.JacksonHydraSerializer.java
@Override public void serialize(Object bean, JsonGenerator jgen, SerializerProvider serializerProvider) throws IOException { if (!isUnwrappingSerializer()) { jgen.writeStartObject();/*from www. jav a 2s . c om*/ } Deque<String> deque = (Deque<String>) serializerProvider.getAttribute(KEY_LD_CONTEXT); if (deque == null) { deque = new ArrayDeque<String>(); serializerProvider.setAttribute(KEY_LD_CONTEXT, deque); } serializeContext(bean, jgen, serializerProvider, deque); serializeType(bean, jgen, serializerProvider); serializeFields(bean, jgen, serializerProvider); if (!isUnwrappingSerializer()) { jgen.writeEndObject(); } deque = (Deque<String>) serializerProvider.getAttribute(KEY_LD_CONTEXT); if (!deque.isEmpty()) { deque.pop(); } }
From source file:RandomChooser.java
private RandomChooser(List<Double> weights, List<T> events, Random random) { double sum = 0.0; for (double prob : weights) sum += prob;/*from w w w . ja v a 2 s.c o m*/ this.probs = new double[weights.size()]; for (int i = 0; i < weights.size(); i++) { probs[i] = weights.get(i) * weights.size() / sum; //average = 1.0 } Deque<Integer> smaller = new ArrayDeque<Integer>(weights.size() / 2 + 2); Deque<Integer> greater = new ArrayDeque<Integer>(weights.size() / 2 + 2); for (int i = 0; i < probs.length; i++) { if (probs[i] < 1.0) { smaller.push(i); } else { greater.push(i); } } indexes = new int[weights.size()]; while (!smaller.isEmpty()) { Integer i = smaller.pop(); Integer k = greater.peek(); indexes[i] = k; probs[k] -= (1 - probs[i]); if (probs[k] < 1.0) { greater.pop(); if (greater.isEmpty()) break; smaller.push(k); } } this.events = events; this.random = random; }
From source file:com.grepcurl.random.ObjectGenerator.java
@SuppressWarnings("unused") public <T> T generate(Class<T> klass, Object... constructorArgs) { Validate.notNull(klass);//from ww w . j ava 2s . c om Validate.notNull(constructorArgs); if (verbose) { log(String.format("generating object of type: %s, with args: %s", klass, Arrays.toString(constructorArgs))); } try { Deque<Object> objectStack = new ArrayDeque<>(); Class[] constructorTypes = _toClasses(constructorArgs); T t; if (klass.isEnum()) { int randomOrdinal = randomInt(0, klass.getEnumConstants().length - 1); t = klass.getEnumConstants()[randomOrdinal]; } else { t = klass.getConstructor(constructorTypes).newInstance(constructorArgs); } objectStack.push(t); Method[] methods = klass.getMethods(); for (Method method : methods) { _processMethod(method, new SetterOverrides(), t, objectStack); } objectStack.pop(); return t; } catch (Exception e) { throw new FailedRandomObjectGenerationException(e); } }
From source file:org.eclipse.cbi.maven.plugins.macsigner.SignMojo.java
/** * Creates a zip file.//from w w w . ja v a 2 s . c o m * @param dir The Directory of the files to be zipped. * @param zip An output stream to write the file * @throws IOException */ private void createZip(File dir, ZipArchiveOutputStream zip) throws IOException { Deque<File> dir_stack = new LinkedList<File>(); dir_stack.push(dir); // base path is the parent of the "Application.app" folder // it will be used to make "Application.app" the top-level folder in the zip String base_path = getParentDirAbsolutePath(dir); // verify that "dir" actually id the ".app" folder if (!dir.getName().endsWith(".app")) throw new IOException("Please verify the configuration. Directory does not end with '.app': " + dir); while (!dir_stack.isEmpty()) { File file = dir_stack.pop(); File[] files = file.listFiles(); for (File f : files) { String name = f.getAbsolutePath().substring(base_path.length()); getLog().debug("Found: " + name); if (f.isFile() && isInContentsFolder(name)) { getLog().debug("Adding to zip file for signing: " + f); ZipArchiveEntry entry = new ZipArchiveEntry(name); zip.putArchiveEntry(entry); if (f.canExecute()) { //work around to track the relative file names // of those that need to be set as executable on unZip executableFiles.add(name); } InputStream is = new FileInputStream(f); copyInputStreamToOutputStream(is, zip); is.close(); zip.closeArchiveEntry(); } else if (f.isDirectory() && isInContentsFolder(name)) { //add directory entry dir_stack.push(f); } else { getLog().debug(f + " was not included in the zip file to be signed."); } } } }
From source file:com.streamsets.datacollector.definition.ConfigDefinitionExtractor.java
void resolveDependencies(String configPrefix, List<ConfigDefinition> defs, Object contextMsg) { Map<String, ConfigDefinition> definitionsMap = new HashMap<>(); Map<String, Map<String, Set<Object>>> dependencyMap = new HashMap<>(); Map<String, Boolean> isFullyProcessed = new HashMap<>(); for (ConfigDefinition def : defs) { definitionsMap.put(def.getName(), def); dependencyMap.put(def.getName(), new HashMap<String, Set<Object>>()); isFullyProcessed.put(def.getName(), false); }//from w w w .ja v a2 s . c o m cycles.clear(); for (ConfigDefinition def : defs) { String dependsOnKey = def.getDependsOn(); if (!StringUtils.isEmpty(dependsOnKey)) { verifyDependencyExists(definitionsMap, def, dependsOnKey, contextMsg); ConfigDefinition dependsOnDef = definitionsMap.get(dependsOnKey); // evaluate dependsOn triggers ConfigDef annotation = def.getConfigField().getAnnotation(ConfigDef.class); Set<Object> triggers = new HashSet<>(); for (String trigger : annotation.triggeredByValue()) { triggers.add(ConfigValueExtractor.get().extract(dependsOnDef.getConfigField(), dependsOnDef.getType(), trigger, contextMsg, true)); } dependencyMap.get(def.getName()).put(dependsOnDef.getName(), triggers); } // Add direct dependencies to dependencyMap if (!def.getDependsOnMap().isEmpty()) { // Copy same as above. for (Map.Entry<String, List<Object>> dependsOn : def.getDependsOnMap().entrySet()) { dependsOnKey = dependsOn.getKey(); if (!StringUtils.isEmpty(dependsOnKey)) { verifyDependencyExists(definitionsMap, def, dependsOnKey, contextMsg); Set<Object> triggers = new HashSet<>(); ConfigDefinition dependsOnDef = definitionsMap.get(dependsOnKey); for (Object trigger : dependsOn.getValue()) { triggers.add(ConfigValueExtractor.get().extract(dependsOnDef.getConfigField(), dependsOnDef.getType(), (String) trigger, contextMsg, true)); } Map<String, Set<Object>> dependencies = dependencyMap.get(def.getName()); if (dependencies.containsKey(dependsOnKey)) { dependencies.get(dependsOnKey).addAll(triggers); } else { dependencies.put(dependsOnKey, triggers); } } } } } for (ConfigDefinition def : defs) { if (isFullyProcessed.get(def.getName())) { continue; } // Now find all indirect dependencies Deque<StackNode> stack = new ArrayDeque<>(); stack.push(new StackNode(def, new LinkedHashSet<String>())); while (!stack.isEmpty()) { StackNode current = stack.peek(); // We processed this one's dependencies before, don't bother adding its children // The dependencies of this one have all been processed if (current.childrenAddedToStack) { stack.pop(); Map<String, Set<Object>> currentDependencies = dependencyMap.get(current.def.getName()); Set<String> children = new HashSet<>(current.def.getDependsOnMap().keySet()); for (String child : children) { if (StringUtils.isEmpty(child)) { continue; } Map<String, Set<Object>> depsOfChild = dependencyMap.get(child); for (Map.Entry<String, Set<Object>> depOfChild : depsOfChild.entrySet()) { if (currentDependencies.containsKey(depOfChild.getKey())) { // Add only the common trigger values, // since it has to be one of those for both these to be triggered. Set<Object> currentTriggers = currentDependencies.get(depOfChild.getKey()); Set<Object> childTriggers = depOfChild.getValue(); currentDependencies.put(depOfChild.getKey(), Sets.intersection(currentTriggers, childTriggers)); } else { currentDependencies.put(depOfChild.getKey(), new HashSet<>(depOfChild.getValue())); } } } isFullyProcessed.put(current.def.getName(), true); } else { Set<String> children = current.def.getDependsOnMap().keySet(); String dependsOn = current.def.getDependsOn(); LinkedHashSet<String> dependencyAncestors = new LinkedHashSet<>(current.ancestors); dependencyAncestors.add(current.def.getName()); if (!StringUtils.isEmpty(dependsOn) && !isFullyProcessed.get(current.def.getDependsOn()) && !detectCycle(dependencyAncestors, cycles, dependsOn)) { stack.push( new StackNode(definitionsMap.get(current.def.getDependsOn()), dependencyAncestors)); } for (String child : children) { if (!StringUtils.isEmpty(child) && !isFullyProcessed.get(child) && !detectCycle(dependencyAncestors, cycles, child)) { stack.push(new StackNode(definitionsMap.get(child), dependencyAncestors)); } } current.childrenAddedToStack = true; } } } Preconditions.checkState(cycles.isEmpty(), "The following cycles were detected in the configuration dependencies:\n" + Joiner.on("\n").join(cycles)); for (Map.Entry<String, Map<String, Set<Object>>> entry : dependencyMap.entrySet()) { Map<String, List<Object>> dependencies = new HashMap<>(); definitionsMap.get(entry.getKey()).setDependsOnMap(dependencies); for (Map.Entry<String, Set<Object>> trigger : entry.getValue().entrySet()) { List<Object> triggerValues = new ArrayList<>(); triggerValues.addAll(trigger.getValue()); dependencies.put(trigger.getKey(), triggerValues); } definitionsMap.get(entry.getKey()).setDependsOn(""); } }
From source file:com.grepcurl.random.ObjectGenerator.java
protected <T> T generate(Class<T> klass, SetterOverrides setterOverrides, Deque<Object> objectStack, Object... constructorArgs) { Validate.notNull(klass);/*from w w w .j a v a 2s . c om*/ Validate.notNull(constructorArgs); if (verbose) { log(String.format("generating object of type: %s, with args: %s, with overrides: %s", klass, Arrays.toString(constructorArgs), setterOverrides)); } try { Class[] constructorTypes = _toClasses(constructorArgs); T t; if (klass.isEnum()) { int randomOrdinal = randomInt(0, klass.getEnumConstants().length - 1); t = klass.getEnumConstants()[randomOrdinal]; } else { t = klass.getConstructor(constructorTypes).newInstance(constructorArgs); } objectStack.push(t); Method[] methods = klass.getMethods(); for (Method method : methods) { _processMethod(method, setterOverrides, t, objectStack); } objectStack.pop(); return t; } catch (Exception e) { e.printStackTrace(); throw new FailedRandomObjectGenerationException(e); } }
From source file:io.bibleget.HTTPCaller.java
/** * * @param myQuery//from www . j a va 2 s . c o m * @param selectedVersions * @return * @throws java.lang.ClassNotFoundException * @throws java.io.UnsupportedEncodingException */ public boolean integrityCheck(String myQuery, List<String> selectedVersions) throws ClassNotFoundException, UnsupportedEncodingException { String versionsStr = StringUtils.join(selectedVersions.toArray(), ','); //System.out.println("Starting integrity check on query "+myQuery+" for versions: "+versionsStr); if (indexes == null) { indexes = Indexes.getInstance(); } //build indexes based on versions //final result is true until proved false //set finFlag to false for non-breaking errors, or simply return false for breaking errors boolean finFlag = true; errorMessages.removeAll(errorMessages); List<String> queries = new ArrayList<>(); //if english notation is found, translate to european notation if (myQuery.contains(":") && myQuery.contains(".")) { errorMessages.add(__( "Mixed notations have been detected. Please use either english notation or european notation.")); return false; } else if (myQuery.contains(":")) { if (myQuery.contains(",")) { myQuery = myQuery.replace(",", "."); } myQuery = myQuery.replace(":", ","); } if (myQuery.isEmpty() == false) { if (myQuery.contains(";")) { //System.out.println("We have a semicolon"); queries.addAll(Arrays.asList(myQuery.split(";"))); for (Iterator<String> it = queries.iterator(); it.hasNext();) { if (it.next().isEmpty()) { it.remove(); // NOTE: Iterator's remove method, not ArrayList's, is used. } } } else { //System.out.println("There is no semicolon"); queries.add(myQuery); } } boolean first = true; String currBook = ""; if (queries.isEmpty()) { errorMessages.add(__("You cannot send an empty query.")); return false; } for (String querie : queries) { //System.out.println(querie); querie = toProperCase(querie); //System.out.println(querie); //RULE 1: at least the first query must have a book indicator if (first) { if (querie.matches("^[1-3]{0,1}((\\p{L}\\p{M}*)+)(.*)") == false) { errorMessages.add(MessageFormat.format(__( "The first query <{0}> in the querystring <{1}> must start with a valid book indicator!"), querie, myQuery)); finFlag = false; } first = false; } //RULE 2: for every query that starts with a book indicator, // the book indicator must be followed by valid chapter indicator; // else query must start with valid chapter indicator int bBooksContains; int myidx = -1; String tempBook = ""; if (querie.matches("^[1-3]{0,1}((\\p{L}\\p{M}*)+)(.*)") == true) { //while we're at it, let's capture the book value from the query Pattern pattern = Pattern.compile("^[1-3]{0,1}((\\p{L}\\p{M}*)+)", Pattern.UNICODE_CHARACTER_CLASS); Matcher matcher = pattern.matcher(querie); if (matcher.find()) { tempBook = matcher.group(); bBooksContains = isValidBook(tempBook); myidx = bBooksContains + 1; //if(bBooksContains == false && bBooksAbbrevsContains == false){ if (bBooksContains == -1) { errorMessages.add(MessageFormat.format(__( "The book indicator <{0}> in the query <{1}> is not valid. Please check the documentation for a list of valid book indicators."), tempBook, querie)); finFlag = false; } else { //if(bBooksContains) currBook = tempBook; //querie = querie.replace(tempBook,""); } } Pattern pattern1 = Pattern.compile("^[1-3]{0,1}((\\p{L}\\p{M}*)+)", Pattern.UNICODE_CHARACTER_CLASS); Pattern pattern2 = Pattern.compile("^[1-3]{0,1}((\\p{L}\\p{M}*)+)[1-9][0-9]{0,2}", Pattern.UNICODE_CHARACTER_CLASS); Matcher matcher1 = pattern1.matcher(querie); Matcher matcher2 = pattern2.matcher(querie); int count1 = 0; while (matcher1.find()) { count1++; } int count2 = 0; while (matcher2.find()) { count2++; } if (querie.matches("^[1-3]{0,1}((\\p{L}\\p{M}*)+)[1-9][0-9]{0,2}(.*)") == false || count1 != count2) { errorMessages.add(__("You must have a valid chapter following the book indicator!")); finFlag = false; } querie = querie.replace(tempBook, ""); } else { if (querie.matches("^[1-9][0-9]{0,2}(.*)") == false) { errorMessages.add(__( "A query that doesn't start with a book indicator must however start with a valid chapter indicator!")); finFlag = false; } } //RULE 3: Queries with a dot operator must first have a comma operator; and cannot have more commas than dots if (querie.contains(".")) { Pattern pattern11 = Pattern.compile("[,|\\-|\\.][1-9][0-9]{0,2}\\."); Matcher matcher11 = pattern11.matcher(querie); if (querie.contains(",") == false || matcher11.find() == false) { errorMessages.add(__( "You cannot use a dot without first using a comma or a dash. A dot is a liason between verses, which are separated from the chapter by a comma.")); finFlag = false; } Pattern pattern3 = Pattern.compile("(?<![0-9])(?=(([1-9][0-9]{0,2})\\.([1-9][0-9]{0,2})))"); Matcher matcher3 = pattern3.matcher(querie); int count = 0; while (matcher3.find()) { //RULE 4: verse numbers around dot operators must be sequential if (Integer.parseInt(matcher3.group(2)) >= Integer.parseInt(matcher3.group(3))) { errorMessages.add(MessageFormat.format(__( "Verses concatenated by a dot must be consecutive, instead <{0}> is greater than or equal to <{1}> in the expression <{2}> in the query <{3}>"), matcher3.group(2), matcher3.group(3), matcher3.group(1), querie)); finFlag = false; } count++; } //RULE 5: Dot operators must be preceded and followed by a number from one to three digits, of which the first digit cannot be a 0 if (count == 0 || count != StringUtils.countMatches(querie, ".")) { errorMessages.add(__( "A dot must be preceded and followed by 1 to 3 digits of which the first digit cannot be zero.") + " <" + querie + ">"); finFlag = false; } } //RULE 6: Comma operators must be preceded and followed by a number from one to three digits, of which the first digit cannot be 0 if (querie.contains(",")) { Pattern pattern4 = Pattern.compile("([1-9][0-9]{0,2})\\,[1-9][0-9]{0,2}"); Matcher matcher4 = pattern4.matcher(querie); int count = 0; List<Integer> chapters = new ArrayList<>(); while (matcher4.find()) { //System.out.println("group0="+matcher4.group(0)+", group1="+matcher4.group(1)); chapters.add(Integer.parseInt(matcher4.group(1))); count++; } if (count == 0 || count != StringUtils.countMatches(querie, ",")) { errorMessages.add(__( "A comma must be preceded and followed by 1 to 3 digits of which the first digit cannot be zero.") + " <" + querie + ">" + "(count=" + Integer.toString(count) + ",comma count=" + StringUtils.countMatches(querie, ",") + "); chapters=" + chapters.toString()); finFlag = false; } else { // let's check the validity of the chapter numbers against the version indexes //for each chapter captured in the querystring for (int chapter : chapters) { if (indexes.isValidChapter(chapter, myidx, selectedVersions) == false) { int[] chapterLimit = indexes.getChapterLimit(myidx, selectedVersions); errorMessages.add(MessageFormat.format(__( "A chapter in the query is out of bounds: there is no chapter <{0}> in the book <{1}> in the requested version <{2}>, the last possible chapter is <{3}>"), Integer.toString(chapter), currBook, StringUtils.join(selectedVersions, ","), StringUtils.join(chapterLimit, ','))); finFlag = false; } } } } if (StringUtils.countMatches(querie, ",") > 1) { if (!querie.contains("-")) { errorMessages.add(__("You cannot have more than one comma and not have a dash!")); finFlag = false; } String[] parts = StringUtils.split(querie, "-"); if (parts.length != 2) { errorMessages .add(__("You seem to have a malformed querystring, there should be only one dash.")); finFlag = false; } for (String p : parts) { Integer[] pp = new Integer[2]; String[] tt = StringUtils.split(p, ","); int x = 0; for (String t : tt) { pp[x++] = Integer.parseInt(t); } if (indexes.isValidChapter(pp[0], myidx, selectedVersions) == false) { int[] chapterLimit; chapterLimit = indexes.getChapterLimit(myidx, selectedVersions); // System.out.print("chapterLimit = "); // System.out.println(Arrays.toString(chapterLimit)); errorMessages.add(MessageFormat.format(__( "A chapter in the query is out of bounds: there is no chapter <{0}> in the book <{1}> in the requested version <{2}>, the last possible chapter is <{3}>"), Integer.toString(pp[0]), currBook, StringUtils.join(selectedVersions, ","), StringUtils.join(chapterLimit, ','))); finFlag = false; } else { if (indexes.isValidVerse(pp[1], pp[0], myidx, selectedVersions) == false) { int[] verseLimit = indexes.getVerseLimit(pp[0], myidx, selectedVersions); // System.out.print("verseLimit = "); // System.out.println(Arrays.toString(verseLimit)); errorMessages.add(MessageFormat.format(__( "A verse in the query is out of bounds: there is no verse <{0}> in the book <{1}> at chapter <{2}> in the requested version <{3}>, the last possible verse is <{4}>"), Integer.toString(pp[1]), currBook, Integer.toString(pp[0]), StringUtils.join(selectedVersions, ","), StringUtils.join(verseLimit, ','))); finFlag = false; } } } } else if (StringUtils.countMatches(querie, ",") == 1) { String[] parts = StringUtils.split(querie, ","); //System.out.println(Arrays.toString(parts)); if (indexes.isValidChapter(Integer.parseInt(parts[0]), myidx, selectedVersions) == false) { int[] chapterLimit = indexes.getChapterLimit(myidx, selectedVersions); errorMessages.add(MessageFormat.format(__( "A chapter in the query is out of bounds: there is no chapter <{0}> in the book <{1}> in the requested version <{2}>, the last possible chapter is <{3}>"), parts[0], currBook, StringUtils.join(selectedVersions, ","), StringUtils.join(chapterLimit, ','))); finFlag = false; } else { if (parts[1].contains("-")) { Deque<Integer> highverses = new ArrayDeque<>(); Pattern pattern11 = Pattern.compile("[,\\.][1-9][0-9]{0,2}\\-([1-9][0-9]{0,2})"); Matcher matcher11 = pattern11.matcher(querie); while (matcher11.find()) { highverses.push(Integer.parseInt(matcher11.group(1))); } int highverse = highverses.pop(); if (indexes.isValidVerse(highverse, Integer.parseInt(parts[0]), myidx, selectedVersions) == false) { int[] verseLimit = indexes.getVerseLimit(Integer.parseInt(parts[0]), myidx, selectedVersions); errorMessages.add(MessageFormat.format(__( "A verse in the query is out of bounds: there is no verse <{0}> in the book <{1}> at chapter <{2}> in the requested version <{3}>, the last possible verse is <{4}>"), highverse, currBook, parts[0], StringUtils.join(selectedVersions, ","), StringUtils.join(verseLimit, ','))); finFlag = false; } } else { Pattern pattern12 = Pattern.compile(",([1-9][0-9]{0,2})"); Matcher matcher12 = pattern12.matcher(querie); int highverse = -1; while (matcher12.find()) { highverse = Integer.parseInt(matcher12.group(1)); //System.out.println("[line 376]:highverse="+Integer.toString(highverse)); } if (highverse != -1) { //System.out.println("Checking verse validity for book "+myidx+" chapter "+parts[0]+"..."); if (indexes.isValidVerse(highverse, Integer.parseInt(parts[0]), myidx, selectedVersions) == false) { int[] verseLimit = indexes.getVerseLimit(Integer.parseInt(parts[0]), myidx, selectedVersions); errorMessages.add(MessageFormat.format(__( "A verse in the query is out of bounds: there is no verse <{0}> in the book <{1}> at chapter <{2}> in the requested version <{3}>, the last possible verse is <{4}>"), highverse, currBook, parts[0], StringUtils.join(selectedVersions, ","), StringUtils.join(verseLimit, ','))); finFlag = false; } } } Pattern pattern13 = Pattern.compile("\\.([1-9][0-9]{0,2})$"); Matcher matcher13 = pattern13.matcher(querie); int highverse = -1; while (matcher13.find()) { highverse = Integer.parseInt(matcher13.group(1)); } if (highverse != -1) { if (indexes.isValidVerse(highverse, Integer.parseInt(parts[0]), myidx, selectedVersions) == false) { int[] verseLimit = indexes.getVerseLimit(Integer.parseInt(parts[0]), myidx, selectedVersions); errorMessages.add(MessageFormat.format(__( "A verse in the query is out of bounds: there is no verse <{0}> in the book <{1}> at chapter <{2}> in the requested version <{3}>, the last possible verse is <{4}>"), highverse, currBook, parts[0], StringUtils.join(selectedVersions, ","), StringUtils.join(verseLimit, ','))); finFlag = false; } } } } else { //if there is no comma, it's either a single chapter or an extension of chapters with a dash //System.out.println("no comma found"); String[] parts = StringUtils.split(querie, "-"); //System.out.println(Arrays.toString(parts)); int highchapter = Integer.parseInt(parts[parts.length - 1]); if (indexes.isValidChapter(highchapter, myidx, selectedVersions) == false) { int[] chapterLimit = indexes.getChapterLimit(myidx, selectedVersions); errorMessages.add(MessageFormat.format(__( "A chapter in the query is out of bounds: there is no chapter <{0}> in the book <{1}> in the requested version <{2}>, the last possible chapter is <{3}>"), Integer.toString(highchapter), currBook, StringUtils.join(selectedVersions, ","), StringUtils.join(chapterLimit, ','))); finFlag = false; } } if (querie.contains("-")) { //RULE 7: If there are multiple dashes in a query, there cannot be more dashes than there are dots minus 1 int dashcount = StringUtils.countMatches(querie, "-"); int dotcount = StringUtils.countMatches(querie, "."); if (dashcount > 1) { if (dashcount - 1 > dotcount) { errorMessages.add(__( "There are multiple dashes in the query, but there are not enough dots. There can only be one more dash than dots.") + " <" + querie + ">"); finFlag = false; } } //RULE 8: Dash operators must be preceded and followed by a number from one to three digits, of which the first digit cannot be 0 Pattern pattern5 = Pattern.compile("([1-9][0-9]{0,2}\\-[1-9][0-9]{0,2})"); Matcher matcher5 = pattern5.matcher(querie); int count = 0; while (matcher5.find()) { count++; } if (count == 0 || count != StringUtils.countMatches(querie, "-")) { errorMessages.add(__( "A dash must be preceded and followed by 1 to 3 digits of which the first digit cannot be zero.") + " <" + querie + ">"); finFlag = false; } //RULE 9: If a comma construct follows a dash, there must also be a comma construct preceding the dash Pattern pattern6 = Pattern.compile("\\-([1-9][0-9]{0,2})\\,"); Matcher matcher6 = pattern6.matcher(querie); if (matcher6.find()) { Pattern pattern7 = Pattern.compile("\\,[1-9][0-9]{0,2}\\-"); Matcher matcher7 = pattern7.matcher(querie); if (matcher7.find() == false) { errorMessages.add(__( "If there is a chapter-verse construct following a dash, there must also be a chapter-verse construct preceding the same dash.") + " <" + querie + ">"); finFlag = false; } else { //RULE 10: Chapters before and after dashes must be sequential int chap1 = -1; int chap2 = -1; Pattern pattern8 = Pattern.compile("([1-9][0-9]{0,2})\\,[1-9][0-9]{0,2}\\-"); Matcher matcher8 = pattern8.matcher(querie); if (matcher8.find()) { chap1 = Integer.parseInt(matcher8.group(1)); } Pattern pattern9 = Pattern.compile("\\-([1-9][0-9]{0,2})\\,"); Matcher matcher9 = pattern9.matcher(querie); if (matcher9.find()) { chap2 = Integer.parseInt(matcher9.group(1)); } if (chap1 >= chap2) { errorMessages.add(MessageFormat.format(__( "Chapters must be consecutive. Instead the first chapter indicator <{0}> is greater than or equal to the second chapter indicator <{1}> in the expression <{2}>"), chap1, chap2, querie)); finFlag = false; } } } else { //if there are no comma constructs immediately following the dash //RULE 11: Verses (or chapters if applicable) around each of the dash operator(s) must be sequential Pattern pattern10 = Pattern.compile("([1-9][0-9]{0,2})\\-([1-9][0-9]{0,2})"); Matcher matcher10 = pattern10.matcher(querie); while (matcher10.find()) { int num1 = Integer.parseInt(matcher10.group(1)); int num2 = Integer.parseInt(matcher10.group(2)); if (num1 >= num2) { errorMessages.add(MessageFormat.format(__( "Verses (or chapters if applicable) around the dash operator must be consecutive. Instead <{0}> is greater than or equal to <{1}> in the expression <{2}>"), num1, num2, querie)); finFlag = false; } } } } } return finFlag; }