Example usage for java.util ArrayDeque ArrayDeque

List of usage examples for java.util ArrayDeque ArrayDeque

Introduction

In this page you can find the example usage for java.util ArrayDeque ArrayDeque.

Prototype

public ArrayDeque() 

Source Link

Document

Constructs an empty array deque with an initial capacity sufficient to hold 16 elements.

Usage

From source file:com.espertech.esper.core.context.util.StatementAgentInstanceUtil.java

public static boolean evaluateFilterForStatement(EPServicesContext servicesContext, EventBean theEvent,
        AgentInstanceContext agentInstanceContext, FilterHandle filterHandle) {
    // context was created - reevaluate for the given event
    ArrayDeque<FilterHandle> callbacks = new ArrayDeque<FilterHandle>();
    servicesContext.getFilterService().evaluate(theEvent, callbacks,
            agentInstanceContext.getStatementContext().getStatementId());

    try {// www .  j a  v a2s .  c  om
        servicesContext.getVariableService().setLocalVersion();

        // sub-selects always go first
        for (FilterHandle handle : callbacks) {
            if (handle == filterHandle) {
                return true;
            }
        }

        agentInstanceContext.getEpStatementAgentInstanceHandle().internalDispatch(agentInstanceContext);

    } catch (RuntimeException ex) {
        servicesContext.getExceptionHandlingService().handleException(ex,
                agentInstanceContext.getEpStatementAgentInstanceHandle());
    }

    return false;
}

From source file:com.roche.sequencing.bioinformatics.common.utils.FileUtil.java

/**
 * taken from here http://codereview.stackexchange.com/questions/47923/simplifying-a-path -Kurt Heilman
 * /*from ww w  . j a  va 2s.c o m*/
 * @param path
 * @return
 */
public static String simplifyPath(String path) {
    String simplifiedPath = null;
    Deque<String> pathDeterminer = new ArrayDeque<String>();
    path = path.replaceAll(Pattern.quote("\\"), "/");
    path = path.replaceAll(Pattern.quote("\\\\"), "/");
    String[] pathSplitter = path.split("/");
    StringBuilder absolutePath = new StringBuilder();
    for (String term : pathSplitter) {
        if (term == null || term.length() == 0 || term.equals(".")) {
            /* ignore these guys */
        } else if (term.equals("..")) {
            if (pathDeterminer.size() > 0) {
                pathDeterminer.removeLast();
            }
        } else {
            pathDeterminer.addLast(term);
        }
    }
    if (pathDeterminer.isEmpty()) {
        simplifiedPath = "/";
    } else {
        while (!pathDeterminer.isEmpty()) {
            absolutePath.insert(0, pathDeterminer.removeLast());
            absolutePath.insert(0, "/");
        }
        simplifiedPath = absolutePath.toString();
    }
    return simplifiedPath;
}

From source file:com.google.gwt.emultest.java.util.ArrayDequeTest.java

public void testPop() {
    Object o1 = new Object();
    Object o2 = new Object();

    ArrayDeque<Object> deque = new ArrayDeque<>();
    try {/*from  w  w w . j a  v a 2s. com*/
        deque.pop();
        fail();
    } catch (NoSuchElementException expected) {
    }

    deque.add(o1);
    assertEquals(o1, deque.pop());
    assertTrue(deque.isEmpty());

    deque.add(o1);
    deque.add(o2);
    assertEquals(o1, deque.pop());
    checkDequeSizeAndContent(deque, o2);
    assertEquals(o2, deque.pop());
    assertTrue(deque.isEmpty());
    try {
        deque.pop();
        fail();
    } catch (NoSuchElementException expected) {
    }
}

From source file:com.google.gwt.emultest.java.util.ArrayDequeTest.java

public void testPush() {
    Object o1 = new Object();
    Object o2 = new Object();
    Object o3 = new Object();

    ArrayDeque<Object> deque = new ArrayDeque<>();
    deque.push(o1);/*from  w  w w.j a  v a  2s .  co m*/
    checkDequeSizeAndContent(deque, o1);
    deque.push(o2);
    checkDequeSizeAndContent(deque, o2, o1);
    deque.push(o3);
    checkDequeSizeAndContent(deque, o3, o2, o1);

    try {
        deque.push(null);
        fail();
    } catch (NullPointerException expected) {
    }
}

From source file:org.shaman.terrain.polygonal.PolygonalMapGenerator.java

/**
 * Step 4: assign elevation/*w  w  w.ja  v a2s.  c  o  m*/
 */
