Example usage for org.apache.commons.lang StringUtils substringBefore

List of usage examples for org.apache.commons.lang StringUtils substringBefore

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils substringBefore.

Prototype

public static String substringBefore(String str, String separator) 

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:com.amalto.core.query.user.UserQueryHelper.java

public static Condition buildCondition(UserQueryBuilder queryBuilder, IWhereItem whereItem,
        MetadataRepository repository) {
    if (whereItem == null) {
        return TRUE;
    }//  ww  w  .j  a v a  2  s  . c  om
    if (whereItem instanceof WhereAnd || whereItem instanceof WhereOr) { // Handle ANDs and ORs
        List<IWhereItem> whereItems = ((WhereLogicOperator) whereItem).getItems();
        Condition current;
        // TMDM-7513: Prevent incorrect conditions (choose right constant condition depending on operator).
        if (whereItem instanceof WhereAnd) {
            current = TRUE;
        } else {
            current = FALSE;
        }
        for (IWhereItem item : whereItems) {
            if (whereItem instanceof WhereAnd) {
                current = and(current, buildCondition(queryBuilder, item, repository));
            } else {
                current = or(current, buildCondition(queryBuilder, item, repository));
            }
        }
        return current;
    } else if (whereItem instanceof WhereCondition) {
        WhereCondition whereCondition = (WhereCondition) whereItem;
        String operator = whereCondition.getOperator();
        String value = whereCondition.getRightValueOrPath();
        boolean isNotCondition = WhereCondition.PRE_NOT.equals(whereCondition.getStringPredicate());
        // Get metadata information for building query
        String leftPath = whereCondition.getLeftPath();
        ComplexTypeMetadata leftType;
        if (leftPath.contains("/")) { //$NON-NLS-1$
            String leftTypeName = leftPath.substring(0, leftPath.indexOf('/'));
            if (".".equals(leftTypeName)) { //$NON-NLS-1$
                // When using ".", uses first type in select
                leftTypeName = queryBuilder.getSelect().getTypes().get(0).getName();
            }
            leftType = repository.getComplexType(leftTypeName);
        } else {
            leftType = queryBuilder.getSelect().getTypes().get(0);
        }
        String leftFieldName = StringUtils.substringAfter(leftPath, "/"); //$NON-NLS-1$
        // Full text query handling
        if (WhereCondition.FULLTEXTSEARCH.equals(operator)) {
            if (StringUtils.isEmpty(leftPath) || "/".equals(leftPath) || StringUtils.isEmpty(leftFieldName)) { //$NON-NLS-1$
                // Special case for full text: left path is actually the keyword for full text search.
                return fullText(value);
            } else {
                return fullText(leftType.getField(leftFieldName), value);
            }
        }
        if (leftPath.indexOf('/') == -1) {
            throw new IllegalArgumentException(
                    "Incorrect XPath '" + leftPath + "'. An XPath like 'Entity/element' was expected."); //$NON-NLS-1$ //$NON-NLS-2$
        }
        boolean isPerformingTypeCheck = false;
        if (leftFieldName.endsWith("xsi:type") || leftFieldName.endsWith("tmdm:type")) { //$NON-NLS-1$ //$NON-NLS-2$
            isPerformingTypeCheck = true;
        }
        List<TypedExpression> fields;
        if (UserQueryBuilder.ALL_FIELD.equals(leftFieldName)) {
            Collection<FieldMetadata> list = leftType.getFields();
            fields = new LinkedList<TypedExpression>();
            for (FieldMetadata fieldMetadata : list) {
                if (fieldMetadata instanceof SimpleTypeFieldMetadata) {
                    fields.add(new Field(fieldMetadata));
                }
            }
        } else {
            fields = getInnerField(leftPath);
        }
        if (fields == null) {
            fields = getFields(leftType, leftFieldName);
        }
        Condition condition = null;
        for (TypedExpression field : fields) {
            // Field comparisons
            if (!isRealXpath(repository, whereCondition.getRightValueOrPath())) { // Value based comparison
                if (isPerformingTypeCheck) {
                    if (!WhereCondition.EMPTY_NULL.equals(whereCondition.getOperator())) {
                        if (!(field instanceof Alias)) {
                            throw new IllegalArgumentException(
                                    "Expected field '" + leftFieldName + "' to be an alias.");
                        }
                        Alias alias = (Alias) field;
                        if (!(alias.getTypedExpression() instanceof Type)) {
                            throw new IllegalArgumentException(
                                    "Expected alias '" + leftFieldName + "' to be an alias of type.");
                        }
                        Type fieldExpression = (Type) alias.getTypedExpression();
                        ComplexTypeMetadata typeForCheck = (ComplexTypeMetadata) fieldExpression.getField()
                                .getFieldMetadata().getType();
                        if (!typeForCheck.getName().equals(value)) {
                            for (ComplexTypeMetadata subType : typeForCheck.getSubTypes()) {
                                if (subType.getName().equals(value)) {
                                    typeForCheck = subType;
                                    break;
                                }
                            }
                        }
                        condition = isa(fieldExpression.getField().getFieldMetadata(), typeForCheck);
                    } else {
                        // TMDM-6831: Consider a "emptyOrNull(type)" as a "isa(field, actual_field_type)".
                        Alias alias = (Alias) field;
                        if (!(alias.getTypedExpression() instanceof Type)) {
                            throw new IllegalArgumentException(
                                    "Expected alias '" + leftFieldName + "' to be an alias of type.");
                        }
                        Type fieldExpression = (Type) alias.getTypedExpression();
                        condition = emptyOrNull(fieldExpression);
                    }
                } else {
                    boolean isFk = field instanceof Field
                            && ((Field) field).getFieldMetadata() instanceof ReferenceFieldMetadata;
                    if (!isFk
                            && (field instanceof Field && !StorageMetadataUtils.isValueAssignable(value,
                                    ((Field) field).getFieldMetadata()))
                            && !WhereCondition.EMPTY_NULL.equals(operator)) {
                        LOGGER.warn(
                                "Skip '" + leftFieldName + "' because it can't accept value '" + value + "'");
                        continue;
                    }
                    if (WhereCondition.CONTAINS.equals(operator)) {
                        condition = add(condition, contains(field, value));
                    } else if (WhereCondition.CONTAINS_SENTENCE.equals(operator)) {
                        condition = add(condition, contains(field, value));
                    } else if (WhereCondition.EQUALS.equals(operator)) {
                        condition = add(condition, eq(field, value));
                    } else if (WhereCondition.GREATER_THAN.equals(operator)) {
                        condition = add(condition, gt(field, value));
                    } else if (WhereCondition.GREATER_THAN_OR_EQUAL.equals(operator)) {
                        condition = add(condition, gte(field, value));
                    } else if (WhereCondition.LOWER_THAN.equals(operator)) {
                        condition = add(condition, lt(field, value));
                    } else if (WhereCondition.LOWER_THAN_OR_EQUAL.equals(operator)) {
                        condition = add(condition, lte(field, value));
                    } else if (WhereCondition.NOT_EQUALS.equals(operator)) {
                        condition = add(condition, neq(field, value));
                    } else if (WhereCondition.STARTSWITH.equals(operator)) {
                        condition = add(condition, startsWith(field, value));
                    } else if (WhereCondition.EMPTY_NULL.equals(operator)) {
                        condition = add(condition, emptyOrNull(field));
                    } else {
                        throw new NotImplementedException("'" + operator + "' support not implemented.");
                    }
                }
            } else {
                // Right value is another field name
                String rightTypeName = StringUtils.substringBefore(whereCondition.getRightValueOrPath(), "/"); //$NON-NLS-1$
                String rightFieldName = StringUtils.substringAfter(whereCondition.getRightValueOrPath(), "/"); //$NON-NLS-1$
                FieldMetadata leftField = leftType.getField(leftFieldName);
                ComplexTypeMetadata rightType = repository.getComplexType(rightTypeName);
                if (rightType == null) {
                    throw new IllegalArgumentException("Path '" + whereCondition.getRightValueOrPath()
                            + "' seems invalid (entity '" + rightTypeName + "' does not exist).");
                }
                FieldMetadata rightField = rightType.getField(rightFieldName);
                if (WhereCondition.EQUALS.equals(operator)) {
                    condition = add(condition, eq(leftField, rightField));
                } else if (WhereCondition.LOWER_THAN_OR_EQUAL.equals(operator)) {
                    condition = add(condition, lte(leftField, rightField));
                } else if (WhereCondition.JOINS.equals(operator)) {
                    if (field instanceof Field) {
                        FieldMetadata fieldMetadata = ((Field) field).getFieldMetadata();
                        if (!(fieldMetadata instanceof ReferenceFieldMetadata)) {
                            throw new IllegalArgumentException(
                                    "Field '" + leftFieldName + "' is not a FK field.");
                        }
                        queryBuilder.join(field, ((ReferenceFieldMetadata) fieldMetadata).getReferencedField());
                    } else {
                        throw new IllegalArgumentException(
                                "Can not perform not on '" + leftFieldName + "' because it is not a field.");
                    }
                } else {
                    throw new NotImplementedException(
                            "'" + operator + "' support not implemented for field to field comparison.");
                }
            }
        }
        if (condition == null) {
            return TRUE;
        }
        if (isNotCondition) {
            return not(condition);
        } else {
            return condition;
        }
    } else {
        throw new NotImplementedException(
                "No support for where item of type " + whereItem.getClass().getName());
    }
}

