Example usage for org.apache.commons.lang3 StringUtils strip

List of usage examples for org.apache.commons.lang3 StringUtils strip

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils strip.

Prototype

public static String strip(String str, final String stripChars) 

Source Link

Document

Strips any of a set of characters from the start and end of a String.

Usage

From source file:com.thoughtworks.go.domain.materials.svn.SvnExternalParser.java

private String relativeRoot(String absoluteRoot, String repoUrl) {
    return StringUtils.strip(StringUtils.remove(absoluteRoot, repoUrl), "/");
}

From source file:io.github.robwin.swagger2markup.builder.document.MarkupDocument.java

/**
 * Create a normalized filename/*w w w  .  j ava 2s.co m*/
 * @param name current name of the file
 * @return a normalized filename
 */
protected String normalizeFileName(String name) {
    String fileName = FILENAME_FORBIDDEN_PATTERN.matcher(name).replaceAll("_");
    fileName = fileName.replaceAll(String.format("([%1$s])([%1$s]+)", "-_"), "$1");
    fileName = StringUtils.strip(fileName, "_-");
    fileName = fileName.trim().toLowerCase();
    return fileName;
}

From source file:io.hawkcd.agent.services.FileManagementService.java

@Override
public String getPattern(String rootPath, String path) {

    String pattern = path.replace(rootPath, "");

    if (pattern.isEmpty() || pattern.equals("/") || pattern.equals("\\")) {
        pattern = "**";
    }//from  w  ww  .  jav a2  s.  com

    pattern = this.normalizePath(pattern);

    return StringUtils.strip(pattern, "/");
}

From source file:com.ibasco.agql.protocols.valve.source.query.handlers.SourceRconPacketAssembler.java

private SourceRconAuthResponsePacket processAuthResponsePacket(SourceRconResponsePacket msg) {
    int requestId = msg.getId();

    //We received a new auth cmd response, so create a new SourceRconAuthResponsePacket and merge with it
    if ((msg instanceof SourceRconCmdResponsePacket) && !this.packetContainer.containsKey(requestId)) {
        if (!SourceRconUtil.isValidRequestId(requestId))
            throw new IllegalStateException(
                    String.format("Expecting a valid request id. Received : %d", requestId));

        //Create a new auth response container
        SourceRconAuthResponsePacket authPacket = new SourceRconAuthResponsePacket();
        authPacket.setId(requestId);//  w w  w  .  ja v  a 2 s.com
        authPacket.setBody(StringUtils.strip(msg.getBody(), "\r\n "));

        //Place it into the multimap container
        this.packetContainer.put(requestId, authPacket);

        //Store the request id to lastAuthRequestId. If the authentication fails,
        // we will only receive a request id value of -1 from the auth response packet.
        this.lastAuthRequestId = requestId;
        log.debug("Saving the auth request id : {}", lastAuthRequestId);
    } else {
        log.debug("Received AUTH response packet. Current Request Id = {}, Last Request Id = {}", requestId,
                lastAuthRequestId);
        if (lastAuthRequestId == null && msg instanceof SourceRconAuthResponsePacket) {
            //some games only respond with the AUTH packet, immediately return for processing.

            //if id is -1, look for the latest entry in the map
            if (msg.getId() == -1) {
                Integer id = findLatestAuthId();
                log.debug("Updating id from -1 to '{}'", id);
                msg.setId(id != null ? id : -1);
                ((SourceRconAuthResponsePacket) msg).setSuccess(false);
            } else {
                ((SourceRconAuthResponsePacket) msg).setSuccess(true);
            }

            log.debug("Returning authentication packet response for processing");
            return (SourceRconAuthResponsePacket) msg;
        } else if (lastAuthRequestId != null && SourceRconUtil.isValidRequestId(lastAuthRequestId)) {
            List<SourceRconResponsePacket> authPacketContainer = this.packetContainer.get(lastAuthRequestId);
            Iterator<SourceRconResponsePacket> it = authPacketContainer.iterator();
            try {
                //Update the auth response instance with the actual request id
                SourceRconAuthResponsePacket authResponsePacket = (SourceRconAuthResponsePacket) it.next();
                if (!SourceRconUtil.isValidRequestId(requestId)) {
                    log.debug("Updating request id to : {}", lastAuthRequestId);
                    authResponsePacket.setId(lastAuthRequestId); //update the request id
                }
                authResponsePacket.setSuccess(requestId != -1);
                return authResponsePacket;
            } finally {
                //send to the next handler
                it.remove(); //remove from the container
                lastAuthRequestId = null; //reset id
            }
        } else
            throw new InvalidRconRequestIdException(
                    "Unable to retrieve the authentication request id. Expected a valid request id but received: "
                            + lastAuthRequestId);
    }
    return null;
}

