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

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

Introduction

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

Prototype

public static String substring(String str, int start) 

Source Link

Document

Gets a substring from the specified String avoiding exceptions.

Usage

From source file:it.biztech.btable.olap.OlapUtils.java

private Connection getMdxConnection(String catalog) {
    if (catalog != null && catalog.startsWith("/")) {
        catalog = StringUtils.substring(catalog, 1);
    }/*from ww w.j  a  v  a  2  s. c om*/

    MondrianCatalog selectedCatalog = mondrianCatalogService.getCatalog(catalog, userSession);
    if (selectedCatalog == null) {
        logger.error("Received catalog '" + catalog + "' doesn't appear to be valid");
        return null;
    }
    selectedCatalog.getDataSourceInfo();
    logger.info("Found catalog " + selectedCatalog.toString());

    return getMdxConnection(selectedCatalog.getDefinition(), selectedCatalog.getJndi());
}

From source file:gda.jython.translator.GeneralTranslator.java

static char nextPart(String string, int currentlocation) {
    String rightOfStart = StringUtils.stripToEmpty(StringUtils.substring(string, currentlocation));
    char nextPart = rightOfStart.charAt(0);
    return nextPart;
}

From source file:com.prowidesoftware.swift.model.field.SwiftParseUtils.java

/**
 * Returns the alpha suffix of the value.
 * The split is made when the first alpha (not numetic or comma) character is found.
 * For example:<br />/*from   w ww.java2 s  . c o  m*/
 * 2345,33ABCD will be return ABCD<br />
 * If the value does not contain any alpha character <code>null</code> is returned.
 *
 * @param value
 * @return s
 */
public static String getAlphaSuffix(final String value) {
    if (value != null && value.length() > 0) {
        int i = 0;
        while (i < value.length() && (StringUtils.isNumeric("" + value.charAt(i))
                || StringUtils.equals("" + value.charAt(i), ","))) {
            i++;
        }
        if (i < value.length()) {
            return StringUtils.substring(value, i);
        }
    }
    return null;
}

From source file:com.haulmont.cuba.core.global.FileTypesHelper.java

/**
 * Gets the mime-type of a file. Currently the mime-type is resolved based
 * only on the file name extension.//from www.j av a 2s .c  o m
 *
 * @param fileName
 *            the name of the file whose mime-type is requested.
 * @return mime-type <code>String</code> for the given filename
 */
public static String getMIMEType(String fileName) {

    // Checks for nulls
    if (fileName == null) {
        throw new NullPointerException("Filename can not be null");
    }

    // Calculates the extension of the file
    int dotIndex = fileName.lastIndexOf(".");
    if (dotIndex > -1) {
        final String ext = StringUtils.substring(fileName, dotIndex + 1).toLowerCase();

        // Return type from extension map, if found
        final String type = extToMIMEMap.get(ext);
        if (type != null) {
            return type;
        }
    }

    return DEFAULT_MIME_TYPE;
}

From source file:com.intuit.tank.runner.TestPlanRunner.java

