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

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

Introduction

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

Prototype

public static int ordinalIndexOf(String str, String searchStr, int ordinal) 

Source Link

Document

Finds the n-th index within a String, handling null.

Usage

From source file:org.apache.hadoop.hive.ql.udf.generic.GenericUDFSubstringIndex.java

@Override
public Object evaluate(DeferredObject[] arguments) throws HiveException {
    // str/*from   ww  w .  ja  v a  2 s.c o  m*/
    String str = getStringValue(arguments, 0, converters);
    if (str == null) {
        return null;
    }
    if (str.length() == 0) {
        output.set("");
        return output;
    }

    // delim
    String delim;
    if (isDelimConst) {
        delim = delimConst;
    } else {
        delim = getStringValue(arguments, 1, converters);
    }
    if (delim == null) {
        return null;
    }
    if (delim.length() == 0) {
        output.set("");
        return output;
    }

    // count
    Integer countV;
    if (isCountConst) {
        countV = countConst;
    } else {
        countV = getIntValue(arguments, 2, converters);
    }
    if (countV == null) {
        return null;
    }
    int count = countV.intValue();
    if (count == 0) {
        output.set("");
        return output;
    }

    // get substring
    String res;
    if (count > 0) {
        int idx = StringUtils.ordinalIndexOf(str, delim, count);
        if (idx != -1) {
            res = str.substring(0, idx);
        } else {
            res = str;
        }
    } else {
        int idx = StringUtils.lastOrdinalIndexOf(str, delim, -count);
        if (idx != -1) {
            res = str.substring(idx + 1);
        } else {
            res = str;
        }
    }

    output.set(res);
    return output;
}

From source file:org.apache.sysml.runtime.instructions.cp.VariableCPInstruction.java

@Override
public void updateInstructionThreadID(String pattern, String replace) throws DMLRuntimeException {
    if (opcode == VariableOperationCode.CreateVariable || opcode == VariableOperationCode.SetFileName) {
        //replace in-memory instruction
        input2.setName(input2.getName().replaceAll(pattern, replace));

        // Find a start position of file name string.
        int iPos = StringUtils.ordinalIndexOf(instString, Lop.OPERAND_DELIMITOR, CREATEVAR_FILE_NAME_VAR_POS);
        // Find a end position of file name string.
        int iPos2 = StringUtils.indexOf(instString, Lop.OPERAND_DELIMITOR, iPos + 1);

        StringBuilder sb = new StringBuilder();
        sb.append(instString.substring(0, iPos + 1)); // It takes first part before file name.
        // This will replace 'pattern' with 'replace' string from file name.
        sb.append(ProgramConverter.saveReplaceFilenameThreadID(instString.substring(iPos + 1, iPos2 + 1),
                pattern, replace));//from   w  w  w. j  a  v a 2 s  .co  m
        sb.append(instString.substring(iPos2 + 1)); // It takes last part after file name.

        instString = sb.toString();
    }
}

From source file:org.artifactory.storage.db.DbServiceImpl.java

private boolean checkMySqlMinVersion() {
    log.debug("Checking MySQL version compatibility");
    ResultSet rs = null;/*from w w  w  . j  a  v a  2  s.co  m*/
    try {
        rs = jdbcHelper.executeSelect("SELECT VERSION();");
        if (rs.next()) {
            String versionString = rs.getString(1);
            int i = StringUtils.ordinalIndexOf(versionString, ".", 2);
            if (i == -1) {
                i = versionString.length();
            }
            Double mysqlVersion = Double.valueOf(versionString.substring(0, i));
            if (mysqlVersion >= MYSQL_MIN_VERSION) {
                return true;
            } else {
                log.error("Unsupported MySQL version found [" + versionString + "]. "
                        + "Minimum version required is " + MYSQL_MIN_VERSION + ". "
                        + "Please follow the requirements on the wiki page.");
                return false;
            }
        }
    } catch (Exception e) {
        log.error("Could not determine MySQL version due to an exception", e);
    } finally {
        DbUtils.close(rs);
    }
    log.error("Could not determine MySQL version. Minimum version should be " + MYSQL_MIN_VERSION
            + " and above.");
    return false;
}

From source file:org.commonwl.view.workflow.WorkflowController.java

