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

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

Introduction

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

Prototype

public static boolean endsWith(String str, String suffix) 

Source Link

Document

Check if a String ends with a specified suffix.

Usage

From source file:cn.orignzmn.shopkepper.common.utils.excel.ImportExcel.java

/**
 * ??//from   w ww .j  a  va2s  . c o  m
 * @param cls 
 * @param groups 
 */
public <E> List<E> getDataList(Class<E> cls, Map<String, Object> inportInfo, int... groups)
        throws InstantiationException, IllegalAccessException {
    List<Object[]> annotationList = Lists.newArrayList();
    // Get annotation field 
    Field[] fs = cls.getDeclaredFields();
    ExcelSheet esarr = cls.getAnnotation(ExcelSheet.class);
    String annTitle = "";
    if (esarr == null)
        return Lists.newArrayList();
    annTitle = esarr.value();
    for (Field f : fs) {
        ExcelField ef = f.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == 2)) {
            if (groups != null && groups.length > 0) {
                boolean inGroup = false;
                for (int g : groups) {
                    if (inGroup) {
                        break;
                    }
                    for (int efg : ef.groups()) {
                        if (g == efg) {
                            inGroup = true;
                            annotationList.add(new Object[] { ef, f });
                            break;
                        }
                    }
                }
            } else {
                annotationList.add(new Object[] { ef, f });
            }
        }
    }
    // Get annotation method
    Method[] ms = cls.getDeclaredMethods();
    for (Method m : ms) {
        ExcelField ef = m.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == 2)) {
            if (groups != null && groups.length > 0) {
                boolean inGroup = false;
                for (int g : groups) {
                    if (inGroup) {
                        break;
                    }
                    for (int efg : ef.groups()) {
                        if (g == efg) {
                            inGroup = true;
                            annotationList.add(new Object[] { ef, m });
                            break;
                        }
                    }
                }
            } else {
                annotationList.add(new Object[] { ef, m });
            }
        }
    }
    // Field sorting
    Collections.sort(annotationList, new Comparator<Object[]>() {
        public int compare(Object[] o1, Object[] o2) {
            return new Integer(((ExcelField) o1[0]).sort()).compareTo(new Integer(((ExcelField) o2[0]).sort()));
        };
    });
    //log.debug("Import column count:"+annotationList.size());
    // Get excel data
    List<E> dataList = Lists.newArrayList();
    //???
    if (!"".equals(annTitle)) {
        String title = StringUtils.trim(this.getCellValue(this.getRow(0), 0).toString());
        if (!annTitle.equals(title)) {
            inportInfo.put("success", false);
            inportInfo.put("message", "??");
            return Lists.newArrayList();
        }
    }
    for (int i = this.getDataRowNum(); i < this.getLastDataRowNum(); i++) {
        E e = (E) cls.newInstance();
        int column = 0;
        Row row = this.getRow(i);

        StringBuilder sb = new StringBuilder();
        for (Object[] os : annotationList) {
            Object val = this.getCellValue(row, column++);
            if (val != null) {
                ExcelField ef = (ExcelField) os[0];
                // If is dict type, get dict value
                //               if (StringUtils.isNotBlank(ef.dictType())){
                //                  val = DictUtils.getDictValue(val.toString(), ef.dictType(), "");
                //                  //log.debug("Dictionary type value: ["+i+","+colunm+"] " + val);
                //               }
                // Get param type and type cast
                Class<?> valType = Class.class;
                if (os[1] instanceof Field) {
                    valType = ((Field) os[1]).getType();
                } else if (os[1] instanceof Method) {
                    Method method = ((Method) os[1]);
                    if ("get".equals(method.getName().substring(0, 3))) {
                        valType = method.getReturnType();
                    } else if ("set".equals(method.getName().substring(0, 3))) {
                        valType = ((Method) os[1]).getParameterTypes()[0];
                    }
                }
                //log.debug("Import value type: ["+i+","+column+"] " + valType);
                try {
                    if (valType == String.class) {
                        String s = String.valueOf(val.toString());
                        if (StringUtils.endsWith(s, ".0")) {
                            val = StringUtils.substringBefore(s, ".0");
                        } else {
                            val = String.valueOf(val.toString());
                        }
                    } else if (valType == Integer.class) {
                        val = Double.valueOf(val.toString()).intValue();
                    } else if (valType == Long.class) {
                        val = Double.valueOf(val.toString()).longValue();
                    } else if (valType == Double.class) {
                        val = Double.valueOf(val.toString());
                    } else if (valType == Float.class) {
                        val = Float.valueOf(val.toString());
                    } else if (valType == Date.class) {
                        val = DateUtil.getJavaDate((Double) val);
                    } else {
                        if (ef.fieldType() != Class.class) {
                            val = ef.fieldType().getMethod("getValue", String.class).invoke(null,
                                    val.toString());
                        } else {
                            val = Class
                                    .forName(this.getClass().getName().replaceAll(
                                            this.getClass().getSimpleName(),
                                            "fieldtype." + valType.getSimpleName() + "Type"))
                                    .getMethod("getValue", String.class).invoke(null, val.toString());
                        }
                    }
                } catch (Exception ex) {
                    log.info("Get cell value [" + i + "," + column + "] error: " + ex.toString());
                    val = null;
                }
                // set entity value
                if (os[1] instanceof Field) {
                    Reflections.invokeSetter(e, ((Field) os[1]).getName(), val);
                } else if (os[1] instanceof Method) {
                    String mthodName = ((Method) os[1]).getName();
                    if ("get".equals(mthodName.substring(0, 3))) {
                        mthodName = "set" + StringUtils.substringAfter(mthodName, "get");
                    }
                    Reflections.invokeMethod(e, mthodName, new Class[] { valType }, new Object[] { val });
                }
            }
            sb.append(val + ", ");
        }
        dataList.add(e);
        log.debug("Read success: [" + i + "] " + sb.toString());
    }
    return dataList;
}

