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.netflix.aegisthus.io.sstable.SSTableColumnScanner.java

private String keyToString(byte[] rowKey) {
    if (rowKey == null) {
        return "null";
    }//from  www . j  av  a  2s  . c  o m

    String str = BytesType.instance.getString(ByteBuffer.wrap(rowKey));
    return StringUtils.left(str, 32);
}

From source file:io.hops.hopsworks.common.dao.user.security.audit.AccountAuditFacade.java

private String extractUserAgent(HttpServletRequest httpServletRequest) {
    String userAgent = httpServletRequest.getHeader("User-Agent");
    if (userAgent == null || userAgent.isEmpty()) {
        return "Unknown User-Agent";
    }/*from  w w w .java 2  s. c o m*/

    return StringUtils.left(userAgent, 255);
}

From source file:com.sonicle.webtop.core.versioning.SqlUpgradeScript.java

private void readFile(InputStreamReader readable, boolean flatNewLines) throws IOException {
    this.statements = new ArrayList<>();
    StringBuilder sb = null, sbsql = null;
    String lines[] = null;//from w  ww . ja  va 2s  .c  o m

    Scanner s = new Scanner(readable);
    s.useDelimiter("(;( )?(\r)?\n)");
    //s.useDelimiter("(;( )?(\r)?\n)|(--\n)");
    while (s.hasNext()) {
        String block = s.next();
        block = StringUtils.replace(block, "\r", "");
        if (!StringUtils.isEmpty(block)) {
            // Remove remaining ; at the end of the block (only if this block is the last one)
            if (!s.hasNext() && StringUtils.endsWith(block, ";"))
                block = StringUtils.left(block, block.length() - 1);

            sb = new StringBuilder();
            sbsql = new StringBuilder();
            lines = StringUtils.split(block, "\n");
            for (String line : lines) {
                if (AnnotationLine.matches(line)) {
                    if (DataSourceAnnotationLine.matches(line)) {
                        statements.add(new DataSourceAnnotationLine(line));
                    } else if (IgnoreErrorsAnnotationLine.matches(line)) {
                        statements.add(new IgnoreErrorsAnnotationLine(line));
                    } else if (RequireAdminAnnotationLine.matches(line)) {
                        statements.add(new RequireAdminAnnotationLine(line));
                    } else {
                        throw new IOException("Bad line: " + line);
                    }
                } else if (CommentLine.matches(line)) {
                    sb.append(line);
                    sb.append("\n");
                } else {
                    sbsql.append(StringUtils.trim(line));
                    sbsql.append(" ");
                    if (!flatNewLines)
                        sbsql.append("\n");
                }
            }
            if (sb.length() > 0)
                statements.add(new CommentLine(StringUtils.removeEnd(sb.toString(), "\n")));
            if (sbsql.length() > 0)
                statements.add(new SqlLine(StringUtils.removeEnd(sbsql.toString(), "\n")));
        }
    }
}

From source file:net.sf.dynamicreports.examples.complex.applicationform.ApplicationFormDesign.java

private HorizontalListBuilder textCell(String text, int size) {
    HorizontalListBuilder list = cmp.horizontalList();
    String cellText = StringUtils.rightPad(text, size);
    cellText = StringUtils.left(cellText, size);
    for (char character : cellText.toCharArray()) {
        TextFieldBuilder<String> cell = cmp.text(String.valueOf(character)).setStyle(cellStyle)
                .setFixedDimension(cellWidth, cellHeight);
        list.add(cell);/*from  w  w  w  . j a  v a 2 s .com*/
    }
    return list;
}

From source file:com.bellman.bible.android.control.page.PageControl.java

/** 
 * Get page title including info about key/verse
 * Return it in 1 or 2 parts allowing it to be split over 2 lines
 * /*from  ww w.  j a v a 2  s.c o m*/
 * @return
 */