From source file:gov.nih.nci.caintegrator.external.biodbnet.BioDbNetSearchImpl.java

/**
 * {@inheritDoc}//from  www.j  a  v a  2  s.c  om
 */
@Override
public Set<PathwayResults> retrievePathwaysByGeneSymbols(SearchParameters params) {
    Db2DbParams db2dbParams = new Db2DbParams();
    db2dbParams.setInput("Gene Symbol");
    db2dbParams.setOutputs("Biocarta Pathway Name");
    db2dbParams.setTaxonId(params.getTaxon().getTaxonId());
    db2dbParams.setInputValues(params.getInputValues());

    Set<PathwayResults> pathways = Sets.newTreeSet();
    String results = bioDbNetRemoteService.db2db(db2dbParams);
    CSVReader reader = new CSVReader(new StringReader(results), '\t', '\'', 1);
    try {
        List<String[]> lines = reader.readAll();
        for (String[] nextLine : lines) {
            if (!StringUtils.equals(nextLine[PATHWAY_INFO_INDEX], EMPTY_VALUE)) {
                String pathwayLine = StringUtils.strip(nextLine[PATHWAY_INFO_INDEX], "\"");
                pathways.addAll(extractPathways(StringUtils.split(pathwayLine, ';')));
            }
        }
    } catch (IOException e) {
        LOG.error("Unabled to read dbBioNet pathway by gene results.", e);
    } finally {
        IOUtils.closeQuietly(reader);
    }
    return pathways;
}

From source file:io.scigraph.vocabulary.VocabularyNeo4jImpl.java

@Override
public Optional<Concept> getConceptFromId(Query query) {
    String idQuery = StringUtils.strip(query.getInput(), "\"");
    idQuery = curieUtil.getIri(idQuery).or(idQuery);
    try (Transaction tx = graph.beginTx()) {
        Node node = graph.index().getNodeAutoIndexer().getAutoIndex().get(CommonProperties.IRI, idQuery)
                .getSingle();//w  w  w  .  j a  va 2 s .  co  m
        tx.success();
        Concept concept = null;
        if (null != node) {
            concept = transformer.apply(node);
        }
        return Optional.fromNullable(concept);
    }
}

From source file:com.google.dart.java2dart.processor.ObjectSemanticProcessor.java