private void runScriptSteps(HDScriptUseCase hdScriptUseCase) throws KillScriptException, AbortScriptException,
        GotoScriptException, RestartScriptException, NextScriptGroupException {
    List<TestStep> scriptSteps = hdScriptUseCase.getScriptSteps();
    String gotoGroup = null;//from  ww w .ja va2 s. co m
    LogEvent logEvent = LogUtil.getLogEvent();
    for (int i = 0; i < scriptSteps.size(); i++) {
        while (APITestHarness.getInstance().getCmd() == WatsAgentCommand.pause) {
            if (APITestHarness.getInstance().hasMetSimulationTime()) {
                APITestHarness.getInstance().setCommand(WatsAgentCommand.stop);
                break;
            } else {
                try {
                    Thread.sleep(APITestHarness.POLL_INTERVAL);
                } catch (InterruptedException e) {
                    // LOG.warn("Got interrupded during pause.");
                }
            }
        }
        if (APITestHarness.getInstance().getCmd() == WatsAgentCommand.kill) {
            return;
        }
        TestStep testStep = scriptSteps.get(i);
        logEvent.setStep(testStep);
        logEvent.setTransactionId(UUID.randomUUID().toString());
        testStep.setParent(hdScriptUseCase);
        if (gotoGroup != null) {
            if (testStep instanceof RequestStep) {
                RequestStep rs = (RequestStep) testStep;
                logEvent.setStepGroupName(rs.getScriptGroupName());
                if (!gotoGroup.equalsIgnoreCase(rs.getScriptGroupName())) {
                    continue;
                }
            }
        }

        FlowController flowController = APITestHarness.getInstance()
                .getFlowController(Thread.currentThread().getId());

        TestStepContext tsc = new TestStepContext(testStep, variables, testPlan.getTestPlanName(), uniqueName,
                timerMap, this);
        tsc.setRequest(previousRequest);
        tsc.setResponse(previousResponse);
        if (!flowController.shouldExecute(tsc)) {
            continue;
        }
        flowController.nextStep(tsc);
        if (!flowController.shouldExecute(tsc)) {
            continue;
        }

        TestStepRunner tsr = new TestStepRunner(tsc);
        if (APITestHarness.getInstance().getCmd() == WatsAgentCommand.stop) {
            LOG.info(LogUtil.getLogMessage("Executing step after stop command " + tsc.getTestStep(),
                    LogEventType.Script));
        }
        flowController.startStep(tsc);
        String validation = TankConstants.HTTP_CASE_FAIL;
        try {
            validation = tsr.execute();
        } catch (Exception e) {
            if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            }
            throw new RuntimeException(e);
        } finally {
            flowController.endStep(tsc);
        }
        previousRequest = tsc.getRequest();
        previousResponse = tsc.getResponse();

        if (validation.equals(TankConstants.HTTP_CASE_FAIL)) {
            FailableStep rs = (FailableStep) tsc.getTestStep();
            String onFail = rs.getOnFail();
            if (onFail.equalsIgnoreCase(TankConstants.HTTP_CASE_SKIP)) {
                APITestHarness.getInstance().addSkip();
                String groupNameToSkip = rs.getScriptGroupName();
                for (int j = i + 1; j < scriptSteps.size(); j++) {
                    TestStep testStep2 = scriptSteps.get(j);
                    String scriptGroupToTest = null;
                    if (testStep2 instanceof RequestStep) {
                        scriptGroupToTest = ((RequestStep) testStep2).getScriptGroupName();
                    }

                    if (!groupNameToSkip.equals(scriptGroupToTest)) {
                        i = j;
                        break;
                    }
                    if (j == scriptSteps.size() - 1) {
                        return;
                    }
                }
            } else if (onFail.equalsIgnoreCase(TankConstants.HTTP_CASE_KILL)) {
                APITestHarness.getInstance().addKill();
                throw new KillScriptException("Killing " + tsc.getTestStep());
            } else if (onFail.equalsIgnoreCase(TankConstants.HTTP_CASE_SKIPGROUP)) {
                APITestHarness.getInstance().addSkipGroup();
                throw new NextScriptGroupException("Skilling test group at " + tsc.getTestStep());
            } else if (onFail.equalsIgnoreCase(TankConstants.HTTP_CASE_ABORT)) {
                APITestHarness.getInstance().addAbort();
                throw new AbortScriptException("Aborting " + tsc.getTestStep());
            } else if (onFail.equalsIgnoreCase(TankConstants.HTTP_CASE_RESTART)) {
                if (APITestHarness.getInstance().hasMetSimulationTime()) {
                    APITestHarness.getInstance().addKill();
                    throw new KillScriptException("Killing " + tsc.getTestStep());
                } else {
                    APITestHarness.getInstance().addRestart();
                    throw new RestartScriptException("Restarting user at " + tsc.getTestStep());
                }
            } else if (onFail.toLowerCase().startsWith(ScriptConstants.ACTION_GOTO_PREFIX)) {
                gotoGroup = StringUtils.substring(onFail, ScriptConstants.ACTION_GOTO_PREFIX.length());
                i = -1;
                APITestHarness.getInstance().addGoto();
                throw new GotoScriptException("Go to group " + gotoGroup, gotoGroup);
            }
        }
        if (shouldStop(RunPhase.step)) {
            LOG.info("Stop set to step, exiting at step " + testStep.getStepIndex());
            return;
        }
    }
}

From source file:com.taobao.tdhs.jdbc.TDHSStatement.java

