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

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

Introduction

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

Prototype

public static String left(final String str, final int len) 

Source Link

Document

Gets the leftmost len characters of a String.

If len characters are not available, or the String is null , the String will be returned without an exception.

Usage

From source file:com.sonicle.webtop.core.app.DocEditorManager.java

public String buildDocumentKey(String documentUniqueId, long lastModifiedTime) {
    String s = documentUniqueId//from w ww . j a v a  2  s .co m
            + String.valueOf((lastModifiedTime > -1) ? lastModifiedTime : DateTimeUtils.now().getMillis());
    return StringUtils.left(AlgoUtils.md5Hex(s), 20);
}

From source file:net.sf.jsignpdf.Signer.java

/**
 * Sign the files//from www.  j av a  2s  . c om
 * 
 * @param anOpts
 */
private static void signFiles(SignerOptionsFromCmdLine anOpts) {
    final SignerLogic tmpLogic = new SignerLogic(anOpts);
    if (ArrayUtils.isEmpty(anOpts.getFiles())) {
        // we've used -lp (loadproperties) parameter
        if (!tmpLogic.signFile()) {
            exit(Constants.EXIT_CODE_ALL_SIG_FAILED);
        }
        return;
    }
    int successCount = 0;
    int failedCount = 0;

    for (final String wildcardPath : anOpts.getFiles()) {
        final File wildcardFile = new File(wildcardPath);

        File[] inputFiles;
        if (StringUtils.containsAny(wildcardFile.getName(), '*', '?')) {
            final File inputFolder = wildcardFile.getAbsoluteFile().getParentFile();
            final FileFilter fileFilter = new AndFileFilter(FileFileFilter.FILE,
                    new WildcardFileFilter(wildcardFile.getName()));
            inputFiles = inputFolder.listFiles(fileFilter);
            if (inputFiles == null) {
                continue;
            }
        } else {
            inputFiles = new File[] { wildcardFile };
        }
        for (File inputFile : inputFiles) {
            final String tmpInFile = inputFile.getPath();
            if (!inputFile.canRead()) {
                failedCount++;
                System.err.println(RES.get("file.notReadable", new String[] { tmpInFile }));
                continue;
            }
            anOpts.setInFile(tmpInFile);
            String tmpNameBase = inputFile.getName();
            String tmpSuffix = ".pdf";
            if (StringUtils.endsWithIgnoreCase(tmpNameBase, tmpSuffix)) {
                tmpSuffix = StringUtils.right(tmpNameBase, 4);
                tmpNameBase = StringUtils.left(tmpNameBase, tmpNameBase.length() - 4);
            }
            final StringBuilder tmpName = new StringBuilder(anOpts.getOutPath());
            tmpName.append(anOpts.getOutPrefix());
            tmpName.append(tmpNameBase).append(anOpts.getOutSuffix()).append(tmpSuffix);
            String outFile = anOpts.getOutFile();
            if (outFile == null)
                anOpts.setOutFile(tmpName.toString());
            if (tmpLogic.signFile()) {
                successCount++;
            } else {
                failedCount++;
            }

        }
    }
    if (failedCount > 0) {
        exit(successCount > 0 ? Constants.EXIT_CODE_SOME_SIG_FAILED : Constants.EXIT_CODE_ALL_SIG_FAILED);
    }
}

From source file:info.magnolia.integrationtests.uitest.SecurityAppUITest.java

private String getHierarchicalPath(String name) {
    final String lcName = name.toLowerCase();
    if (lcName.length() < 3) {
        return "/" + name;
    }/*from  w w  w  . j a v a  2  s .  com*/
    return "/" + String.valueOf(lcName.charAt(0)) + "/" + StringUtils.left(lcName, 2) + "/" + name;
}

From source file:de.micromata.genome.gwiki.plugin.rssfeed_1_0.filter.RssFeedFilter.java