@Override
public void process(CompilationUnit unit) {
    unit.accept(new GeneralizingASTVisitor<Void>() {
        @Override/* w  w  w .j a  v a  2  s  .co m*/
        public Void visitAssignmentExpression(AssignmentExpression node) {
            super.visitAssignmentExpression(node);
            if (node.getOperator().getType() == TokenType.EQ) {
                Expression leftExpr = node.getLeftHandSide();
                Expression rightExpr = node.getRightHandSide();
                ITypeBinding leftBinding = context.getNodeTypeBinding(leftExpr);
                ITypeBinding rightBinding = context.getNodeTypeBinding(rightExpr);
                if (JavaUtils.isTypeNamed(leftBinding, "java.lang.CharSequence")
                        && JavaUtils.isTypeNamed(rightBinding, "java.lang.String")) {
                    node.setRightHandSide(
                            instanceCreationExpression(Keyword.NEW, typeName("CharSequence"), rightExpr));
                    return null;
                }
            }
            return null;
        }

        @Override
        public Void visitBinaryExpression(BinaryExpression node) {
            if (node.getOperator().getType() == TokenType.PLUS) {
                List<Expression> expressions = gatherBinaryExpressions(node);
                if (hasStringObjects(context, expressions)) {
                    // try to rewrite each expression
                    for (Expression expression : expressions) {
                        expression.accept(this);
                    }
                    expressions = gatherBinaryExpressions(node);
                    // compose interpolation using expressions
                    List<InterpolationElement> elements = Lists.newArrayList();
                    elements.add(interpolationString("\"", ""));
                    for (Expression expression : expressions) {
                        if (expression instanceof SimpleStringLiteral) {
                            SimpleStringLiteral literal = (SimpleStringLiteral) expression;
                            String value = literal.getValue();
                            String lexeme = StringUtils.strip(literal.getLiteral().getLexeme(), "\"");
                            elements.add(interpolationString(lexeme, value));
                        } else if (expression instanceof IntegerLiteral
                                && JavaUtils.isTypeNamed(context.getNodeTypeBinding(expression), "char")) {
                            String value = "" + (char) ((IntegerLiteral) expression).getValue().intValue();
                            elements.add(interpolationString(value, value));
                        } else {
                            elements.add(interpolationExpression(expression));
                        }
                    }
                    elements.add(interpolationString("\"", ""));
                    StringInterpolation interpolation = string(elements);
                    replaceNode(node, interpolation);
                    return null;
                }
            }
            // super
            super.visitBinaryExpression(node);
            // in Java "true | false" will compute both operands
            if (node.getOperator().getType() == TokenType.BAR) {
                Expression leftOperand = node.getLeftOperand();
                ITypeBinding argTypeBinding = context.getNodeTypeBinding(leftOperand);
                if (JavaUtils.isTypeNamed(argTypeBinding, "boolean")) {
                    replaceNode(node, methodInvocation("javaBooleanOr", leftOperand, node.getRightOperand()));
                    return null;
                }
            }
            // done
            return null;
        }

        @Override
        public Void visitInstanceCreationExpression(InstanceCreationExpression node) {
            super.visitInstanceCreationExpression(node);
            ITypeBinding typeBinding = context.getNodeTypeBinding(node);
            List<Expression> args = node.getArgumentList().getArguments();
            String typeSimpleName = node.getConstructorName().getType().getName().getName();
            if (JavaUtils.isTypeNamed(typeBinding, "java.lang.StringBuilder")) {
                args.clear();
                return null;
            }
            if (typeSimpleName.equals("int")) {
                if (args.size() == 1) {
                    replaceNode(node, methodInvocation(identifier("int"), "parse", args.get(0)));
                } else {
                    replaceNode(node, methodInvocation(identifier("int"), "parse", args.get(0),
                            namedExpression("radix", args.get(1))));
                }
            }
            return null;
        }

        @Override
        public Void visitMethodDeclaration(MethodDeclaration node) {
            if (node.getName() instanceof SimpleIdentifier) {
                String name = node.getName().getName();
                if (name.equals("hashCode")) {
                    node.setOperatorKeyword(token(Keyword.GET));
                    node.setParameters(null);
                }
                if (name.equals("equals") && node.getParameters().getParameters().size() == 1) {
                    node.setOperatorKeyword(token(Keyword.OPERATOR));
                    node.setName(identifier("=="));
                }
            }
            return super.visitMethodDeclaration(node);
        }

        @Override
        public Void visitMethodInvocation(MethodInvocation node) {
            super.visitMethodInvocation(node);
            SimpleIdentifier nameNode = node.getMethodName();
            String name = nameNode.getName();
            NodeList<Expression> args = node.getArgumentList().getArguments();
            // System -> JavaSystem
            if (node.getTarget() instanceof SimpleIdentifier) {
                SimpleIdentifier targetIdentifier = (SimpleIdentifier) node.getTarget();
                if (targetIdentifier.getName().equals("System")) {
                    targetIdentifier.setToken(token("JavaSystem"));
                }
                if (isMethodInClass(node, "getProperty", "java.lang.System")
                        || isMethodInClass(node, "getenv", "java.lang.System")) {
                    targetIdentifier.setToken(token("JavaSystemIO"));
                }
            }
            //
            if (args.isEmpty()) {
                if ("hashCode".equals(name) || isMethodInClass(node, "length", "java.lang.String")
                        || isMethodInClass(node, "isEmpty", "java.lang.String")
                        || isMethodInClass(node, "ordinal", "java.lang.Enum")
                        || isMethodInClass(node, "values", "java.lang.Enum")) {
                    replaceNode(node, propertyAccess(node.getTarget(), nameNode));
                    return null;
                }
                if ("getClass".equals(name)) {
                    replaceNode(node, propertyAccess(node.getTarget(), "runtimeType"));
                    return null;
                }
                if (isMethodInClass(node, "getName", "java.lang.Class")
                        || isMethodInClass(node, "getSimpleName", "java.lang.Class")) {
                    nameNode.setToken(token("toString"));
                    return null;
                }
            }
            if (name.equals("equals") && args.size() == 1) {
                ASTNode parent = node.getParent();
                if (parent instanceof PrefixExpression
                        && ((PrefixExpression) parent).getOperator().getType() == TokenType.BANG) {
                    replaceNode(parent, binaryExpression(node.getTarget(), TokenType.BANG_EQ, args.get(0)));
                } else {
                    replaceNode(node, binaryExpression(node.getTarget(), TokenType.EQ_EQ, args.get(0)));
                }
                return null;
            }
            if (isMethodInClass(node, "printStackTrace", "java.lang.Throwable")) {
                replaceNode(node, methodInvocation("print", node.getTarget()));
                return null;
            }
            if (isMethodInClass(node, "isInstance", "java.lang.Class")) {
                replaceNode(node, methodInvocation("isInstanceOf", args.get(0), node.getTarget()));
                return null;
            }
            if (isMethodInClass(node, "charAt", "java.lang.String")) {
                nameNode.setToken(token("codeUnitAt"));
                return null;
            }
            if (isMethodInClass(node, "replace", "java.lang.String")) {
                nameNode.setToken(token("replaceAll"));
                return null;
            }
            if (isMethodInClass(node, "equalsIgnoreCase", "java.lang.String")) {
                replaceNode(node,
                        methodInvocation("javaStringEqualsIgnoreCase", node.getTarget(), args.get(0)));
                return null;
            }
            if (isMethodInClass(node, "indexOf", "java.lang.String")) {
                IMethodBinding binding = (IMethodBinding) context.getNodeBinding(node);
                if (binding != null && binding.getParameterTypes().length >= 1
                        && binding.getParameterTypes()[0].getName().equals("int")) {
                    char c = (char) ((IntegerLiteral) args.get(0)).getValue().intValue();
                    replaceNode(args.get(0), string("" + c));
                }
                return null;
            }
            if (isMethodInClass(node, "print", "java.io.PrintWriter")) {
                IMethodBinding binding = (IMethodBinding) context.getNodeBinding(node);
                if (binding != null && binding.getParameterTypes().length >= 1
                        && binding.getParameterTypes()[0].getName().equals("char")) {
                    char c = (char) ((IntegerLiteral) args.get(0)).getValue().intValue();
                    replaceNode(args.get(0), string("" + c));
                }
                return null;
            }
            if (isMethodInClass2(node, "println()", "java.io.PrintWriter")) {
                nameNode.setToken(token("newLine"));
                return null;
            }
            if (isMethodInClass2(node, "println(java.lang.String)", "java.io.PrintWriter")) {
                nameNode.setToken(token("println"));
                return null;
            }
            if (isMethodInClass2(node, "startsWith(java.lang.String,int)", "java.lang.String")) {
                replaceNode(node, methodInvocation(identifier("JavaString"), "startsWithBefore",
                        node.getTarget(), args.get(0), args.get(1)));
                return null;
            }
            if (isMethodInClass(node, "format", "java.lang.String")) {
                replaceNode(node.getTarget(), identifier("JavaString"));
                return null;
            }
            if (name.equals("longValue") && node.getTarget() instanceof MethodInvocation) {
                MethodInvocation node2 = (MethodInvocation) node.getTarget();
                if (isMethodInClass(node2, "floor", "java.lang.Math")) {
                    NodeList<Expression> args2 = node2.getArgumentList().getArguments();
                    if (args2.size() == 1 && args2.get(0) instanceof BinaryExpression) {
                        BinaryExpression binary = (BinaryExpression) args2.get(0);
                        if (binary.getOperator().getType() == TokenType.SLASH) {
                            replaceNode(node, binaryExpression(binary.getLeftOperand(), TokenType.TILDE_SLASH,
                                    binary.getRightOperand()));
                            return null;
                        }
                    }
                }
            }
            if (isMethodInClass(node, "valueOf", "java.lang.Integer")
                    || isMethodInClass(node, "valueOf", "java.lang.Long")
                    || isMethodInClass(node, "valueOf", "java.lang.Double")
                    || isMethodInClass(node, "valueOf", "java.math.BigInteger")) {
                replaceNode(node, args.get(0));
                return null;
            }
            if (isMethodInClass(node, "parseInt", "java.lang.Integer")) {
                node.setTarget(identifier("int"));
                nameNode.setToken(token("parse"));
                if (args.size() == 2) {
                    args.set(1, namedExpression("radix", args.get(1)));
                }
                return null;
            }
            if (isMethodInClass(node, "parseDouble", "java.lang.Double")) {
                node.setTarget(identifier("double"));
                nameNode.setToken(token("parse"));
                return null;
            }
            if (isMethodInClass2(node, "toString(double)", "java.lang.Double")
                    || isMethodInClass2(node, "toString(int)", "java.lang.Integer")
                    || isMethodInClass2(node, "toString(long)", "java.lang.Long")) {
                replaceNode(node, methodInvocation(args.get(0), "toString"));
                return null;
            }
            if (isMethodInClass(node, "booleanValue", "java.lang.Boolean")
                    || isMethodInClass(node, "doubleValue", "java.lang.Double")
                    || isMethodInClass(node, "intValue", "java.lang.Integer")
                    || isMethodInClass(node, "longValue", "java.lang.Long")
                    || isMethodInClass(node, "intValue", "java.math.BigInteger")) {
                replaceNode(node, node.getTarget());
                return null;
            }
            if (isMethodInClass(node, "doubleValue", "java.math.BigInteger")) {
                nameNode.setToken(token("toDouble"));
                return null;
            }
            {
                TokenType tokenType = null;
                if (isMethodInClass(node, "and", "java.math.BigInteger")) {
                    tokenType = TokenType.AMPERSAND;
                } else if (isMethodInClass(node, "or", "java.math.BigInteger")) {
                    tokenType = TokenType.BAR;
                } else if (isMethodInClass(node, "xor", "java.math.BigInteger")) {
                    tokenType = TokenType.CARET;
                } else if (isMethodInClass(node, "add", "java.math.BigInteger")) {
                    tokenType = TokenType.PLUS;
                } else if (isMethodInClass(node, "subtract", "java.math.BigInteger")) {
                    tokenType = TokenType.MINUS;
                } else if (isMethodInClass(node, "multiply", "java.math.BigInteger")) {
                    tokenType = TokenType.STAR;
                } else if (isMethodInClass(node, "divide", "java.math.BigInteger")) {
                    tokenType = TokenType.TILDE_SLASH;
                } else if (isMethodInClass(node, "shiftLeft", "java.math.BigInteger")) {
                    tokenType = TokenType.LT_LT;
                } else if (isMethodInClass(node, "shiftRight", "java.math.BigInteger")) {
                    tokenType = TokenType.GT_GT;
                }
                if (tokenType != null) {
                    replaceNode(node, binaryExpression(node.getTarget(), tokenType, args.get(0)));
                    return null;
                }
            }
            {
                TokenType tokenType = null;
                if (isMethodInClass(node, "not", "java.math.BigInteger")) {
                    tokenType = TokenType.TILDE;
                } else if (isMethodInClass(node, "negate", "java.math.BigInteger")) {
                    tokenType = TokenType.MINUS;
                }
                if (tokenType != null) {
                    replaceNode(node, prefixExpression(tokenType, node.getTarget()));
                    return null;
                }
            }
            if (isMethodInClass2(node, "append(char)", "java.lang.StringBuilder")) {
                replaceNode(nameNode, identifier("appendChar"));
                return null;
            }
            if (isMethodInClass(node, "length", "java.lang.AbstractStringBuilder")) {
                replaceNode(node, propertyAccess(node.getTarget(), nameNode));
                return null;
            }
            if (isMethodInClass(node, "setLength", "java.lang.AbstractStringBuilder")) {
                nameNode.setToken(token("length"));
                replaceNode(node, assignmentExpression(propertyAccess(node.getTarget(), nameNode), TokenType.EQ,
                        args.get(0)));
                return null;
            }
            return null;
        }

        @Override
        public Void visitPropertyAccess(PropertyAccess node) {
            Expression target = node.getTarget();
            ITypeBinding targetTypeBinding = context.getNodeTypeBinding(target);
            if (target instanceof SimpleIdentifier) {
                String targetName = ((SimpleIdentifier) target).getName();
                if (targetName.equals("Boolean")) {
                    boolean value = node.getPropertyName().getName().equals("TRUE");
                    replaceNode(node, booleanLiteral(value));
                    return null;
                }
                if (targetName.equals("Integer")) {
                    int value;
                    if (node.getPropertyName().getName().equals("MIN_VALUE")) {
                        value = Integer.MIN_VALUE;
                    } else {
                        value = Integer.MAX_VALUE;
                    }
                    replaceNode(node, integer(value));
                    return null;
                }
                if (JavaUtils.isTypeNamed(targetTypeBinding, "java.math.BigInteger")) {
                    if (node.getPropertyName().getName().equals("ZERO")) {
                        replaceNode(node, integer(0));
                        return null;
                    }
                }
            }
            return super.visitPropertyAccess(node);
        }

        @Override
        public Void visitSuperConstructorInvocation(SuperConstructorInvocation node) {
            super.visitSuperConstructorInvocation(node);
            IMethodBinding binding = (IMethodBinding) context.getNodeBinding(node);
            if (isMethodInClass2(binding, "<init>(java.lang.Throwable)", "java.lang.Exception")) {
                node.setConstructorName(identifier("withCause"));
            }
            return null;
        }

        @Override
        public Void visitTypeName(TypeName node) {
            ITypeBinding typeBinding = (ITypeBinding) context.getNodeBinding(node);
            // replace by name
            if (node.getName() instanceof SimpleIdentifier) {
                SimpleIdentifier nameNode = (SimpleIdentifier) node.getName();
                String name = nameNode.getName();
                // Exception -> JavaException
                if (JavaUtils.isTypeNamed(typeBinding, "java.lang.Exception")) {
                    replaceNode(nameNode, identifier("JavaException"));
                }
                if (JavaUtils.isTypeNamed(typeBinding, "java.lang.Throwable")) {
                    replaceNode(nameNode, identifier("Exception"));
                }
                if (JavaUtils.isTypeNamed(typeBinding, "java.lang.IndexOutOfBoundsException")) {
                    replaceNode(nameNode, identifier("RangeError"));
                }
                // StringBuilder -> JavaStringBuilder
                if (name.equals("StringBuilder")) {
                    replaceNode(nameNode, identifier("JavaStringBuilder"));
                }
                // Class<T> -> Type
                if (name.equals("Class")) {
                    replaceNode(node, typeName("Type"));
                }
            }
            // done
            return super.visitTypeName(node);
        }

        @Override
        public Void visitVariableDeclaration(VariableDeclaration node) {
            super.visitVariableDeclaration(node);
            Expression initializer = node.getInitializer();
            ITypeBinding leftBinding = context.getNodeTypeBinding(node);
            ITypeBinding rightBinding = context.getNodeTypeBinding(initializer);
            if (JavaUtils.isTypeNamed(leftBinding, "java.lang.CharSequence")
                    && JavaUtils.isTypeNamed(rightBinding, "java.lang.String")) {
                node.setInitializer(
                        instanceCreationExpression(Keyword.NEW, typeName("CharSequence"), initializer));
                return null;
            }
            return null;
        }
    });
}