private void doUpdate(com.taobao.tdhs.client.statement.Statement s, ParseSQL parseSQL, String tableName,
        String dbName) throws SQLException {
    Query query = preprocessGet(s, parseSQL, tableName, dbName);
    List<Entry<String, String>> updateEntries = parseSQL.getUpdateEntries();
    if (updateEntries == null || updateEntries.isEmpty()) {
        throw new TDHSSQLException("no value to update!", parseSQL.getSql());
    }/*from  ww w .  jav  a 2s  . c om*/

    for (Entry<String, String> e : updateEntries) {
        if (StringUtils.isBlank(e.getKey()) || StringUtils.isBlank(e.getValue())) {
            throw new TDHSSQLException("insert column and values can't be empty!", parseSQL.getSql());
        }
        String field = StringUtil.escapeField(StringUtils.trim(e.getKey()));
        if (field == null) {
            throw new TDHSSQLException("insert column is error!", parseSQL.getSql());
        }
        String value = StringUtils.trim(e.getValue());
        if (StringUtils.equalsIgnoreCase("null", value)) {
            query.set().field(field).setNull();
        } else if (StringUtils.equalsIgnoreCase("now()", value)) {
            query.set().field(field).setNow();
        } else {
            if (StringUtils.startsWith(value, field)) {
                value = value.substring(field.length());
                value = StringUtils.trim(value);
                if (StringUtils.startsWith(value, "+")) {
                    value = value.substring(1);
                    value = StringUtils.trim(value);
                    if (StringUtil.isLong(value)) {
                        query.set().field(field).add(Long.valueOf(value));
                    } else {
                        throw new TDHSSQLException("update value is error ,is not long", parseSQL.getSql());
                    }
                } else if (StringUtils.startsWith(value, "-")) {
                    value = value.substring(1);
                    value = StringUtils.trim(value);
                    if (StringUtil.isLong(value)) {
                        query.set().field(field).sub(Long.valueOf(value));
                    } else {
                        throw new TDHSSQLException("update value is error ,is not long", parseSQL.getSql());
                    }

                } else {
                    throw new TDHSSQLException("update value is error maybe can't support!", parseSQL.getSql());
                }
            } else {
                value = StringUtil.escapeValue(value);
                if (value == null) {
                    throw new TDHSSQLException("update value is error!", parseSQL.getSql());
                }

                if (StringUtils.startsWith(value, BYTE_PARAMETER_PREFIX)) {
                    int pidx = ConvertUtil
                            .safeConvertInt(StringUtils.substring(value, BYTE_PARAMETER_PREFIX.length()), -1);
                    if (byteParameters.containsKey(pidx)) {
                        query.set().field(field).set(byteParameters.get(pidx));
                    } else {
                        query.set().field(field).set(value);
                    }
                } else {
                    query.set().field(field).set(value);
                }
            }
        }
    }
    TDHSResponse response = null;
    try {
        response = query.update();
    } catch (TDHSException e) {
        throw new SQLException(e);
    }
    processResponse(response, true);
}

From source file:com.taobao.tdhs.jdbc.TDHSStatement.java

private void doInsert(com.taobao.tdhs.client.statement.Statement s, ParseSQL parseSQL, String tableName,
        String dbName) throws SQLException {
    Insert insert = s.insert().use(dbName).from(tableName);
    List<Entry<String, String>> insertEntries = parseSQL.getInsertEntries();
    if (insertEntries == null || insertEntries.isEmpty()) {
        throw new TDHSSQLException("no value to insert!", parseSQL.getSql());
    }/*from www  . ja  va2s.co m*/
    for (Entry<String, String> e : insertEntries) {
        if (StringUtils.isBlank(e.getKey()) || StringUtils.isBlank(e.getValue())) {
            throw new TDHSSQLException("insert column and values can't be empty!", parseSQL.getSql());
        }
        String field = StringUtil.escapeField(StringUtils.trim(e.getKey()));
        if (field == null) {
            throw new TDHSSQLException("insert column is error!", parseSQL.getSql());
        }
        String value = StringUtils.trim(e.getValue());
        if (StringUtils.equalsIgnoreCase("null", value)) {
            insert.valueSetNull(field);
        } else if (StringUtils.equalsIgnoreCase("now()", value)) {
            insert.valueSetNow(field);
        } else {
            value = StringUtil.escapeValue(value);
            if (value == null) {
                throw new TDHSSQLException("insert value is error!", parseSQL.getSql());
            }
            if (StringUtils.startsWith(value, BYTE_PARAMETER_PREFIX)) {
                int pidx = ConvertUtil
                        .safeConvertInt(StringUtils.substring(value, BYTE_PARAMETER_PREFIX.length()), -1);
                if (byteParameters.containsKey(pidx)) {
                    insert.value(field, byteParameters.get(pidx));
                } else {
                    insert.value(field, value);
                }
            } else {
                insert.value(field, value);
            }
        }
    }
    TDHSResponse response = null;
    try {
        response = insert.insert();
    } catch (TDHSException e) {
        throw new SQLException(e);
    }
    processResponse(response, null, true, true);
}

From source file:com.primovision.lutransport.core.util.TollCompanyTagUploadUtil.java