private void assignElevation() {
    if (graph == null) {
        return;
    }
    Random rand = new Random(seed * 2);
    //initialize border corners with zero elevation
    Deque<Graph.Corner> q = new ArrayDeque<>();
    for (Graph.Corner c : graph.corners) {
        if (c.border) {
            c.elevation = 0;
            q.add(c);
        } else {
            c.elevation = Float.POSITIVE_INFINITY;
        }
    }
    // Traverse the graph and assign elevations to each point. As we
    // move away from the map border, increase the elevations. This
    // guarantees that rivers always have a way down to the coast by
    // going downhill (no local minima).
    while (!q.isEmpty()) {
        Graph.Corner c = q.poll();
        for (Graph.Corner a : c.adjacent) {
            if (c.ocean && a.ocean && a.elevation > 0) {
                a.elevation = 0;
                q.addFirst(a);
                continue;
            }
            float elevation = c.elevation + (a.ocean ? 0 : 0.01f);
            if (!c.water && !a.water) {
                elevation += 1;
            }
            //add some more randomness
            //elevation += rand.nextDouble()/4;
            if (elevation < a.elevation) {
                a.elevation = elevation;
                q.add(a);
            }
        }
    }

    //redistribute elevation
    float SCALE_FACTOR = 1.1f;
    ArrayList<Graph.Corner> corners = new ArrayList<>();
    for (Graph.Corner c : graph.corners) {
        if (!c.ocean) {
            corners.add(c);
        }
    }
    Collections.sort(corners, new Comparator<Graph.Corner>() {
        @Override
        public int compare(Graph.Corner o1, Graph.Corner o2) {
            return Float.compare(o1.elevation, o2.elevation);
        }
    });
    for (int i = 0; i < corners.size(); i++) {
        // Let y(x) be the total area that we want at elevation <= x.
        // We want the higher elevations to occur less than lower
        // ones, and set the area to be y(x) = 1 - (1-x)^2.
        float y = (float) i / (float) (corners.size() - 1);
        float x = (float) (Math.sqrt(SCALE_FACTOR) - Math.sqrt(SCALE_FACTOR * (1 - y)));
        if (x > 1.0)
            x = 1; // TODO: does this break downslopes?
        corners.get(i).elevation = x;
    }

    assignCenterElevations();

    //update mesh
    updateElevationGeometry();
}

From source file:com.google.gwt.emultest.java.util.ArrayDequeTest.java

public void testRemove() {
    Object o1 = new Object();
    Object o2 = new Object();

    ArrayDeque<Object> deque = new ArrayDeque<>();
    try {//  www. j  a va  2s. c  om
        deque.remove();
        fail();
    } catch (NoSuchElementException expected) {
    }

    deque.add(o1);
    assertEquals(o1, deque.remove());
    assertTrue(deque.isEmpty());

    deque.add(o1);
    deque.add(o2);
    assertEquals(o1, deque.remove());
    checkDequeSizeAndContent(deque, o2);
    assertEquals(o2, deque.removeFirst());
    assertTrue(deque.isEmpty());

    try {
        deque.remove();
        fail();
    } catch (NoSuchElementException expected) {
    }
}

From source file:com.fizzed.rocker.compiler.JavaGenerator.java