From source file:jef.database.dialect.SqliteDialect.java

public void parseDbInfo(ConnectInfo connectInfo) {
    String url = connectInfo.getUrl();
    if (!url.startsWith("jdbc:sqlite:")) {
        throw new IllegalArgumentException(url);
    }//from  w  w  w.  j  a  v  a2 s . c o  m
    String dbpath = url.substring(12);
    dbpath = StringUtils.substringBefore(dbpath, "?");
    File file = new File(dbpath);
    connectInfo.setDbname(file.getName());
    connectInfo.setHost("");
}

From source file:edu.wfu.inotado.InotadoTestBase.java

/**
 * Reads a Json file from directory - inotado-api/api/resources/json
 * //  w  ww .j  a  va 2s .  co m
 * @param fileName
 */
@SuppressWarnings("resource")
protected String readJsonFromFile(String fileName) {
    BufferedReader br;
    String jsonStr = "No content available!";
    // get the file location
    URL location = this.getClass().getProtectionDomain().getCodeSource().getLocation();
    String pathCurrent = location.getFile();
    String pathToXml = StringUtils.substringBefore(pathCurrent, "inotado-")
            + "/inotado-api/api/resources/json/";
    String file = pathToXml + fileName;
    try {
        br = new BufferedReader(new FileReader(file));
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append('\n');
            line = br.readLine();
        }
        jsonStr = sb.toString();
    } catch (FileNotFoundException e) {
        log.error("Unalbe to read the file:" + file, e);
    } catch (IOException e) {
        log.error("Erorr occurred while reading file:" + file, e);
    }
    return jsonStr;
}