private Collection<XmlNode> renderAtomEntries(GWikiContext wikiContext, List<GWikiElementInfo> children) {
    List<XmlNode> childrenNodes = new ArrayList<XmlNode>();
    for (GWikiElementInfo child : children) {

        GWikiElement element = wikiContext.getWikiWeb().findElement(child.getId());
        GWikiArtefakt<?> artefakt = element.getPart("MainPage");

        if (artefakt instanceof GWikiWikiPageArtefakt) {
            GWikiWikiPageArtefakt wikiPageArtefakt = (GWikiWikiPageArtefakt) artefakt;
            String pageContent = getPageContent(wikiContext, wikiPageArtefakt);

            // DateFormat dfmt = new SimpleDateFormat("EE, d MMM yyyy hh:mm:ss +0100", Locale.ENGLISH);
            String createDate = formatDate(child.getCreatedAt());
            XmlNode c = entry( //
                    title(Xml.text(child.getTitle())), //
                    (link(wikiContext.localUrl(child.getId()))), //
                    (updated(Xml.text(createDate))), // TODO falsches Datum
                    (summary("html").nest(//
                            Xml.text(StringUtils.left(pageContent, 100) + "[...]"))),
                    (content("html").nest(Xml.text(pageContent))), //
                    (author(Xml.text(child.getCreatedBy()))));
            childrenNodes.add(c);/*from w  w w . j av  a 2 s. c  o m*/
        }
    }
    return childrenNodes;
}

From source file:com.jeans.iservlet.service.rest.impl.SoftwareRestServiceImpl.java

@Override
@Transactional/*from  www . j  a  va2s . c om*/
public SoftwareResource[] update(SoftwareResource resource) {
    SoftwareResource[] updates = new SoftwareResource[2];
    if (resource.getId() < 0) {
        updates[UPDATED] = ResourceFactory.createEmptyResource(SoftwareResource.class);
        updates[ORIGIN] = ResourceFactory.createEmptyResource(SoftwareResource.class);
        BeanUtils.copyProperties(resource, updates[UPDATED]);
        BeanUtils.copyProperties(resource, updates[ORIGIN]);
        updates[UPDATED].setId(0);
    } else {
        Software sw = swDao.getById(Software.class, resource.getId());
        if (null != sw && sw.getState() != AssetConstants.DISUSE) {
            AssetChangeLog acl = new AssetChangeLog(sw, sw.getState(), sw.getState(), getRequest());
            updates[ORIGIN] = ResourceFactory.createResource(Software.class, SoftwareResource.class, sw);
            // 1. name?
            if (!StringUtils.isBlank(resource.getName())) {
                sw.setName(StringUtils.left(StringUtils.trimToEmpty(resource.getName()), 32));
            }
            // 2. catalog?
            byte catalog = resource.getCatalog();
            if ((catalog >= AssetConstants.OPERATING_SYSTEM_SOFTWARE
                    && catalog <= AssetConstants.APPLICATION_SOFTWARE)
                    || catalog == AssetConstants.OTHER_SOFTWARE) {
                sw.setCatalog(catalog);
            }
            // 3. vender[32], modelOrVersion[64], assetUsage[255], comment[255], license[64], null?
            if (null != resource.getVendor()) {
                sw.setVendor(StringUtils.left(StringUtils.trimToEmpty(resource.getVendor()), 32));
            }
            if (null != resource.getModelOrVersion()) {
                sw.setModelOrVersion(
                        StringUtils.left(StringUtils.trimToEmpty(resource.getModelOrVersion()), 64));
            }
            if (null != resource.getAssetUsage()) {
                sw.setAssetUsage(StringUtils.left(StringUtils.trimToEmpty(resource.getAssetUsage()), 255));
            }
            if (null != resource.getComment()) {
                sw.setComment(StringUtils.left(StringUtils.trimToEmpty(resource.getComment()), 255));
            }
            if (null != resource.getLicense()) {
                sw.setLicense(StringUtils.left(StringUtils.trimToEmpty(resource.getLicense()), 64));
            }
            // 4. purchaseTimenull?
            if (null != resource.getPurchaseTime()) {
                sw.setPurchaseTime(resource.getPurchaseTime());
            }
            // 5. quantity?0?
            if (resource.getQuantity() > 0) {
                sw.setQuantity(resource.getQuantity());
            }
            // 6. costnull?0?
            if (null != resource.getCost() && resource.getCost().doubleValue() >= 0) {
                sw.setCost(resource.getCost());
            }
            // 7. state0=, 1=, 3=
            byte state = resource.getState();
            if (state == AssetConstants.IN_USE || state == AssetConstants.IDLE
                    || state == AssetConstants.DISUSE) {
                acl.setNewState(state);
                sw.setState(state);
            }
            // 8. softwareType?
            byte softwareType = resource.getSoftwareType();
            if (softwareType >= AssetConstants.COMMERCIAL_SOFTWARE
                    && softwareType <= AssetConstants.OTHER_TYPE_SOFTWARE) {
                sw.setSoftwareType(softwareType);
            }
            // 9. expiredTimenull?
            if (null != resource.getExpiredTime()) {
                sw.setExpiredTime(resource.getExpiredTime());
            }
            swDao.update(sw);
            if (acl.isValid()) {
                aclDao.save(acl);
            }
            updates[UPDATED] = ResourceFactory.createResource(Software.class, SoftwareResource.class, sw);
        }
    }
    return updates;
}