private void createSourceTemplate(TemplateModel model, Writer w) throws GeneratorException, IOException {
    if (model.getOptions().getPostProcessing() != null) {
        // allow post-processors to transform the model
        try {//from w w w.ja  v  a2  s  .  c  om
            model = postProcess(model);
        } catch (PostProcessorException ppe) {
            throw new GeneratorException("Error during post-processing of model.", ppe);
        }
    }

    // Used to register any withstatements we encounter, so we can generate all dynamic consumers at the end.
    final WithStatementConsumerGenerator withStatementConsumerGenerator = new WithStatementConsumerGenerator();

    // simple increment to help create unique var names
    int varCounter = -1;

    if (model.getPackageName() != null && !model.getPackageName().equals("")) {
        w.append("package ").append(model.getPackageName()).append(";").append(CRLF);
    }

    // imports regardless of template
    w.append(CRLF);
    w.append("import ").append(java.io.IOException.class.getName()).append(";").append(CRLF);
    w.append("import ").append(com.fizzed.rocker.ForIterator.class.getName()).append(";").append(CRLF);
    w.append("import ").append(com.fizzed.rocker.RenderingException.class.getName()).append(";").append(CRLF);
    w.append("import ").append(com.fizzed.rocker.RockerContent.class.getName()).append(";").append(CRLF);
    w.append("import ").append(com.fizzed.rocker.RockerOutput.class.getName()).append(";").append(CRLF);
    w.append("import ").append(com.fizzed.rocker.runtime.DefaultRockerTemplate.class.getName()).append(";")
            .append(CRLF);
    w.append("import ").append(com.fizzed.rocker.runtime.PlainTextUnloadedClassLoader.class.getName())
            .append(";").append(CRLF);

    // template imports
    if (model.getImports().size() > 0) {
        for (JavaImport i : model.getImports()) {
            w.append("// import ").append(sourceRef(i)).append(CRLF);
            w.append("import ").append(i.getStatement()).append(";").append(CRLF);
        }
    }

    w.append(CRLF);
    w.append("/*").append(CRLF);
    w.append(" * Auto generated code to render template ").append(model.getPackageName().replace('.', '/'))
            .append("/").append(model.getTemplateName()).append(CRLF);
    w.append(" * Do not edit this file. Changes will eventually be overwritten by Rocker parser!").append(CRLF);
    w.append(" */").append(CRLF);

    int indent = 0;

    // MODEL CLASS

    // class definition
    tab(w, indent).append("public class ").append(model.getName()).append(" extends ")
            .append(model.getOptions().getExtendsModelClass()).append(" {").append(CRLF);

    indent++;

    w.append(CRLF);

    // static info about this template
    tab(w, indent).append("static public final ").append(ContentType.class.getCanonicalName())
            .append(" CONTENT_TYPE = ").append(ContentType.class.getCanonicalName()).append(".")
            .append(model.getContentType().toString()).append(";").append(CRLF);
    tab(w, indent).append("static public final String TEMPLATE_NAME = \"").append(model.getTemplateName())
            .append("\";").append(CRLF);
    tab(w, indent).append("static public final String TEMPLATE_PACKAGE_NAME = \"")
            .append(model.getPackageName()).append("\";").append(CRLF);
    tab(w, indent).append("static public final String HEADER_HASH = \"").append(model.createHeaderHash() + "")
            .append("\";").append(CRLF);

    // Don't include MODIFIED_AT header when optimized compiler is used since this implicitly disables hot reloading anyhow
    if (!model.getOptions().getOptimize()) {
        tab(w, indent).append("static public final long MODIFIED_AT = ").append(model.getModifiedAt() + "")
                .append("L;").append(CRLF);
    }

    tab(w, indent).append("static public final String[] ARGUMENT_NAMES = {");
    StringBuilder argNameList = new StringBuilder();
    for (Argument arg : model.getArgumentsWithoutRockerBody()) {
        if (argNameList.length() > 0) {
            argNameList.append(",");
        }
        argNameList.append(" \"").append(arg.getExternalName()).append("\"");
    }
    w.append(argNameList).append(" };").append(CRLF);

    // model arguments as members of model class
    appendArgumentMembers(model, w, "private", false, indent);

    // model setters & getters with builder-style pattern
    // special case for the RockerBody argument which sorta "hides" its getter/setter
    if (model.getArguments().size() > 0) {
        for (Argument arg : model.getArguments()) {
            // setter
            w.append(CRLF);
            tab(w, indent).append("public ").append(model.getName()).append(" ").append(arg.getExternalName())
                    .append("(" + arg.getExternalType()).append(" ").append(arg.getName()).append(") {")
                    .append(CRLF);
            tab(w, indent + 1).append("this.").append(arg.getName()).append(" = ").append(arg.getName())
                    .append(";").append(CRLF);
            tab(w, indent + 1).append("return this;").append(CRLF);
            tab(w, indent).append("}").append(CRLF);

            // getter
            w.append(CRLF);
            tab(w, indent).append("public ").append(arg.getExternalType()).append(" ")
                    .append(arg.getExternalName()).append("() {").append(CRLF);
            tab(w, indent + 1).append("return this.").append(arg.getName()).append(";").append(CRLF);
            tab(w, indent).append("}").append(CRLF);
        }
    }

    w.append(CRLF);

    //
    // model "template" static builder
    //
    tab(w, indent).append("static public ").append(model.getName()).append(" template(");

    if (model.getArguments().size() > 0) {
        int i = 0;
        // RockerBody is NOT included (it is passed via a closure block in other templates)
        // so we only care about the other arguments
        for (Argument arg : model.getArgumentsWithoutRockerBody()) {
            if (i != 0) {
                w.append(", ");
            }
            w.append(arg.getType()).append(" ").append(arg.getName());
            i++;
        }
    }
    w.append(") {").append(CRLF);

    tab(w, indent + 1).append("return new ").append(model.getName()).append("()");
    if (model.getArguments().size() > 0) {
        int i = 0;
        for (Argument arg : model.getArgumentsWithoutRockerBody()) {
            w.append(CRLF);
            tab(w, indent + 2).append(".").append(arg.getName()).append("(").append(arg.getName()).append(")");
            i++;
        }
    }
    w.append(";").append(CRLF);
    tab(w, indent).append("}").append(CRLF);

    //
    // render of model
    //
    w.append(CRLF);

    tab(w, indent).append("@Override").append(CRLF);
    tab(w, indent).append("protected DefaultRockerTemplate buildTemplate() throws RenderingException {")
            .append(CRLF);

    if (model.getOptions().getOptimize()) {
        // model "template" static builder (not reloading support, fastest performance)
        tab(w, indent + 1).append("// optimized for performance (via rocker.optimize flag; no auto reloading)")
                .append(CRLF);
        tab(w, indent + 1).append("return new Template(this);").append(CRLF);
        //tab(w, indent+1).append("return template.__render(context);").append(CRLF);
    } else {
        tab(w, indent + 1).append(
                "// optimized for convenience (runtime auto reloading enabled if rocker.reloading=true)")
                .append(CRLF);
        // use bootstrap to create underlying template
        tab(w, indent + 1).append("return ").append(RockerRuntime.class.getCanonicalName())
                .append(".getInstance().getBootstrap().template(this.getClass(), this);").append(CRLF);
        //tab(w, indent+1).append("return template.__render(context);").append(CRLF);
    }

    tab(w, indent).append("}").append(CRLF);

    //
    // TEMPLATE CLASS
    //

    w.append(CRLF);

    // class definition
    tab(w, indent).append("static public class Template extends ").append(model.getOptions().getExtendsClass());

    w.append(" {").append(CRLF);

    indent++;

    // plain text -> map of chunks of text (Java only supports 2-byte length of string constant)
    LinkedHashMap<String, LinkedHashMap<String, String>> plainTextMap = model
            .createPlainTextMap(PLAIN_TEXT_CHUNK_LENGTH);

    if (!plainTextMap.isEmpty()) {

        w.append(CRLF);

        for (String plainText : plainTextMap.keySet()) {

            // include static text as comments in source (limit to 500)
            tab(w, indent).append("// ")
                    .append(StringUtils.abbreviate(RockerUtil.ESCAPE_JAVA.translate(plainText), 500))
                    .append(CRLF);
            for (Map.Entry<String, String> chunk : plainTextMap.get(plainText).entrySet()) {

                if (this.plainTextStrategy == PlainTextStrategy.STATIC_STRINGS) {
                    tab(w, indent).append("static private final String ").append(chunk.getKey()).append(" = \"")
                            .append(StringEscapeUtils.escapeJava(chunk.getValue())).append("\";").append(CRLF);
                } else if (this.plainTextStrategy == PlainTextStrategy.STATIC_BYTE_ARRAYS_VIA_UNLOADED_CLASS) {
                    tab(w, indent).append("static private final byte[] ").append(chunk.getKey()).append(";")
                            .append(CRLF);
                }

            }
        }

        // generate the static initializer
        if (this.plainTextStrategy == PlainTextStrategy.STATIC_BYTE_ARRAYS_VIA_UNLOADED_CLASS) {

            w.append(CRLF);

            tab(w, indent).append("static {").append(CRLF);

            String loaderClassName = unqualifiedClassName(PlainTextUnloadedClassLoader.class);
            tab(w, indent + 1).append(loaderClassName).append(" loader = ").append(loaderClassName)
                    .append(".tryLoad(").append(model.getName()).append(".class.getClassLoader(), ")
                    .append(model.getName()).append(".class.getName()").append(" + \"$PlainText\", \"")
                    .append(model.getOptions().getTargetCharset()).append("\");").append(CRLF);

            for (String plainText : plainTextMap.keySet()) {

                for (Map.Entry<String, String> chunk : plainTextMap.get(plainText).entrySet()) {

                    if (this.plainTextStrategy == PlainTextStrategy.STATIC_BYTE_ARRAYS_VIA_UNLOADED_CLASS) {
                        tab(w, indent + 1).append(chunk.getKey()).append(" = loader.tryGet(\"")
                                .append(chunk.getKey()).append("\");").append(CRLF);
                    }

                }

            }

            tab(w, indent).append("}").append(CRLF);
        }

    }

    // arguments as members of template class
    appendArgumentMembers(model, w, "protected", true, indent);

    w.append(CRLF);

    // constructor
    tab(w, indent).append("public Template(").append(model.getName()).append(" model) {").append(CRLF);

    tab(w, indent + 1).append("super(model);").append(CRLF);
    tab(w, indent + 1).append("__internal.setCharset(\"").append(model.getOptions().getTargetCharset())
            .append("\");").append(CRLF);
    tab(w, indent + 1).append("__internal.setContentType(CONTENT_TYPE);").append(CRLF);
    tab(w, indent + 1).append("__internal.setTemplateName(TEMPLATE_NAME);").append(CRLF);
    tab(w, indent + 1).append("__internal.setTemplatePackageName(TEMPLATE_PACKAGE_NAME);").append(CRLF);

    // each model argument passed along as well
    for (Argument arg : model.getArguments()) {
        tab(w, indent + 1).append("this.").append(arg.getName()).append(" = model.")
                .append(arg.getExternalName()).append("();").append(CRLF);
    }

    tab(w, indent).append("}").append(CRLF);

    w.append(CRLF);

    tab(w, indent).append("@Override").append(CRLF);
    tab(w, indent).append("protected void __doRender() throws IOException, RenderingException {").append(CRLF);

    // build rendering code
    int depth = 1;
    Deque<String> blockEnd = new ArrayDeque<>();

    for (TemplateUnit unit : model.getUnits()) {
        if (unit instanceof Comment) {
            continue;
        }

        // something like
        // IfBeginBlock
        // __internal.aboutToExecutePosInSourceTemplate(5, 10);
        appendCommentAndSourcePositionUpdate(w, depth + indent, unit);

        if (unit instanceof PlainText) {
            PlainText plain = (PlainText) unit;

            LinkedHashMap<String, String> chunks = plainTextMap.get(plain.getText());

            for (String chunkName : chunks.keySet()) {

                tab(w, depth + indent).append("__internal.writeValue(").append(chunkName).append(");")
                        .append(CRLF);

            }

        } else if (unit instanceof ValueExpression) {
            ValueExpression value = (ValueExpression) unit;
            tab(w, depth + indent).append("__internal.renderValue(").append(value.getExpression()).append(", ")
                    .append("" + value.isNullSafe()).append(");").append(CRLF);
        } else if (unit instanceof NullTernaryExpression) {
            NullTernaryExpression nullTernary = (NullTernaryExpression) unit;
            tab(w, depth + indent).append("{").append(CRLF);
            tab(w, depth + indent + 1).append("final Object __v = ").append(nullTernary.getLeftExpression())
                    .append(";").append(CRLF);
            tab(w, depth + indent + 1).append("if (__v != null) { __internal.renderValue(__v, false); }")
                    .append(CRLF);
            if (nullTernary.getRightExpression() != null) {
                tab(w, depth + indent + 1).append("else {__internal.renderValue(")
                        .append(nullTernary.getRightExpression()).append(", true); }").append(CRLF);
            }
            tab(w, depth + indent).append("}").append(CRLF);
        } else if (unit instanceof ValueClosureBegin) {

            ValueClosureBegin closure = (ValueClosureBegin) unit;
            tab(w, depth + indent).append("__internal.renderValue(").append(closure.getExpression())
                    .append(".__body(");

            // Java 1.8+ use lambda
            if (isJava8Plus(model)) {
                w.append("() -> {").append(CRLF);

                depth++;

                blockEnd.push("}), false);");
            }
            // Java 1.7- uses anonymous inner class
            else {
                w.append("new ").append(unqualifiedClassName(RockerContent.class)).append("() {").append(CRLF);

                depth++;

                blockEnd.push("}), false);");

                tab(w, depth + indent).append("@Override").append(CRLF);

                tab(w, depth + indent).append("public void render() throws IOException, RenderingException {")
                        .append(CRLF);

                depth++;

                blockEnd.push("}");
            }
        } else if (unit instanceof ValueClosureEnd) {
            // Java 1.8+ use lambda
            if (isJava8Plus(model)) {
                depth--;

                tab(w, depth + indent).append(blockEnd.pop()).append(" // value closure end ")
                        .append(sourceRef(unit)).append(CRLF);
            }
            // Java 1.7- uses anonymous inner class
            else {
                depth--;

                tab(w, depth + indent).append(blockEnd.pop()).append(CRLF);

                depth--;

                tab(w, depth + indent).append(blockEnd.pop()).append(" // value closure end ")
                        .append(sourceRef(unit)).append(CRLF);
            }
        } else if (unit instanceof ContentClosureBegin) {

            ContentClosureBegin closure = (ContentClosureBegin) unit;
            tab(w, depth + indent).append("RockerContent ").append(closure.getIdentifier()).append(" = ");

            // Java 1.8+ use lambda
            if (isJava8Plus(model)) {
                w.append("() -> {").append(CRLF);

                depth++;

                blockEnd.push("};");
            }
            // Java 1.7- uses anonymous inner class
            else {
                w.append("new ").append(unqualifiedClassName(com.fizzed.rocker.RockerContent.class))
                        .append("() {").append(CRLF);

                depth++;

                blockEnd.push("};");

                tab(w, depth + indent).append("@Override").append(CRLF);

                tab(w, depth + indent).append("public void render() throws IOException, RenderingException {")
                        .append(CRLF);

                depth++;

                blockEnd.push("}");
            }
        } else if (unit instanceof ContentClosureEnd) {
            // Java 1.8+ use lambda
            if (isJava8Plus(model)) {
                depth--;

                tab(w, depth + indent).append(blockEnd.pop()).append(" // content closure end ")
                        .append(sourceRef(unit)).append(CRLF);
            }
            // Java 1.7- uses anonymous inner class
            else {
                depth--;

                tab(w, depth + indent).append(blockEnd.pop()).append(CRLF);

                depth--;

                tab(w, depth + indent).append(blockEnd.pop()).append(" // content closure end ")
                        .append(sourceRef(unit)).append(CRLF);
            }
        } else if (unit instanceof IfBlockBegin) {
            IfBlockBegin block = (IfBlockBegin) unit;

            tab(w, depth + indent).append("if ").append(block.getExpression()).append(" {").append(CRLF);

            blockEnd.push("}");
            depth++;
        } else if (unit instanceof IfBlockElseIf) {
            final IfBlockElseIf block = (IfBlockElseIf) unit;

            depth--;

            // This keeps else-if nicely formatted in generated code.
            tab(w, depth + indent).append("} else if ").append(block.getExpression()).append(" {").append(CRLF);

            depth++;
        } else if (unit instanceof IfBlockElse) {
            depth--;

            tab(w, depth + indent).append("} else {").append(" // else ").append(sourceRef(unit)).append(CRLF);

            depth++;
        } else if (unit instanceof IfBlockEnd) {
            depth--;

            tab(w, depth + indent).append(blockEnd.pop()).append(" // if end ").append(sourceRef(unit))
                    .append(CRLF);

        } else if (unit instanceof WithBlockBegin) {
            WithBlockBegin block = (WithBlockBegin) unit;
            WithStatement stmt = block.getStatement();

            String statementConsumerName = withStatementConsumerGenerator.register(stmt);

            final List<WithStatement.VariableWithExpression> variables = stmt.getVariables();

            if (isJava8Plus(model)) {
                tab(w, depth + indent)
                        .append(variables.size() == 1 ? qualifiedClassName(WithBlock.class)
                                : WithStatementConsumerGenerator.WITH_BLOCKS_GENERATED_CLASS_NAME)
                        .append(".with(");
                // All expressions
                for (int i = 0; i < variables.size(); i++) {
                    final WithStatement.VariableWithExpression var = variables.get(i);
                    if (i > 0) {
                        w.append(", ");
                    }
                    w.append(var.getValueExpression());
                }
                w.append(", ").append(stmt.isNullSafe() + "").append(", (");
                for (int i = 0; i < variables.size(); i++) {
                    final WithStatement.VariableWithExpression var = variables.get(i);
                    if (i > 0) {
                        w.append(", ");
                    }
                    w.append(var.getVariable().getName());
                }
                w.append(") -> {").append(CRLF);

                depth++;

                blockEnd.push("});");

            } else {
                tab(w, depth + indent)
                        // Note for standard 1 variable with block we use the predefined consumers.
                        // Otherwise we fallback to the generated ones.
                        .append(variables.size() == 1 ? qualifiedClassName(WithBlock.class)
                                : WithStatementConsumerGenerator.WITH_BLOCKS_GENERATED_CLASS_NAME)
                        .append(".with(");

                // All expressions
                for (int i = 0; i < variables.size(); i++) {
                    final WithStatement.VariableWithExpression var = variables.get(i);
                    if (i > 0) {
                        w.append(", ");
                    }
                    w.append(var.getValueExpression());
                }
                w.append(", ").append(stmt.isNullSafe() + "").append(", (new ").append(statementConsumerName)
                        .append('<');

                // Types for the .with(..)
                for (int i = 0; i < variables.size(); i++) {
                    final JavaVariable variable = variables.get(i).getVariable();
                    if (i > 0) {
                        w.append(", ");
                    }
                    w.append(variable.getType());
                }
                w.append(">() {").append(CRLF);
                tab(w, depth + indent + 1).append("@Override public void accept(");
                for (int i = 0; i < variables.size(); i++) {
                    final JavaVariable variable = variables.get(i).getVariable();
                    if (i > 0) {
                        w.append(", ");
                    }
                    w.append("final ").append(variable.toString());
                }
                w.append(") throws IOException {").append(CRLF);

                depth++;

                blockEnd.push("}}));");
            }
        } else if (unit instanceof WithBlockElse) {
            depth--;

            if (isJava8Plus(model)) {
                tab(w, depth + indent).append("}, () -> {").append(CRLF);
            } else {
                tab(w, depth + indent).append("}}), (new ")
                        .append(qualifiedClassName(WithBlock.Consumer0.class)).append("() { ")
                        .append("@Override public void accept() throws IOException {").append(CRLF);
            }
            depth++;
        } else if (unit instanceof WithBlockEnd) {
            depth--;

            tab(w, depth + indent).append(blockEnd.pop()).append(" // with end ").append(sourceRef(unit))
                    .append(CRLF);
        } else if (unit instanceof ForBlockBegin) {
            ForBlockBegin block = (ForBlockBegin) unit;
            ForStatement stmt = block.getStatement();

            // break support via try and catch mechanism (works across lambdas!)
            tab(w, depth + indent).append("try {").append(CRLF);

            depth++;

            if (stmt.getForm() == ForStatement.Form.GENERAL) {
                // print out raw statement including parentheses
                tab(w, depth + indent).append("for ").append(block.getExpression()).append(" {").append(CRLF);

                blockEnd.push("}");
            } else if (stmt.getForm() == ForStatement.Form.ENHANCED) {
                // Java 1.8+ (use lambdas)
                if (stmt.hasAnyUntypedArguments() && isJava8Plus(model)) {

                    // build list of lambda vars
                    String localVars = "";
                    for (JavaVariable arg : stmt.getArguments()) {
                        if (localVars.length() != 0) {
                            localVars += ",";
                        }
                        localVars += arg.getName();
                    }

                    tab(w, depth + indent).append(Java8Iterator.class.getName()).append(".forEach(")
                            .append(stmt.getValueExpression()).append(", (").append(localVars).append(") -> {")
                            .append(CRLF);

                    blockEnd.push("});");
                } else {

                    // is the first argument a "ForIterator" ?
                    boolean forIterator = isForIteratorType(stmt.getArguments().get(0).getType());
                    int collectionCount = (forIterator ? 2 : 1);
                    int mapCount = (forIterator ? 3 : 2);

                    // type and value we are going to iterate thru
                    String iterateeType = null;
                    String valueExpression = null;
                    if (stmt.getArguments().size() == collectionCount) {
                        iterateeType = stmt.getArguments().get(collectionCount - 1).getTypeAsNonPrimitiveType();
                        valueExpression = stmt.getValueExpression();
                    } else if (stmt.getArguments().size() == mapCount) {
                        iterateeType = "java.util.Map.Entry<"
                                + stmt.getArguments().get(mapCount - 2).getTypeAsNonPrimitiveType() + ","
                                + stmt.getArguments().get(mapCount - 1).getTypeAsNonPrimitiveType() + ">";
                        valueExpression = stmt.getValueExpression() + ".entrySet()";
                    }

                    // create unique variable name for iterator
                    String forIteratorVarName = "__forIterator" + (++varCounter);

                    // ForIterator for collection and make it final to assure nested anonymous
                    // blocks can access it as well.
                    tab(w, depth + indent).append("final ")
                            .append(com.fizzed.rocker.runtime.CollectionForIterator.class.getName()).append("<")
                            .append(iterateeType).append(">").append(" ").append(forIteratorVarName)
                            .append(" = new ")
                            .append(com.fizzed.rocker.runtime.CollectionForIterator.class.getName()).append("<")
                            .append(iterateeType).append(">").append("(").append(valueExpression).append(");")
                            .append(CRLF);

                    // for loop same regardless of map vs. collection
                    tab(w, depth + indent).append("while (").append(forIteratorVarName).append(".hasNext()) {")
                            .append(CRLF);

                    // if forIterator request assign to local var and make it final to assure nested anonymous
                    // blocks can access it as well.
                    if (forIterator) {
                        tab(w, depth + indent + 1).append("final ")
                                .append(com.fizzed.rocker.ForIterator.class.getName()).append(" ")
                                .append(stmt.getArguments().get(0).getName()).append(" = ")
                                .append(forIteratorVarName).append(";").append(CRLF);
                    }

                    if (stmt.getArguments().size() == collectionCount) {
                        // assign item to local var and make it final to assure nested anonymous
                        // blocks can access it as well.
                        tab(w, depth + indent + 1).append("final ")
                                .append(stmt.getArguments().get(collectionCount - 1).toString()).append(" = ")
                                .append(forIteratorVarName).append(".next();").append(CRLF);
                    } else if (stmt.getArguments().size() == mapCount) {
                        // create unique variable name for iterator
                        String entryVarName = "__entry" + (++varCounter);

                        // assign map entry to local var
                        tab(w, depth + indent + 1).append("final ").append(iterateeType).append(" ")
                                .append(entryVarName).append(" = ").append(forIteratorVarName)
                                .append(".next();").append(CRLF);

                        // assign entry to local values  make it final to assure nested anonymous
                        // blocks can access it as well.
                        tab(w, depth + indent + 1).append("final ")
                                .append(stmt.getArguments().get(mapCount - 2).toString()).append(" = ")
                                .append(entryVarName).append(".getKey();").append(CRLF);

                        tab(w, depth + indent + 1).append("final ")
                                .append(stmt.getArguments().get(mapCount - 1).toString()).append(" = ")
                                .append(entryVarName).append(".getValue();").append(CRLF);
                    } else {
                        throw new GeneratorException("Unsupported number of arguments for for loop");
                    }

                    blockEnd.push("}");
                }
            }

            depth++;

            // continue support via try and catch mechanism (works across lambdas!)
            tab(w, depth + indent).append("try {").append(CRLF);

            depth++;

        } else if (unit instanceof ForBlockEnd) {
            depth--;

            // continue support via try and catch mechanism (works across lambdas!)
            tab(w, depth + indent).append("} catch (").append(ContinueException.class.getCanonicalName())
                    .append(" e) {").append(CRLF);

            tab(w, depth + indent + 1).append("// support for continuing for loops").append(CRLF);

            tab(w, depth + indent).append("}").append(CRLF);

            depth--;

            tab(w, depth + indent).append(blockEnd.pop()).append(" // for end ").append(sourceRef(unit))
                    .append(CRLF);

            depth--;

            // break support via try and catch mechanism (works across lambdas!)
            tab(w, depth + indent).append("} catch (").append(BreakException.class.getCanonicalName())
                    .append(" e) {").append(CRLF);

            tab(w, depth + indent + 1).append("// support for breaking for loops").append(CRLF);

            tab(w, depth + indent).append("}").append(CRLF);
        } else if (unit instanceof BreakStatement) {
            tab(w, depth + indent).append("__internal.throwBreakException();").append(CRLF);
        } else if (unit instanceof ContinueStatement) {
            tab(w, depth + indent).append("__internal.throwContinueException();").append(CRLF);
        }
        //log.info(" src (@ {}): [{}]", unit.getSourceRef(), unit.getSourceRef().getConsoleFriendlyText());
    }

    // end of render()
    tab(w, indent).append("}").append(CRLF);

    indent--;

    // end of template class
    tab(w, indent).append("}").append(CRLF);

    // Generate class with all gathered consumer interfaces for all withblocks
    withStatementConsumerGenerator.generate(this, w);

    if (this.plainTextStrategy == PlainTextStrategy.STATIC_BYTE_ARRAYS_VIA_UNLOADED_CLASS
            && !plainTextMap.isEmpty()) {

        w.append(CRLF);

        tab(w, indent).append("private static class PlainText {").append(CRLF);
        w.append(CRLF);

        for (String plainText : plainTextMap.keySet()) {

            for (Map.Entry<String, String> chunk : plainTextMap.get(plainText).entrySet()) {

                tab(w, indent + 1).append("static private final String ").append(chunk.getKey()).append(" = \"")
                        .append(StringEscapeUtils.escapeJava(chunk.getValue())).append("\";").append(CRLF);

            }

        }

        w.append(CRLF);
        tab(w, indent).append("}").append(CRLF);
    }

    w.append(CRLF);
    w.append("}").append(CRLF);
}