From source file:com.bstek.dorado.view.resolver.HtmlViewResolver.java

protected String extractViewName(String uri) {
    String viewName = StringUtils.substringBefore(uri, ";");
    if (uriPrefix != null && viewName.startsWith(uriPrefix)) {
        viewName = viewName.substring(uriPrefixLen);
    }//from   w  w w  .j a  va2 s .co  m
    if (uriSuffix != null && viewName.endsWith(uriSuffix)) {
        viewName = viewName.substring(0, viewName.length() - uriSuffixLen);
    }
    return viewName;
}

From source file:com.hangum.tadpole.rdb.core.dialog.dbconnect.MSSQLLoginComposite.java

/**
 * ip? instance   ping./*from ww w.  j  a  v  a  2s.  c om*/
 */
public boolean isPing(String strHost, String port) {
    if (StringUtils.contains(strHost, "\\")) {
        String strIp = StringUtils.substringBefore(strHost, "\\");

        return super.isPing(strIp, port);
    } else if (StringUtils.contains(strHost, "/")) {
        String strIp = StringUtils.substringBefore(strHost, "/");

        return super.isPing(strIp, port);
    } else {
        return super.isPing(strHost, port);
    }
}

From source file:com.razorfish.controllers.pages.CheckoutController.java

protected String processOrderCode(final String orderCode, final Model model, final HttpServletRequest request)
        throws CMSItemNotFoundException {
    final OrderData orderDetails = orderFacade.getOrderDetailsForCode(orderCode);

    if (orderDetails.isGuestCustomer() && !StringUtils.substringBefore(orderDetails.getUser().getUid(), "|")
            .equals(getSessionService().getAttribute(WebConstants.ANONYMOUS_CHECKOUT_GUID))) {
        return getCheckoutRedirectUrl();
    }//from   w  w  w .j a va2s.co m

    if (orderDetails.getEntries() != null && !orderDetails.getEntries().isEmpty()) {
        for (final OrderEntryData entry : orderDetails.getEntries()) {
            final String productCode = entry.getProduct().getCode();
            final ProductData product = productFacade.getProductForCodeAndOptions(productCode,
                    Arrays.asList(ProductOption.BASIC, ProductOption.PRICE, ProductOption.CATEGORIES));
            entry.setProduct(product);
        }
    }

    model.addAttribute("orderCode", orderCode);
    model.addAttribute("orderData", orderDetails);
    model.addAttribute("allItems", orderDetails.getEntries());
    model.addAttribute("deliveryAddress", orderDetails.getDeliveryAddress());
    model.addAttribute("deliveryMode", orderDetails.getDeliveryMode());
    model.addAttribute("paymentInfo", orderDetails.getPaymentInfo());
    model.addAttribute("pageType", PageType.ORDERCONFIRMATION.name());
    //      final String uid = orderDetails.getPaymentInfo().getBillingAddress().getEmail();
    //      model.addAttribute("email", uid);

    //      if (orderDetails.isGuestCustomer() && !model.containsAttribute("guestRegisterForm"))
    //      {
    //         final GuestRegisterForm guestRegisterForm = new GuestRegisterForm();
    //         guestRegisterForm.setOrderCode(orderDetails.getGuid());
    //         guestRegisterForm.setUid(uid);
    //         model.addAttribute(guestRegisterForm);
    //      }

    final AbstractPageModel cmsPage = getContentPageForLabelOrId(CART_CMS_PAGE_LABEL);
    storeCmsPageInModel(model, cmsPage);
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(CART_CMS_PAGE_LABEL));
    model.addAttribute("metaRobots", "no-index,no-follow");

    return ControllerConstants.Views.Pages.Checkout.CheckoutConfirmationPage;
}