From source file:com.adobe.acs.commons.wcm.notifications.impl.SystemNotificationsImpl.java

@Override
public void handleEvent(final Event event) {
    final long start = System.currentTimeMillis();

    if (!this.isAuthor()) {
        log.warn("This event handler should ONLY run on AEM Author.");
        return;/* w  w w.j  a  va 2  s  . c  om*/
    }

    /** The following code will ONLY execute on AEM Author **/

    final String path = (String) event.getProperty(SlingConstants.PROPERTY_PATH);
    if (StringUtils.endsWith(path, JcrConstants.JCR_CONTENT)) {
        // Ignore jcr:content nodes; Only handle events for cq:Page
        return;
    }

    if (this.hasNotifications()) {
        if (!this.isFilter.getAndSet(true)) {
            this.registerAsFilter();
        }
    } else {
        if (this.isFilter.getAndSet(false)) {
            this.unregisterFilter();
            log.debug("Unregistered System Notifications Sling Filter");
        }
    }

    if (System.currentTimeMillis() - start > 2500) {
        log.warn(
                "Event handling for System notifications took [ {} ] ms. Event blacklisting occurs after 5000 ms.",
                System.currentTimeMillis() - start);
    }
}

From source file:com.adobe.acs.commons.wcm.impl.ComponentErrorHandlerImpl.java

protected final boolean accepts(final SlingHttpServletRequest request,
        final SlingHttpServletResponse response) {

    if (!StringUtils.endsWith(request.getRequestURI(), ".html")
            || !StringUtils.contains(response.getContentType(), "html")) {
        // Do not inject around non-HTML requests
        return false;
    }//from  w  w  w. j  a  v a2s  . c  om

    final ComponentContext componentContext = WCMUtils.getComponentContext(request);
    if (componentContext == null // ComponentContext is null
            || componentContext.getComponent() == null // Component is null
            || componentContext.isRoot()) { // Suppress on root context
        return false;
    }

    // Check to make sure the suppress key has not been added to the request
    if (this.isComponentErrorHandlingSuppressed(request)) {
        // Suppress key is detected, skip handling

        return false;
    }

    // Check to make sure the SlingRequest's resource isn't in the suppress list
    final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request;
    for (final String suppressedResourceType : suppressedResourceTypes) {
        if (slingRequest.getResource().isResourceType(suppressedResourceType)) {
            return false;
        }
    }

    return true;
}

From source file:com.cimmyt.model.dao.impl.AbstractDAO.java

/**
 * Find single by values/*from ww w  . j  av  a2 s.co m*/
 * @param clazz
 * @param properties
 * @param values
 * @return
 * @throws Exception
 */
public List<T> findListByValues(T clazz, Object[] properties, Object[] values) throws Exception {

    if (properties.length != values.length) {
        throw new Exception("The number of properties must be the same than the number of values");
    }
    String strClazz = type.getSimpleName();
    StringBuilder builder = new StringBuilder("FROM " + strClazz + " as a" + " WHERE ");
    for (int i = 0; i < values.length; i++) {
        if (values[i] instanceof String) {
            builder.append("a." + properties[i] + " LIKE ?");
        } else {
            builder.append("a." + properties[i] + " = ?");
        }
        builder.append(" AND ");
    }
    String query = builder.toString().trim();
    if (StringUtils.endsWith(query, "AND")) {
        query = StringUtils.removeEnd(query, "AND");
    }
    @SuppressWarnings("unchecked")
    List<T> list = (List<T>) getHibernateTemplate().find(query, values);
    if (list != null && !list.isEmpty()) {
        return list;
    } else {
        return null;
    }
}