/**
 * Extract the path from the end of a full request string
 * @param path The full request string path
 * @param startSlashNum The ordinal slash index of the start of the path
 * @return The path from the end/*from   w ww . j  a v a 2 s  .c  o  m*/
 */
public static String extractPath(String path, int startSlashNum) {
    int pathStartIndex = StringUtils.ordinalIndexOf(path, "/", startSlashNum);
    if (pathStartIndex > -1 && pathStartIndex < path.length() - 1) {
        return path.substring(pathStartIndex + 1).replaceAll("\\/$", "");
    } else {
        return "/";
    }
}

From source file:org.gradle.nativebinaries.toolchain.internal.msvcpp.DefaultWindowsSdkLocator.java

private static String formatVersion(String version) {
    int index = StringUtils.ordinalIndexOf(version, ".", 2);

    if (index != -1) {
        version = version.substring(0, index);
    }// w  w  w. j  av  a 2  s  .  c om

    return version;
}

From source file:org.metamorfosis.template.directive.AppendFileSectionLogic.java

public String process(String position, String ocurrenceCountStr, String ocurrence) {
    // 1. interpretar el ocurrenceCount: [first , last, number] -> a numero
    int ocurrenceCount = ocurrenceCountParser(originalStr, ocurrenceCountStr, ocurrence);

    // 1.1 Validar el ocurrenceCount
    int matchesInFile = StringUtils.countMatches(originalStr, ocurrence);
    if (ocurrenceCount > matchesInFile) {
        throw new DirectiveException(
                "<@AppendFileSection .../> " + "El nmero de ocurrencia solicitada '" + ocurrenceCount + "' "
                        + "supera el numero de ocurrencias en el archivo original '" + matchesInFile + "'");
    }//  w ww. j ava  2  s . c  o m

    // 2. Obtener la posicion de la ocurrencia dentro del archivo original
    int initIndex = StringUtils.ordinalIndexOf(originalStr, ocurrence, ocurrenceCount);
    int lastIndex = initIndex + ocurrence.length();

    //  3. Interpretar la posicion
    StringBuilder originalSb = new StringBuilder(originalStr);
    if ("before".equalsIgnoreCase(position)) {
        originalSb.insert(initIndex, matchOutputStr);
    } else if ("after".equalsIgnoreCase(position)) {
        originalSb.insert(lastIndex, matchOutputStr);
    }

    return originalSb.toString();
}

From source file:org.openmrs.module.clinicalsummary.io.SummariesTask.java

/**
 * Method to extract the database properties used to run OpenMRS. This will be used to extract the index table along some of the necessary tables.
 *//*  ww  w.  j a  v a2s .c  o m*/
protected void prepareDatabaseProperties() {
    Properties props = Context.getRuntimeProperties();

    databaseUser = props.getProperty("database.username");
    if (StringUtils.isBlank(databaseUser))

        databaseUser = props.getProperty("connection.username", "test");

    databasePassword = props.getProperty("database.password");
    if (StringUtils.isBlank(databasePassword))
        databasePassword = props.getProperty("connection.password", "test");

    databaseName = "openmrs";
    databaseHost = "localhost";
    databasePort = "3306";
    String connectionString = props.getProperty("connection.url");
    if (!StringUtils.isBlank(connectionString)) {
        connectionString = props.getProperty("connection.url");
        int questionMark = connectionString.lastIndexOf("?");
        int slashDatabase = StringUtils.ordinalIndexOf(connectionString, "/", 3);
        databaseName = connectionString.substring(slashDatabase + 1, questionMark);
        // get the host
        int slashHost = StringUtils.ordinalIndexOf(connectionString, "/", 2);
        String databasePath = connectionString.substring(slashHost + 1, slashDatabase);
        int colonMarker = databasePath.indexOf(":");
        databaseHost = databasePath.substring(0, colonMarker);
        databasePort = databasePath.substring(colonMarker + 1);
    }
}

From source file:org.openmrs.module.reportingsummary.api.io.util.InputOutputUtils.java

/**
 * Method to extract the runtime properties of OpenMRS. The properties will be used to extract the inverted index
 * table along some of the necessary tables.
 *
 * @return the runtime properties configuration
 *//*from   w ww  .  j av  a2s.co  m*/