From source file:com.thruzero.common.core.utils.XmlUtils.java

public static String getParentPath(final String xPath) {
    int indexOfLastSlash = StringUtils.lastIndexOf(xPath, "/");

    if (indexOfLastSlash > 0) {
        return StringUtils.left(xPath, indexOfLastSlash);
    }// ww w .  j  a  v a 2s . c om

    return null;
}

From source file:com.bellman.bible.android.control.readingplan.ReadingPlanControl.java

public String getShortTitle() {
    return StringUtils.left(getCurrentPlanCode(), 8);
}

From source file:Heuristics.TermLevelHeuristics.java

public boolean isFirstLetterCapitalized(String termOrig) {
    return (StringUtils.isAllUpperCase(StringUtils.left(termOrig, 1))) ? true : false;
}

From source file:Heuristics.TermLevelHeuristics.java

public boolean isImmediatelyPrecededByANegation(String status, String termOrig) {
    termHeuristic = termHeuristic.toLowerCase();
    int indexTerm = StringUtils.indexOf(status, termHeuristic);
    String[] temp = StringUtils.left(status, indexTerm).split(" ");

    //if the array is empty it means that the term is the first of the status;
    if (temp.length == 0) {
        return false;
        //in this case the term is the second in the status. If the previous one is a negative word, return true (as in "like" being preceded by "don't") 
    } else if (temp.length == 1) {
        boolean res = HLoader.getSetNegations().contains(temp[0]) ? true : false;
        return res;
        //in this case the term is preceded by many other terms. We just check the three previous ones.    
    } else if (temp.length == 2) {
        if (HLoader.getSetNegations().contains(temp[temp.length - 1])) {
            return true;
        }/*from w ww  .  j ava 2s  .  com*/
        //in the case of "don't really like", return true
        if (HLoader.getMapH3().containsKey(temp[temp.length - 1])
                & HLoader.getSetNegations().contains(temp[temp.length - 2])) {
            return true;
        }
        //in the case of "not the hottest", return true
        String concat = temp[0] + " " + temp[1];
        boolean res = (HLoader.getSetNegations().contains(concat)) ? true : false;
        return res;
    } else if (temp.length > 2) {
        if (HLoader.getSetNegations().contains(temp[temp.length - 1])) {
            return true;
        }
        if (HLoader.getMapH3().containsKey(temp[temp.length - 1])
                & HLoader.getSetNegations().contains(temp[temp.length - 2])) {
            return true;
        }
        //in the case of "not the hottest", return true
        String concat = temp[temp.length - 2] + " " + temp[temp.length - 1];
        boolean res = (HLoader.getSetNegations().contains(concat)) ? true : false;
        return res;
    }
    return false;
}

From source file:com.ibm.dbwkl.request.internal.LoggingHandler.java