From source file:io.bibleget.HTTPCaller.java

/**
 *
 * @param myQuery// w  w w.  j a  v a2s . 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;
}

From source file:com.tremolosecurity.proxy.auth.PasswordReset.java

@Override
public void init(ServletContext ctx, HashMap<String, Attribute> init) {
    this.cfgMgr = (ConfigManager) ctx.getAttribute(ProxyConstants.TREMOLO_CONFIG);

    this.enabled = Boolean.parseBoolean(init.get("enabled").getValues().get(0));

    if (this.enabled) {

        this.msgQ = new ArrayDeque<SmtpMessage>();

        StopableThread st = new SendMessageThread(this);
        Thread t = new Thread(st);
        t.start();// www . j a  va  2  s  .co  m
        this.cfgMgr.addThread(st);

        String driver = init.get("driver").getValues().get(0);
        logger.info("Driver : '" + driver + "'");

        String url = init.get("url").getValues().get(0);
        ;
        logger.info("URL : " + url);
        String user = init.get("user").getValues().get(0);
        ;
        logger.info("User : " + user);
        String pwd = init.get("password").getValues().get(0);
        ;
        logger.info("Password : **********");

        int maxCons = Integer.parseInt(init.get("maxCons").getValues().get(0));
        logger.info("Max Cons : " + maxCons);
        int maxIdleCons = Integer.parseInt(init.get("maxIdleCons").getValues().get(0));
        logger.info("maxIdleCons : " + maxIdleCons);

        String dialect = init.get("dialect").getValues().get(0);
        logger.info("Hibernate Dialect : '" + dialect + "'");

        String validationQuery = init.get("validationQuery").getValues().get(0);
        logger.info("Validation Query : '" + validationQuery + "'");

        this.initializeHibernate(driver, user, pwd, url, dialect, maxCons, maxIdleCons, validationQuery);

        this.passwordResetURL = init.get("passwordResetURI").getValues().get(0);
        this.minValidKey = Integer.parseInt(init.get("minValidKey").getValues().get(0));

        StopableThread tokenClean = new TokenCleanup(this.sessionFactory, this.minValidKey);
        t = new Thread(tokenClean);

        this.cfgMgr.addThread(tokenClean);
        t.start();

        this.smtpServer = init.get("smtpHost").getValues().get(0);
        logger.info("SMTP Server : '" + this.smtpServer + "'");
        this.smtpPort = Integer.parseInt(init.get("smtpPort").getValues().get(0));
        logger.info("SMTP Port : '" + this.smtpPort + "'");
        this.smtpUser = init.get("smtpUser").getValues().get(0);
        logger.info("SMTP User : '" + this.smtpUser + "'");
        this.smtpPassword = init.get("smtpPassword").getValues().get(0);
        logger.info("SMTP Password : '************'");
        this.smtpSubject = init.get("smtpSubject").getValues().get(0);
        logger.info("SMTP Subject : '" + this.smtpSubject + "'");
        this.smtpMsg = init.get("smtpMsg").getValues().get(0);

        this.smtpFrom = init.get("smtpFrom").getValues().get(0);
        logger.info("SMTP From : '" + this.smtpFrom + "'");
        this.smtpTLS = Boolean.parseBoolean(init.get("smtpTLS").getValues().get(0));
        logger.info("SMTP TLS : '" + this.smtpTLS + "'");
        if (init.get("smtpSocksHost") != null && init.get("smtpSocksHost").getValues().size() > 0
                && !init.get("smtpSocksHost").getValues().get(0).isEmpty()) {
            logger.info("SMTP SOCKS : 'true'");
            this.useSocks = true;
            this.socksHost = init.get("smtpSocksHost").getValues().get(0);
            logger.info("SMTP SOCKS Host : '" + this.socksHost + "'");
            this.socksPort = Integer.parseInt(init.get("smtpSocksPort").getValues().get(0));
            logger.info("SMTP SOCKS Port : '" + this.socksPort + "'");
        } else {
            logger.info("SMTP SOCKS : 'false'");
            this.useSocks = false;
        }

        if (init.get("smtpLocalhost") != null && init.get("smtpLocalhost").getValues().size() > 0) {
            this.smtpLocalhost = init.get("smtpLocalhost").getValues().get(0);
            logger.info("SMTP Localhost : '" + this.smtpLocalhost + "'");
        } else {
            this.smtpLocalhost = null;
        }

    }

}

From source file:org.voltdb.iv2.Cartographer.java

private boolean doPartitionsHaveReplicas(int hid) {
    hostLog.debug("Cartographer: Reloading partition information.");
    List<String> partitionDirs = null;
    try {/*from  w w w  . j av a2s .  c  o  m*/
        partitionDirs = m_zk.getChildren(VoltZK.leaders_initiators, null);
    } catch (KeeperException | InterruptedException e) {
        return false;
    }

    //Don't fetch the values serially do it asynchronously
    Queue<ZKUtil.ByteArrayCallback> dataCallbacks = new ArrayDeque<>();
    Queue<ZKUtil.ChildrenCallback> childrenCallbacks = new ArrayDeque<>();
    for (String partitionDir : partitionDirs) {
        String dir = ZKUtil.joinZKPath(VoltZK.leaders_initiators, partitionDir);
        try {
            ZKUtil.ByteArrayCallback callback = new ZKUtil.ByteArrayCallback();
            m_zk.getData(dir, false, callback, null);
            dataCallbacks.offer(callback);
            ZKUtil.ChildrenCallback childrenCallback = new ZKUtil.ChildrenCallback();
            m_zk.getChildren(dir, false, childrenCallback, null);
            childrenCallbacks.offer(childrenCallback);
        } catch (Exception e) {
            return false;
        }
    }
    //Assume that we are ksafe
    for (String partitionDir : partitionDirs) {
        int pid = LeaderElector.getPartitionFromElectionDir(partitionDir);
        try {
            //Dont let anyone die if someone is in INITIALIZING state
            byte[] partitionState = dataCallbacks.poll().getData();
            if (partitionState != null && partitionState.length == 1) {
                if (partitionState[0] == LeaderElector.INITIALIZING) {
                    return false;
                }
            }

            List<String> replicas = childrenCallbacks.poll().getChildren();
            //This is here just so callback is polled.
            if (pid == MpInitiator.MP_INIT_PID) {
                continue;
            }
            //Get Hosts for replicas
            final List<Integer> replicaHost = new ArrayList<>();
            boolean hostHasReplicas = false;
            for (String replica : replicas) {
                final String split[] = replica.split("/");
                final long hsId = Long.valueOf(split[split.length - 1].split("_")[0]);
                final int hostId = CoreUtils.getHostIdFromHSId(hsId);
                if (hostId == hid) {
                    hostHasReplicas = true;
                }
                replicaHost.add(hostId);
            }
            hostLog.debug("Replica Host for Partition " + pid + " " + replicaHost);
            if (hostHasReplicas && replicaHost.size() <= 1) {
                return false;
            }
        } catch (InterruptedException | KeeperException | NumberFormatException e) {
            return false;
        }
    }
    return true;
}