public static Properties prepareDatabaseProperties() {
    Properties properties = new Properties();
    Properties runtimeProperties = Context.getRuntimeProperties();

    String databaseUser = runtimeProperties.getProperty("database.username");
    if (StringUtils.isBlank(databaseUser))
        databaseUser = runtimeProperties.getProperty("connection.username", "test");
    properties.setProperty(InputOutputConstants.DATABASE_USERNAME, databaseUser);

    String databasePassword = runtimeProperties.getProperty("database.password");
    if (StringUtils.isBlank(databasePassword))
        databasePassword = runtimeProperties.getProperty("connection.password", "test");
    properties.setProperty(InputOutputConstants.DATABASE_PASSWORD, databasePassword);

    String databaseName = "openmrs";
    String databaseHost = "localhost";
    String databasePort = "3306";
    String connectionString = runtimeProperties.getProperty("connection.url");
    if (!StringUtils.isBlank(connectionString)) {
        connectionString = runtimeProperties.getProperty("connection.url");
        int questionMark = connectionString.lastIndexOf("?");
        int slashDatabase = StringUtils.ordinalIndexOf(connectionString, "/", 3);
        databaseName = connectionString.substring(slashDatabase + 1, questionMark);
        // get the host
        int slashHost = StringUtils.ordinalIndexOf(connectionString, "/", 2);
        String databasePath = connectionString.substring(slashHost + 1, slashDatabase);
        int colonMarker = databasePath.indexOf(":");
        databaseHost = databasePath.substring(0, colonMarker);
        databasePort = databasePath.substring(colonMarker + 1);
    }

    properties.setProperty(InputOutputConstants.DATABASE_NAME, databaseName);
    properties.setProperty(InputOutputConstants.DATABASE_HOSTNAME, databaseHost);
    properties.setProperty(InputOutputConstants.DATABASE_PORT, databasePort);

    return properties;
}

From source file:org.pentaho.di.ui.core.dialog.Splash.java