From source file:io.stallion.dataAccess.db.mysql.MySqlFilterChain.java

@Override
protected void process(int page, int size, boolean fetchTotalCount) {

    if (page < 1) {
        page = 1;// w  w  w  .j  a  va  2s  . c o m
    }

    StringBuilder whereBuilder = new StringBuilder();
    StringBuilder sqlBuilder = new StringBuilder();
    sqlBuilder.append("SELECT * FROM " + getSchema().getName());

    int x = 0;
    List<Object> params = new ArrayList<>();
    boolean hasDeletedOp = false;
    for (FilterOperation op : getOperations()) {
        if (getSchema().getColumns().contains(op.getFieldName())) {
            throw new UsageException(MessageFormat.format(
                    "Trying to filter on a field that is not in the schema: {0} schema:{1}", op.getFieldName(),
                    clazz.getName()));
        }
        if (x >= 1) {
            whereBuilder.append(" AND ");
        }
        if (op.getIsExclude() == true) {
            whereBuilder.append(" NOT ");
        }
        if (op.getFieldName().equals("deleted")) {
            hasDeletedOp = true;
        }

        if (op.isOrOperation()) {
            addOrOperation(op, whereBuilder, params);
        } else {
            if (op.getOperator().equals(FilterOperator.ANY)) {
                addInClause(whereBuilder, op, params);
            } else {
                String operatorSql = op.getOperatorForSql();
                if (operatorSql.equals("=") && op.getOriginalValue() == null) {
                    whereBuilder.append(MessageFormat.format(" (`{0}` IS NULL) ", op.getFieldName()));
                } else {
                    whereBuilder
                            .append(MessageFormat.format(" (`{0}` {1} ?) ", op.getFieldName(), operatorSql));
                    params.add(formatParam(op));
                }

            }

        }
        x++;
    }
    if (!getIncludeDeleted() && !hasDeletedOp) {
        if (whereBuilder.length() > 0) {
            whereBuilder.append(" AND ");
        }
        whereBuilder.append(" deleted=0 ");
    }
    String whereSql = whereBuilder.toString();
    if (whereSql.trim().length() > 0) {
        whereSql = " WHERE " + whereSql;
        sqlBuilder.append(whereSql);
    }
    if (!Literals.empty(getSortField())) {
        List<String> columnNames = apply(getSchema().getColumns(), col -> col.getName());
        if (!"id".equals(getSortField()) && !columnNames.contains(getSortField().toLowerCase())) {
            throw new UsageException(MessageFormat.format(
                    "Sort field not found in schema: field={0} schema={1}", getSortField(), clazz.getName()));
        }
        sqlBuilder.append(" ORDER BY " + getSortField() + " " + getSortDirection().forSql());
        if (isIdAsSecondarySort()) {
            sqlBuilder.append(", id ASC");
        }
    }
    sqlBuilder.append(" LIMIT " + (page - 1) * size + ", " + size);

    Object[] paramObjects = params.toArray();
    setObjects(DB.instance().query(clazz, sqlBuilder.toString(), paramObjects));

    if (page == 1 && getObjects().size() < size) {
        setMatchingCount(getObjects().size());
    } else if (fetchTotalCount) {
        String countSql = "SELECT COUNT(*) FROM " + getSchema().getName() + whereSql;
        Object count = DB.instance().queryScalar(countSql, paramObjects);
        Integer countInt = count instanceof Integer ? (Integer) count : ((Long) count).intValue();
        setMatchingCount(countInt);
    }

    this.setAverages(map());
    this.setSums(map());

    if (getAverageColumns().size() > 0 || getSumColumns().size() > 0) {
        List<String> columnNames = apply(getSchema().getColumns(), col -> col.getName());
        String sql = "";
        for (String col : getAverageColumns()) {
            if (!columnNames.contains(col)) {
                Log.warn("Tried to average column that doesn't exist " + col);
                continue;
            }
            sql += " AVG(`" + col + "`) AS `staverage_" + col + "`,";
        }
        for (String col : getSumColumns()) {
            if (!columnNames.contains(col)) {
                Log.warn("Tried to sum column that doesn't exist " + col);
                continue;
            }
            sql += " SUM(`" + col + "`) AS `stsum_" + col + "`,";
        }
        if (!StringUtils.isEmpty(sql)) {
            sql = " SELECT " + StringUtils.strip(sql, ",") + " FROM `" + getSchema().getName() + "` "
                    + whereSql;
            Map result = DB.instance().findRecord(sql, paramObjects);
            for (String col : getAverageColumns()) {
                if (result.containsKey("staverage_" + col)) {
                    getAverages().put(col, toDouble(result.get("staverage_" + col)));
                }
            }
            for (String col : getSumColumns()) {
                if (result.containsKey("stsum_" + col)) {
                    getSums().put(col, toDouble(result.get("stsum_" + col)));
                }
            }
        }

    }

}