From source file:com.iyonger.apm.web.model.AgentManager.java

/**
 * Filter the user owned agents from given agents.
 *
 * @param agents all agents/*ww  w  .j a  va 2 s .  c  o  m*/
 * @param userId userId
 * @return userOwned agents.
 */
public Set<AgentIdentity> filterUserAgents(Set<AgentIdentity> agents, String userId) {

    Set<AgentIdentity> userAgent = new HashSet<AgentIdentity>();
    for (AgentIdentity each : agents) {
        String region = ((AgentControllerIdentityImplementation) each).getRegion();
        if (StringUtils.endsWith(region, "owned_" + userId) || !StringUtils.contains(region, "owned_")) {
            userAgent.add(each);
        }
    }
    return userAgent;
}

From source file:com.sfs.whichdoctor.dao.PaymentDAOImpl.java

/**
 * Process a credit card payment./*from  www  . j  av  a2  s  .  co m*/
 *
 * @param cardNumber the card number
 * @param cardHolder the card holder
 * @param expiryMonth the expiry month
 * @param expiryYear the expiry year
 * @param securityCode the security code
 * @param totalValue the total value
 * @param description the description
 * @param purchaseComment the purchase comment
 * @return the string[] where:
 *       string[0] = success/error,
 *       string[1] = transaction reference,
 *       string[2] = error message,
 *       string[3] = extended error log
 */
public final String[] processCreditCardPayment(final String cardNumber, final String cardHolder,
        final int expiryMonth, final int expiryYear, final int securityCode, final double totalValue,
        final String description, final String purchaseComment) {

    String success = "", reference = "", message = "", logMessage = "";

    /* Perform a web service call using XFire libraries */
    try {
        Client client = new Client(new URL(this.paymentUrl));

        dataLogger.debug("Processing payment");

        Object[] result = client.invoke("process", new Object[] { accessId, secret, cardNumber, cardHolder,
                expiryMonth, expiryYear, securityCode, totalValue, 0, "", description, purchaseComment });

        dataLogger.info("Payment processing complete. Results Object[]: " + result);

        String resultString = (String) result[0];

        StringTokenizer st = new StringTokenizer(resultString, ",");
        int i = 0;
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            if (StringUtils.startsWith(token, "'")) {
                token = StringUtils.substring(token, 1, token.length());
            }
            if (StringUtils.endsWith(token, "'")) {
                token = StringUtils.substring(token, 0, token.length() - 1);
            }

            switch (i) {
            case 0:
                success = token;
                break;
            case 1:
                reference = token;
                break;
            case 2:
                message = token;
                break;
            case 3:
                logMessage = token;
                break;
            }

            i++;
        }

        dataLogger.info("Payment result: " + success + ", reference: " + reference + ", message: " + message);
    } catch (Exception e) {
        dataLogger.error("Error performing payment process web service lookup: " + e.getMessage(), e);
    }

    return new String[] { success, reference, message, logMessage };
}

From source file:com.widen.valet.Route53Driver.java

private void checkDomainName(String name) {
    Defense.notBlank(name, "name");

    if (StringUtils.startsWith(name, ".") || !StringUtils.endsWith(name, ".")) {
        throw new IllegalArgumentException("Domain name '" + name
                + "' is invalid. Name can not start with a period and must end with a period.");
    }//from   w  ww .java2 s . c o m
}

From source file:com.microsoft.alm.plugin.external.commands.Command.java

protected boolean isFilePath(final String line) {
    if (StringUtils.endsWith(line, ":")) {
        // File paths are different on different OSes
        if (StringUtils.containsAny(line, "\\/")) {
            return true;
        }//  w w  w  . jav  a 2s. co  m
    }
    return false;
}

From source file:gov.nih.nci.firebird.web.action.FirebirdActionSupport.java

@SuppressWarnings({ "PMD.UseStringBufferForStringAppends" })
private String getKeyPrefix(String keyBase) {
    String prefix = keyBase;/*from   w  w w  . j  a  v  a2 s. c o  m*/
    if (StringUtils.isNotEmpty(keyBase) && !StringUtils.endsWith(keyBase, ".")) {
        prefix += ".";
    }
    return prefix;
}

From source file:hydrograph.ui.graph.debugconverter.SchemaHelper.java

/**
 * This function will return file path with validation
 * @param path//from ww w  .  jav  a  2 s .  c  o  m
 * @return validPath
 */
public String validatePath(String path) {
    String validPath = null;
    if (StringUtils.endsWith(path, File.separator)) {
        return path;
    } else {
        validPath = path + File.separator;
        return validPath;
    }
}