From source file:com.hangum.tadpole.rdb.core.dialog.dbconnect.composite.MSSQLLoginComposite.java

/**
 * ip? instance   ping.//from  ww w.ja v  a2  s  .c o  m
 */
public boolean isPing(String strHost, String port) {
    if (StringUtils.contains(strHost, "\\")) {
        String strIp = StringUtils.substringBefore(strHost, "\\");

        return ValidChecker.isPing(strIp, port);
    } else if (StringUtils.contains(strHost, "/")) {
        String strIp = StringUtils.substringBefore(strHost, "/");

        return ValidChecker.isPing(strIp, port);
    } else {
        return ValidChecker.isPing(strHost, port);
    }
}

From source file:captureplugin.drivers.dreambox.connector.DreamboxConnector.java

/**
 * Tries to parse a Long//from   w w w  .  j av  a 2  s  . c o  m
 * 
 * @param longStr
 *          String with Long-Value
 * @return long-Value or -1
 */
private long getLong(String longStr) {
    if (longStr.contains(".")) {
        longStr = StringUtils.substringBefore(longStr, ".");
    }

    try {
        return Long.parseLong(longStr);
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }

    return -1;
}

From source file:eionet.cr.web.action.admin.staging.StagingDatabaseActionBean.java

/**
 * Gets the suggested db name.//from  w  ww.j a va 2s.  c o  m
 *
 * @return the suggested db name
 */
public String getSuggestedDbName() {
    return StringUtils.isBlank(fileName) ? "" : StringUtils.substringBefore(fileName, ".");
}

From source file:com.rosy.bill.dao.hibernate.HibernateDao.java

private String prepareCountSql(String orgSql) {
    String fromSql = orgSql;/*w w  w .  j  a v  a2s  .  c o  m*/
    //select??order by???count,?.
    fromSql = "from " + StringUtils.substringAfter(fromSql, "from");
    fromSql = StringUtils.substringBefore(fromSql, "order by");
    if (StringUtils.contains(fromSql, "group by")) {
        return " select count(*) from ( select count(*) " + fromSql + ")";
    }
    String countSql = "select count(*) " + fromSql;
    return countSql;
}