@Override
public STAFResult execute() {
    StringBuilder resultString = new StringBuilder();

    // user for db logger
    String logdbuser = getRequestOption(Options.DB_USER);

    // password for db logger
    String logdbpassword = getRequestOption(Options.DB_PASSWORD);

    // URL for db logger
    String logdburl = getRequestOption(Options.DB_URL);

    if (hasRequestOption(Options.LOG_LOGTEST)) {
        for (int i = 0; i <= 25; i++) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                //ignore
            }//from  w  w w .ja v  a 2  s  .  c  om
            Logger.log("LOGTEST:" + i, LogLevel.Debug);
        }
        return new STAFResult(STAFResult.Ok, "Logtest at Loglevel Debug executed!");
    }

    /*
     * everything went fine, thus do the changes and hope that all values are allowed
     */

    // level
    if (hasRequestOption(Options.LOG_LEVEL)) {
        String level = getRequestOption(Options.LOG_LEVEL);
        try {
            Logger.logLevel = LogLevel.getLevel(level);
            resultString.append("Log Level set to " + level + "\n");
        } catch (Exception e) {
            return new STAFResult(STAFResult.InvalidValue, "The value '" + level
                    + "' is not allowed as log level. Use one of the following instead: Debug Info Warning Error");
        }
    }

    // details
    if (hasRequestOption(Options.LOG_DETAILS)) {
        String details = getRequestOption(Options.LOG_DETAILS);
        try {
            Logger.details = new Boolean(details).booleanValue();
            resultString.append("Log Details now " + (Logger.details == true ? "ON" : "OFF") + "\n");
        } catch (Exception e) {
            return new STAFResult(STAFResult.InvalidValue, "The value '" + details
                    + "' is not allowed as detailed logging settings. Use either true or false as value.");
        }
    }

    // Cleaning the logger
    if (hasRequestOption(Options.LOG_CLEAN)) {
        String clean = getRequestOption(Options.LOG_CLEAN).trim();

        try {
            ILoggerService logger = getLoggerByName(clean);
            if (logger == null)
                return new STAFResult(STAFResult.DoesNotExist, "Logger could not be found!");

            logger.term();
            logger.clean();
            Logger.registeredLoggers.remove(logger);

            logger = logger.getClass().newInstance();
            Logger.addLogger(logger);

            resultString.append("Logger " + clean + " has been cleaned!");

        } catch (Exception e) {
            return new STAFResult(STAFResult.InvalidValue, "The logger '" + clean
                    + "' is unknown. Use one of the following: htmllogger filelogger dblogger sysout livelog livelogreceiver");
        }
    }

    // remove logger
    else if (hasRequestOption(Options.LOG_REMOVE)) {
        String remove = getRequestOption(Options.LOG_REMOVE).trim();

        try {
            if (remove.equalsIgnoreCase("LIVELOG")) {
                LiveLogger.getInstance().term();
                Logger.registeredLoggers.remove(LiveLogger.getInstance());
                resultString.append("Logger " + remove + " has been removed \n");
            } else {
                ILoggerService logger = getLoggerByName(remove);

                if (logger == null)
                    return new STAFResult(STAFResult.DoesNotExist, "Logger could not be found!");

                logger.term();
                Logger.registeredLoggers.remove(logger);

                resultString.append("Logger has been removed!");
            }

        } catch (Exception e) {
            return new STAFResult(STAFResult.InvalidValue,
                    "The logger '" + remove + "' to be removed is unknown.");
        }
    }

    // add logger
    else if (hasRequestOption(Options.LOG_ADD)) {
        String add = getRequestOption(Options.LOG_ADD);

        if (add.equalsIgnoreCase("FILELOGGER"))
            try {
                Logger.addLogger(new TextLogger());
            } catch (IOException e1) {
                return new STAFResult(STAFResult.JavaError, "Exception occurs while adding a FileLogger.");
            }
        else if (add.equalsIgnoreCase("DBLOGGER")) {
            try {
                Logger.addLogger(new DatabaseLogger(logdbuser, logdbpassword, logdburl));
            } catch (IOException e) {
                return new STAFResult(STAFResult.JavaError,
                        "Exception occurs while adding a DBLogger: " + e.getMessage());
            } catch (InterruptedException e) {
                //
            }
        }

        else if (add.equalsIgnoreCase("HTMLLOGGER"))
            try {
                Logger.addLogger(new HTMLLogger());
            } catch (IOException e) {
                return new STAFResult(STAFResult.JavaError, "Exception occurs while adding a HTMLLogger.");
            }
        else if (add.equalsIgnoreCase("LIVELOG")) {
            if (hasRequestOption(Options.SOCKET_HOST)) {
                if (getRequestOption(Options.SOCKET_HOST).length() != 0) {
                    LiveLogger liveLogger = LiveLogger.getInstance();
                    if (!Logger.getCopyOfLoggers().contains(liveLogger))
                        Logger.addLogger(liveLogger);
                    liveLogger.openServer(getRequestOption(Options.SOCKET_HOST).trim());
                    return new STAFResult(STAFResult.Ok,
                            "LiveLogger added, it will now accept a live logging connection!");
                }
            }
            Logger.log("Adding LiveLog not possible: Invalid Host", LogLevel.Error);
            return new STAFResult(STAFResult.JavaError, "Adding LiveLog not possible: Invalid Host");
        }

        else {
            Logger.log("Adding Logger failed: no such logger to add found: " + add, LogLevel.Error);
            return new STAFResult(STAFResult.JavaError,
                    "Adding Logger failed: no such logger to add found: " + add);
        }
        resultString.append("Logger " + add + " has been added \n");
    }

    else if (hasRequestOption(Options.LOG_SCHEMA)) {
        String xsd = null;
        try {
            xsd = XMLSerializer.createXMLSchema(LoggerEntry.class);
        } catch (IOException e) {
            Logger.log(e.getMessage(), LogLevel.Error);
            return new STAFResult(STAFResult.JavaError, e.getMessage());
        } catch (JAXBException e) {
            Logger.log(e.getMessage(), LogLevel.Error);
            return new STAFResult(STAFResult.JavaError, e.getMessage());
        }

        if (xsd != null)
            return new STAFResult(STAFResult.Ok, xsd);

        return new STAFResult(STAFResult.JavaError, "Error while creating the Schema");
    }

    // LIST shows logs on the console
    // schema:
    //      LIST <what> [FILTER <filter>] [COLUMNS <columns>]
    //          <what> = { , n} (empty=all, n=last n)
    //          <filter> = {LEVEL={DEBUG, INFO, WARNING, ERROR}*;REQID=<reqid>}
    //          <columns> = {REQUEST, THREAD, LOGLEVEL, MESSAGE}
    else if (hasRequestOption(Options.LOG_LIST)) {
        //read <what>
        String listValue = getRequestOption(Options.LOG_LIST);
        //the number of latest entries to retrieve
        int n = 0;
        if (listValue.equalsIgnoreCase("")) {
            //when n<=0, all entries are retrieved
            n = 0;
        } else {
            try {
                n = Integer.parseInt(listValue);
            } catch (NumberFormatException e) {
                return new STAFResult(STAFResult.InvalidValue,
                        "List option needs to be a positive number or empty");
            }
            if (n <= 0) {
                return new STAFResult(STAFResult.InvalidValue,
                        "List option needs to be a positive number or empty");
            }
        }

        //read <filter>
        String levels[] = null;
        int reqid = 0;
        if (hasRequestOption(Options.LOG_LIST_FILTER)) {
            String filter = getRequestOption(Options.LOG_LIST_FILTER).toLowerCase();
            StringTokenizer tokenizer = new StringTokenizer(filter, ";");
            while (tokenizer.hasMoreElements()) {
                String option = (String) tokenizer.nextElement();
                // an option is of the form key=value
                if (option.contains("=")) {
                    String key = option.substring(0, option.indexOf("="));
                    //read LEVEL={DEBUG,INFO,WARNING,ERROR}*
                    if (key.equalsIgnoreCase("level")) {
                        levels = option.substring(option.indexOf("=") + 1).split(",");
                        //Check if the given levels are supported.
                        if (!StringUtility.arrayContainsOnlyIgnoreCase(levels, LogLevel.Debug.toString().trim(),
                                LogLevel.Warning.toString().trim(), LogLevel.Error.toString().trim(),
                                LogLevel.Info.toString().trim())) {
                            return new STAFResult(STAFResult.InvalidValue,
                                    "Supporting only Log Levels: " + LogLevel.Debug.toString().trim() + ","
                                            + LogLevel.Warning.toString().trim() + ","
                                            + LogLevel.Error.toString().trim() + ","
                                            + LogLevel.Info.toString().trim());
                        }
                        //read REQID=<reqid>      
                    } else if (key.equals("reqid")) {
                        try {
                            reqid = Integer.parseInt(option.substring(option.indexOf("=") + 1));
                        } catch (NumberFormatException e) {
                            return new STAFResult(STAFResult.InvalidValue,
                                    "REQID needs to be a positive number.");
                        }
                        if (reqid <= 0) {
                            return new STAFResult(STAFResult.InvalidValue,
                                    "REQID needs to be a positive number.");
                        }
                    } else {
                        //option is not level= or reqid=
                        return new STAFResult(STAFResult.InvalidValue,
                                "Invalid option in the filter: " + option);
                    }
                } else {
                    //option doesn't have '='
                    return new STAFResult(STAFResult.InvalidValue,
                            "Invalid requestOptions in the filter: " + option);
                }
            }
        }

        //read <columns>
        String[] cols = null;
        if (hasRequestOption(Options.LOG_LIST_COL)) {
            cols = getRequestOption(Options.LOG_LIST_COL).toLowerCase().split(",");
            if (!StringUtility.arrayContainsOnlyIgnoreCase(cols, "request", "thread", "level", "message"))
                return new STAFResult(STAFResult.InvalidValue,
                        "Supporting only Columns: Request, Thread, Level, Message.");
        }

        // filter the entries accordingly
        List<LoggerEntry> logEntries = null;

        if (levels == null || levels.length == 0) {
            if (reqid == 0) {
                logEntries = Logger.getLogEntries(n);
            } else {
                logEntries = Logger.getLogEntries(n, reqid);
            }
        } else {
            if (reqid == 0) {
                logEntries = Logger.getLogEntries(n, levels);
            } else {
                logEntries = Logger.getLogEntries(n, levels, reqid);
            }
        }

        // print the lines, with selected columns.
        String ALLCOLUMNS[] = { "Request", "Thread", "Level", "Message" };
        String formats[] = { "%1$-8s", " %2$-12s", " %3$-7s", " %4$-100s" };

        //if no columns is set, display all columns
        if (cols == null || cols.length == 0) {
            cols = ALLCOLUMNS;
        }

        //check is one of the four columns exists, and construct the format string.
        boolean[] colExists = new boolean[ALLCOLUMNS.length];
        String format = "";

        for (int i = 0; i < ALLCOLUMNS.length; i++) {
            if (StringUtility.arrayContainsIgnoreCase(cols, ALLCOLUMNS[i])) {
                colExists[i] = true;
                format += formats[i];
            }
        }
        format += "\n";

        //print the table head
        resultString.append(String.format(format, colExists[0] ? "Request" : "", colExists[1] ? "Thread" : "",
                colExists[2] ? "Level" : "", colExists[3] ? "Message" : ""));

        resultString.append(String.format(format, colExists[0] ? "-------" : "", colExists[1] ? "------" : "",
                colExists[2] ? "-----" : "", colExists[3] ? "-------" : ""));

        //print the log entries
        for (LoggerEntry logEntry : logEntries) {

            if (colExists[3]) {
                //number of chars per row in the message column
                int charsPerRow = 100;
                //in case the message contains multiple lines.
                String msg = logEntry.getMessage();
                String[] lines = msg.split("\\n");
                for (int i = 0; i < lines.length; i++) {
                    //other columns should only appear once on the first row.
                    String formatedString = String.format(format,
                            (i == 0 && colExists[0]) ? logEntry.getRequestName() : "",
                            (i == 0 && colExists[1]) ? logEntry.getThread() : "",
                            (i == 0 && colExists[2]) ? logEntry.getLevel() : "",
                            StringUtils.left(lines[i], charsPerRow));
                    resultString.append(formatedString);

                    //if the line is longer than 'charsPerRow', split it into multiple rows
                    if (lines[i].length() > charsPerRow) {
                        //cut every 'charsPerRow' chars out, and put it in a new row.
                        String txt = "";
                        int j = 1;
                        while ((txt = StringUtils.mid(lines[i], charsPerRow * j, charsPerRow)).length() != 0) {
                            resultString.append(String.format(format, "", "", "", txt));
                            j++;
                        }
                    }
                }
            } else {
                String formatedString = String.format(format, colExists[0] ? logEntry.getRequestName() : "",
                        colExists[1] ? logEntry.getThread() : "", colExists[2] ? logEntry.getLevel() : "", "");
                resultString.append(formatedString);
            }
        }

    }

    return new STAFResult(STAFResult.Ok, resultString.toString());
}