private static void setCellValuePlateNumberFormat(HSSFWorkbook wb, Cell cell, Object oneCellValue,
        String vendor) {//  w  w  w  .  j a v a2s  .  c o  m
    if (oneCellValue == null) {
        cell.setCellValue(StringUtils.EMPTY);
        return;
    }

    String plateNum = StringUtils.trimToEmpty(oneCellValue.toString());
    plateNum = plateNum.replaceAll("\u00a0", StringUtils.EMPTY);
    if (StringUtils.isEmpty(plateNum)) {
        cell.setCellValue(StringUtils.EMPTY);
        return;
    }

    if (StringUtils.contains(vendor, TOLL_COMPANY_EZ_PASS_NY)) {
        plateNum = StringUtils.stripStart(plateNum, "0");
        plateNum = StringUtils.substring(plateNum, 2);
    } else if (StringUtils.contains(vendor, TOLL_COMPANY_EZ_PASS_PA)) {
        plateNum = StringUtils.substring(plateNum, 3);
    }
    cell.setCellValue(plateNum);
}

From source file:com.primovision.lutransport.core.util.TollCompanyTagUploadUtil.java

private static void setCellValueFeeFormat(Workbook wb, Cell cell, Object oneCellValue, String vendor) {
    CellStyle style = wb.createCellStyle();
    style.setDataFormat(wb.createDataFormat().getFormat("$#,#0.00"));
    cell.setCellStyle(style);/*  w  w w . ja va 2 s.  com*/

    if (oneCellValue == null) {
        cell.setCellValue(Double.parseDouble("0.0"));
        return;
    }

    String feeStr = StringUtils.replace(oneCellValue.toString(), "$", StringUtils.EMPTY);
    feeStr = StringUtils.trimToEmpty(feeStr);
    feeStr = feeStr.replaceAll("\\p{javaSpaceChar}", StringUtils.EMPTY);
    if (StringUtils.isEmpty(feeStr)) {
        cell.setCellValue(Double.parseDouble("0.0"));
        return;
    }

    if (StringUtils.contains(vendor, TOLL_COMPANY_EZ_PASS_PA)
            || StringUtils.contains(vendor, TOLL_COMPANY_IPASS)
            || StringUtils.contains(vendor, TOLL_COMPANY_SUN_PASS)) {
        if (StringUtils.startsWith(feeStr, "-")) {
            feeStr = StringUtils.substring(feeStr, 1);
        } else {
            feeStr = "-" + feeStr;
        }
    }

    cell.setCellValue(Double.parseDouble(feeStr));
}

From source file:com.prowidesoftware.swift.model.field.Field.java

/**
 * Replaces the hash by empty and trims to null.<br>
 *
 * It also can remove meaningless component separators (If the resulting string only
 * contains the component separator "/", or starts with ":" or starts with "/" separators
 * all of them will also be removed)./*www .  j  a  v a 2s  .c  om*/
 *
 * @param hash hash string used by the get lines method
 * @param value current value to clean
 * @param removeSeparators if true, meaningless starting separators (: and /) are removed
 * @return proper final line value or null if the original field didn't contained content for such line
 */
private String clean(final String hash, final String value, boolean removeSeparators) {
    /*
     * try to replace /hash first just in case the component is optional
     * then replace the hash only if present
     */
    String trimmed = StringUtils
            .trimToNull(StringUtils.replace(StringUtils.replace(value, "/" + hash, ""), hash, ""));
    if (trimmed != null && !onlySlashes(trimmed)) {
        /*
         * sebastian Oct 2015
         * La logica para remover separadores debiera depender de si el offset
         * abarca la linea entera o si el componente del offset esta en al mitad 
         * de una linea, y removerlo solo en este ultimo caso.
         * Esto es dificil de implementar porque no esta modelada la relacion
         * entre componentes y lineas.
         * Por lo tanto de momento se deja el parametro removeSeparators pero
         * con el codigo de aca abajo comentado. Y se coloca a cambio el patch
         * para el caso especifico de :// que es el que aparentemente no esta
         * contemplado segun los test.
         * 
        if (removeSeparators) {
           for (int i = 0; i < trimmed.length(); i++) {
              char c = trimmed.charAt(i);
              if (c != ':' && c != '/') {
          return trimmed.substring(i);
              }
           }
        } else {
           return trimmed;
        }
        */
        if (trimmed.startsWith("://")) {
            return StringUtils.substringAfter(trimmed, "://");
        } else if (removeSeparators && (trimmed.startsWith(":") || trimmed.startsWith("/"))) {
            return StringUtils.trimToNull(StringUtils.substring(trimmed, 1));
        } else {
            return trimmed;
        }
    }
    /*
     * otherwise return null
     */
    return null;
}