protected Splash(Display display, Shell splashShell) throws KettleException {
    log = new LogChannel(Spoon.APP_NAME);

    Rectangle displayBounds = display.getPrimaryMonitor().getBounds();

    // "kettle_splash.png"
    kettle_image = loadAsResource(display, BasePropertyHandler.getProperty("splash_image"));
    // "spoon.ico"
    kettle_icon = loadAsResource(display, BasePropertyHandler.getProperty("splash_icon"));
    // "exclamation.png"
    exclamation_image = loadAsResource(display, BasePropertyHandler.getProperty("exclamation_image"));

    verFont = new Font(display, "Helvetica", 11, SWT.BOLD);
    licFont = new Font(display, "Helvetica", licFontSize, SWT.NORMAL);
    devWarningFont = new Font(display, "Helvetica", 10, SWT.NORMAL);

    // versionWarningBackgroundColor = new Color(display, 255, 253, 213);
    versionWarningBackgroundColor = new Color(display, 255, 255, 255);
    versionWarningForegroundColor = new Color(display, 220, 177, 20);

    splash = splashShell;//from   www .  j  a v  a 2s  .c om
    splash.setImage(kettle_icon);

    splash.setText(BaseMessages.getString(PKG, "SplashDialog.Title")); // "Pentaho Data Integration"

    splash.addPaintListener(new PaintListener() {
        public void paintControl(PaintEvent e) {
            StringBuilder sb = new StringBuilder();
            String line = null;

            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(Splash.class.getClassLoader()
                        .getResourceAsStream("org/pentaho/di/ui/core/dialog/license/license.txt")));

                while ((line = reader.readLine()) != null) {
                    sb.append(line + System.getProperty("line.separator"));
                }
            } catch (Exception ex) {
                sb.append("");
                log.logError(BaseMessages.getString(PKG, "SplashDialog.LicenseTextNotFound"), ex);
            }
            Calendar cal = Calendar.getInstance();
            String licenseText = String.format(sb.toString(), cal);
            e.gc.drawImage(kettle_image, 0, 0);

            String fullVersionText = BaseMessages.getString(PKG, "SplashDialog.Version");
            String buildVersion = BuildVersion.getInstance().getVersion();
            if (StringUtils.ordinalIndexOf(buildVersion, ".", 2) > 0) {
                fullVersionText = fullVersionText + " "
                        + buildVersion.substring(0, StringUtils.ordinalIndexOf(buildVersion, ".", 2));
            } else {
                fullVersionText = fullVersionText + " " + buildVersion;
            }
            e.gc.setFont(verFont);
            e.gc.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
            e.gc.drawText(fullVersionText, 290, 205, true);

            String inputStringDate = BuildVersion.getInstance().getBuildDate();
            String outputStringDate = "";
            SimpleDateFormat inputFormat = null;
            SimpleDateFormat outputFormat = null;

            if (inputStringDate.matches("^\\d{4}/\\d{1,2}/\\d{1,2}\\s\\d{1,2}:\\d{2}:\\d{2}.\\d{3}$")) {
                inputFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss.SSS");
            }
            if (inputStringDate.matches("^\\d{4}-\\d{1,2}-\\d{1,2}\\_\\d{1,2}-\\d{2}-\\d{2}$")) {
                inputFormat = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
            }
            if (inputStringDate.matches("^\\d{4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}.\\d{2}.\\d{2}$")) {
                inputFormat = new SimpleDateFormat("yyyy-MM-dd hh.mm.ss");
            }
            outputFormat = new SimpleDateFormat("MMMM d, yyyy hh:mm:ss");
            try {
                if (inputFormat != null) {
                    Date date = inputFormat.parse(inputStringDate);
                    outputStringDate = outputFormat.format(date);
                } else {
                    // If date isn't correspond to formats above just show date in origin format
                    outputStringDate = inputStringDate;
                }
            } catch (ParseException pe) {
                // Just show date in origin format
                outputStringDate = inputStringDate;
            }

            // try using the desired font size for the license text
            e.gc.setFont(licFont);
            e.gc.setForeground(display.getSystemColor(SWT.COLOR_WHITE));

            // if the text will not fit the allowed space
            while (!willLicenseTextFit(licenseText, e.gc)) {
                licFontSize--;
                if (licFont != null) {
                    licFont.dispose();
                }
                licFont = new Font(e.display, "Helvetica", licFontSize, SWT.NORMAL);
                e.gc.setFont(licFont);
            }

            e.gc.drawText(licenseText, 290, 275, true);

            String version = buildVersion;
            // If this is a Milestone or RC release, warn the user
            if (Const.RELEASE.equals(Const.ReleaseType.MILESTONE)) {
                version = BaseMessages.getString(PKG, "SplashDialog.DeveloperRelease") + " - " + version;
                drawVersionWarning(e);
            } else if (Const.RELEASE.equals(Const.ReleaseType.RELEASE_CANDIDATE)) {
                version = BaseMessages.getString(PKG, "SplashDialog.ReleaseCandidate") + " - " + version;
            } else if (Const.RELEASE.equals(Const.ReleaseType.PREVIEW)) {
                version = BaseMessages.getString(PKG, "SplashDialog.PreviewRelease") + " - " + version;
            } else if (Const.RELEASE.equals(Const.ReleaseType.GA)) {
                version = BaseMessages.getString(PKG, "SplashDialog.GA") + " - " + version;
            }
            String buildDate = BaseMessages.getString(PKG, "SplashDialog.BuildDate") + " " + outputStringDate;
            // use the same font/size as the license text
            e.gc.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
            e.gc.drawText(version, 290, 235, true);
            e.gc.drawText(buildDate, 290, 250, true);
        }
    });

    splash.addDisposeListener(new DisposeListener() {
        public void widgetDisposed(DisposeEvent arg0) {
            kettle_image.dispose();
            kettle_icon.dispose();
            exclamation_image.dispose();
            verFont.dispose();
            licFont.dispose();
            devWarningFont.dispose();
            versionWarningForegroundColor.dispose();
            versionWarningBackgroundColor.dispose();
        }
    });
    Rectangle bounds = kettle_image.getBounds();
    int x = (displayBounds.width - bounds.width) / 2;
    int y = (displayBounds.height - bounds.height) / 2;

    splash.setSize(bounds.width, bounds.height);
    splash.setLocation(x, y);

    splash.open();

    TimerTask timerTask = new TimerTask() {

        @Override
        public void run() {
            try {
                splash.redraw();
                LogChannel.UI.logBasic("Redraw!");
            } catch (Throwable e) {
                // ignore.
            }
        }
    };
    final Timer timer = new Timer();
    timer.schedule(timerTask, 0, 100);

    splash.addDisposeListener(new DisposeListener() {
        public void widgetDisposed(DisposeEvent arg0) {
            timer.cancel();
        }
    });
}