public String[] getCurrentPageTitleParts() {
    String[] retVal = new String[2];
    try {
        CurrentPage currentPage = ControlFactory.getInstance().getCurrentPageControl().getCurrentPage();
        if (currentPage != null) {
            if (currentPage.getSingleKey() != null) {
                Key key = currentPage.getSingleKey();
                // verses are special - show book at top and verse below
                if (key instanceof Verse) {
                    Verse verse = (Verse) key;
                    Versification v11n = verse.getVersification();
                    retVal[0] = StringUtils.left(v11n.getShortName(verse.getBook()), 6);

                    StringBuilder verseText = new StringBuilder();
                    verseText.append(verse.getChapter());
                    int verseNo = verse.getVerse();
                    if (verseNo > 0) {
                        verseText.append(":").append(verseNo);
                    }
                    retVal[1] = verseText.toString();
                } else {
                    // handle all non verse keys in a generic way
                    String title = key.getName();
                    // favour correct capitalisation because it looks better and is narrower so more fits in
                    if (ABStringUtils.isAllUpperCaseWherePossible(title)) {
                        // Books like INSTITUTES need corrected capitalisation
                        title = WordUtils.capitalizeFully(title);
                    }
                    String[] parts = titleSplitter.split(title);
                    retVal = ArrayUtils.subarray(parts, 0, 2);
                }
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Error getting page title", e);
    }
    return retVal;
}

From source file:de.micromata.genome.util.types.DateUtils.java

/**
 * Parses the h hmm to minutes./*from   w  w  w . j a v  a 2s . c o m*/
 *
 * @param time Zeitangabe der Form "1223". Minimalwert "0000", Maximalwert "2400".
 * @return Minutenangabe der Tageszeit.
 */
public static int parseHHmmToMinutes(String time) {
    Validate.notEmpty(time, "time is empty");

    try {
        Validate.isTrue(time.length() == 4, "time string expected to be 4 digits, but was ", time);

        String hoursPart = StringUtils.left(time, 2);
        String minutesPart = StringUtils.right(time, 2);

        int hours;
        int minutes;

        hours = Integer.parseInt(hoursPart);
        Validate.isTrue(hours >= 0, "hours negative");
        Validate.isTrue(hours <= 24, "hours too big");

        minutes = Integer.parseInt(minutesPart);
        Validate.isTrue(minutes >= 0, "minutes negative");
        Validate.isTrue(minutes <= 60, "minutes too big");

        final int result = hours * 60 + minutes;
        Validate.isTrue(result <= 24 * 60, "result too big");
        return result;
    } catch (Exception e) {
        throw new RuntimeException("Error parsing time string '" + time + "': " + e);
    }
}

From source file:com.music.service.PieceService.java

private Piece savePiece(ScoreContext ctx, byte[] mp3, byte[] midi) {
    Piece piece = new Piece();
    piece.setNewlyCreated(true);// w  w w . j  a  va  2  s. c o  m
    piece.setGenerationTime(new DateTime());
    piece.setTitle(ctx.getScore().getTitle());
    piece.setKeyNote(ctx.getKeyNote());
    piece.setMeasures(ctx.getMeasures());
    piece.setNormalizedMeasureSize(ctx.getNormalizedMeasureSize());
    piece.setTempo((int) ctx.getScore().getTempo());
    piece.setNoteLengthCoefficient(ctx.getNoteLengthCoefficient());
    piece.setScale(ctx.getScale());
    piece.setAlternativeScale(ctx.getAlternativeScale());
    piece.setUpBeatLength(ctx.getUpBeatLength());
    piece.setMetreNumerator(ctx.getMetre()[0]);
    piece.setMetreDenominator(ctx.getMetre()[1]);
    piece.setMainInstrument(ctx.getParts().get(PartType.MAIN).getInstrument());
    piece.setVariation(ctx.getVariation());
    piece.setParts(joiner.join(ctx.getParts().keySet()));
    piece.setAlgorithmVersion(algorithmVersion);

    piece.getIntermediateDecisions().setDullBass(ctx.isDullBass());
    piece.getIntermediateDecisions().setFourToTheFloor(ctx.isFourToTheFloor());
    piece.getIntermediateDecisions().setSimplePhrases(ctx.isSimplePhrases());
    piece.getIntermediateDecisions().setAccompaniment(ctx.getParts().containsKey(PartType.ACCOMPANIMENT));
    piece.getIntermediateDecisions().setDrums(ctx.getParts().containsKey(PartType.PERCUSSIONS));
    piece.getIntermediateDecisions()
            .setClassical(ctx.getParts().get(PartType.MAIN).getInstrument() == Instruments.PIANO
                    && piece.getIntermediateDecisions().isAccompaniment());
    piece.getIntermediateDecisions().setTempoType(Tempo.forValue(piece.getTempo()));
    piece.getIntermediateDecisions().setElectronic(ctx.isElectronic());
    piece.getIntermediateDecisions().setDissonant(ctx.isDissonant());
    piece.getIntermediateDecisions().setOrnamented(ctx.isOrnamented());
    piece.getIntermediateDecisions().setVariations(StringUtils.left(joiner.join(ctx.getVariations()), 2000));

    Piece result = dao.persist(piece);

    try {
        fileStorageService.storeFile(getMp3FilePath(result.getId()), mp3);
        fileStorageService.storeFile(getMidiFilePath(result.getId()), midi);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    return result;
}

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

private void renderAtom(GWikiContext wikiContext, String title, String wikiPageHtmlContent, String createDate,
        String modifiedDate, String autor, List<GWikiElementInfo> children, boolean renderChilds) {
    XmlElement atom = feed("http://www.w3.org/2005/Atom").nest( //
            author((name(Xml.text(autor)))), //
            (title(Xml.text(title))), //
            (link(wikiContext.getWikiWeb().getWikiConfig().getPublicURL())), //
            (subtitle(Xml.text(""))), //
            (updated(Xml.text(modifiedDate))), //
            (entry((title(Xml.text(title))), //
                    (link(wikiContext.getRequest().getRequestURL().toString())), //
                    (updated(Xml.text(createDate))), //
                    (summary("html").nest(Xml.text(StringUtils.left(wikiPageHtmlContent, 100) + "[...]"))), //
                    (content("html").nest(Xml.text(wikiPageHtmlContent))), //
                    author((name(Xml.text(autor))))//
            )));/*ww  w  . j  a v a2s. c o m*/

    if (renderChilds == true) {
        atom.getChilds().addAll(renderAtomEntries(wikiContext, children));
    }

    wikiContext.append(atom.toString());
    wikiContext.flush();
}

From source file:com.sonicle.webtop.core.util.ZPushManager.java

private List<LastsyncRecord> parseLastsyncOutput(List<String> lines) {
    ArrayList<LastsyncRecord> items = new ArrayList<>();

    int lineNo = 0, dataLine = -1;
    for (String line : lines) {
        lineNo++;/*from  ww  w . j av  a2s . c om*/
        if (StringUtils.containsIgnoreCase(line, "Device id")
                && StringUtils.containsIgnoreCase(line, "Synchronized user")
                && StringUtils.containsIgnoreCase(line, "Last sync time")) {
            dataLine = lineNo + 2;
        }
        if ((dataLine != -1) && (lineNo >= dataLine) && !StringUtils.isBlank(StringUtils.trim(line))) {
            String[] tokens = StringUtils.split(line, " ", 3);
            String device = StringUtils.trim(tokens[0]);
            String user = StringUtils.trim(tokens[1]);
            String lastSync = StringUtils.trim(StringUtils.left(tokens[2], 16));
            items.add(new LastsyncRecord(device, user, "never".equalsIgnoreCase(lastSync) ? null : lastSync));
        }
    }
    return items;
}

From source file:de.gbv.ole.Marc21ToOleBulk.java

/**
 * Return the input without the tailing check digit.
 * // w  w  w .  ja  va 2 s .com
 * Example:
 * withoutCheckdigit("123456789X") = "123456789"
 * withoutCheckdigit("987654321")  = "98765432"
 * 
 * @param numberWithCheckdigit      -       number including check digit
 * @return number without check digit
 */
static final String withoutCheckdigit(final String numberWithCheckdigit) {
    return StringUtils.left(numberWithCheckdigit, numberWithCheckdigit.length() - 1);
}