From source file:edu.sdsc.scigraph.vocabulary.VocabularyNeo4jImpl.java

@Override
public Collection<Concept> getConceptFromId(Query query) {
    QueryParser parser = getQueryParser();
    String idQuery = StringUtils.strip(query.getInput(), "\"");
    Optional<String> fullUri = curieUtil.getIri(idQuery);
    idQuery = QueryParser.escape(idQuery);

    String queryString = format("%s:%s", CommonProperties.FRAGMENT, idQuery);
    if (fullUri.isPresent()) {
        queryString += String.format(" %s:%s", CommonProperties.URI, QueryParser.escape(fullUri.get()));
    }/*from   w w  w.  j av a2 s. c  om*/
    IndexHits<Node> hits;
    try (Transaction tx = graph.beginTx()) {
        hits = graph.index().getNodeAutoIndexer().getAutoIndex().query(parser.parse(queryString));
        tx.success();
        return limitHits(hits, query);
    } catch (ParseException e) {
        logger.log(Level.WARNING, "Failed to parse an ID query", e);
        return Collections.emptySet();
    }

}

From source file:annis.CommonHelper.java

public static List<String> getCorpusPath(URI uri) {
    String rawPath = StringUtils.strip(uri.getRawPath(), "/ \t");

    // split on raw path (so "/" in corpus names are still encoded)
    String[] path = rawPath.split("/");

    // decode every single part by itself
    ArrayList<String> result = new ArrayList<String>(path.length);
    for (int i = 0; i < path.length; i++) {
        try {//  w w w . j  a va 2  s .com
            result.add(URLDecoder.decode(path[i], "UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            log.error(null, ex);
            // fallback
            result.add(path[i]);
        }
    }

    return result;
}