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

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

Introduction

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

Prototype

public static String left(String str, int len) 

Source Link

Document

Gets the leftmost len characters of a String.

Usage

From source file:net.sf.sail.webapp.dao.user.impl.HibernateUserDao.java

/**
 * Capitalizes the first letter of a given String
 * //from  w ww  . ja  va  2s.co  m
 * @param string
 * @return String
 */
private String capitalizeFirst(String string) {
    return StringUtils.upperCase(StringUtils.left(string, 1)) + StringUtils.right(string, string.length() - 1);
}

From source file:com.cloudbees.jenkins.plugins.amazonecs.ECSService.java

AmazonECSClient getAmazonECSClient() {
    final AmazonECSClient client;

    ProxyConfiguration proxy = Jenkins.getInstance().proxy;
    ClientConfiguration clientConfiguration = new ClientConfiguration();
    if (proxy != null) {
        clientConfiguration.setProxyHost(proxy.name);
        clientConfiguration.setProxyPort(proxy.port);
        clientConfiguration.setProxyUsername(proxy.getUserName());
        clientConfiguration.setProxyPassword(proxy.getPassword());
    }//from  w w w  .j  av a  2  s .com

    AmazonWebServicesCredentials credentials = getCredentials(credentialsId);
    if (credentials == null) {
        // no credentials provided, rely on com.amazonaws.auth.DefaultAWSCredentialsProviderChain
        // to use IAM Role define at the EC2 instance level ...
        client = new AmazonECSClient(clientConfiguration);
    } else {
        if (LOGGER.isLoggable(Level.FINE)) {
            String awsAccessKeyId = credentials.getCredentials().getAWSAccessKeyId();
            String obfuscatedAccessKeyId = StringUtils.left(awsAccessKeyId, 4)
                    + StringUtils.repeat("*", awsAccessKeyId.length() - (2 * 4))
                    + StringUtils.right(awsAccessKeyId, 4);
            LOGGER.log(Level.FINE, "Connect to Amazon ECS with IAM Access Key {1}",
                    new Object[] { obfuscatedAccessKeyId });
        }
        client = new AmazonECSClient(credentials, clientConfiguration);
    }
    client.setRegion(getRegion(regionName));
    LOGGER.log(Level.FINE, "Selected Region: {0}", regionName);
    return client;
}

From source file:com.googlecode.jmxtrans.model.output.RRDToolWriter.java

/**
 * rrd datasources must be less than 21 characters in length, so work to
 * make it shorter. Not ideal at all, but works fairly well it seems.
 *///from  w  w  w .  jav  a2s  .co m
public String getDataSourceName(String typeName, String attributeName, String entry) {
    String result;
    if (typeName != null) {
        result = typeName + attributeName + entry;
    } else {
        result = attributeName + entry;
    }

    if (attributeName.length() > 15) {
        String[] split = StringUtils.splitByCharacterTypeCamelCase(attributeName);
        String join = StringUtils.join(split, '.');
        attributeName = WordUtils.initials(join, INITIALS);
    }
    result = attributeName + DigestUtils.md5Hex(result);

    result = StringUtils.left(result, 19);

    return result;
}

From source file:com.sun.socialsite.util.UtilitiesModel.java

public static String left(String str, int length) {
    return StringUtils.left(str, length);
}

From source file:nc.noumea.mairie.appock.core.utility.AppockUtil.java

/**
 * Construit un texte tronqu s'il dpasse la longueur du texte indique
 * @param texte texte//w ww  .ja v a  2  s. c  o  m
 * @param longueurMaxTexte longueur max.
 * @param suffixeSiTronque suffixe  utiliser en fin de rsultat si le texte dpasse la longueur max.
 * @return texte tronqu
 */
public static String construitTexteTronque(String texte, int longueurMaxTexte, String suffixeSiTronque) {
    if (texte == null) {
        return null;
    }
    if (StringUtils.isBlank(texte)) {
        return "";
    }
    String result = StringUtils.trimToEmpty(texte);
    if (result.length() <= longueurMaxTexte) {
        return result;
    }
    return StringUtils.left(result, longueurMaxTexte) + ((suffixeSiTronque == null) ? "" : suffixeSiTronque);
}

From source file:net.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
 * /*  ww w.  j  ava 2  s .c  om*/
 * @return
 */
public String[] getCurrentPageTitleParts() {
    String[] retVal = new String[2];
    try {
        CurrentPage currentPage = CurrentPageManager.getInstance().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:com.timtripcony.AbstractDocumentMapModel.java

/**
 * Loads the object with settings based on the passed UNID:
 * <ul>// w w w .  j a  v a2 s . c o  m
 * <ol>
 * Whether or not it is a new Document
 * </ol>
 * <ol>
 * Whether or not the Document is deleted
 * </ol>
 * <ol>
 * Whether or not the Document is read only
 * </ol>
 * <ol>
 * Sets wrappedDoc as a DominoDocument object
 * </ol>
 * <ol>
 * Loads all fields into the object, omitting named fields, anything prefixed with "$", or with type "Error"
 * </ol>
 * </ul>
 * 
 * Extended by PW to allow specific fields to be ignored and to ensure empty fields are loaded as "" (empty String),
 * not "[]" (String version of empty Vector)
 * 
 * @param unid
 *            String UNID or Note ID relating to this Document (empty = new Document)
 */
public void load(final String unid) {
    setUnid(unid);
    Document doc = null;
    setNewNote(true); // Default to true
    setDeleted(false); // Default to false
    setReadOnly(false); // Default to false
    try {
        if (StringUtil.isNotEmpty(unid)) {
            try {
                doc = AppUtils.getDocumentByNoteID_Or_UNID(unid);
                setWrappedDoc(DominoDocument.wrap(AppUtils.getDataDbPath(), // database name
                        doc, // Document
                        null, // computeWithForm
                        null, // concurrency Mode
                        false, // allowDeletedDocs
                        null, // saveLinksAs
                        null)); // webQuerySaveAgent
                for (Object eachItem : doc.getItems()) {
                    if (eachItem instanceof Item) {
                        Item item = (Item) eachItem;
                        String itemName = item.getName();
                        // Certainly not a comprehensive list of items to skip
                        ArrayList<String> ignoreList = ArrayListUtil.stringToArrayList("MIME_Version");
                        String firstChar = StringUtils.left(itemName, 1);
                        if (!ignoreList.contains(itemName) && !StringUtils.equals(firstChar, "$")) {
                            // Item may be of type "Error"
                            if (item.getType() != Type.ERRORITEM.getValue()) {
                                Object itemValue = wrappedDoc.getValue(itemName);
                                setValue(itemName, itemValue);
                                if (itemValue instanceof Vector) {
                                    if ("[]".equals(itemValue.toString())) {
                                        setValue(itemName, new String(""));
                                    }
                                }
                            }
                        }
                    }
                }
                if (doc.isDeleted() || !doc.isValid()) {
                    setDeleted(true);
                }
                setNewNote(false);
            } catch (Throwable t) {
                AppUtils.handleException(t);
            }
        }
    } catch (Throwable t) {
        AppUtils.handleException(t);
    }
}

From source file:biblivre3.cataloging.bibliographic.BiblioBO.java

public MemoryFileDTO createFileLabelsPDF(ArrayList<LabelDTO> labels, LabelConfigDTO labelConfig) {
    Document document = new Document();
    final MemoryFileDTO file = new MemoryFileDTO();
    file.setFileName("biblivre_etiquetas_" + new Date().getTime() + ".pdf");
    try {/*from w  ww. j a  v a 2 s  .c o m*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.setPageSize(PageSize.A4);
        float verticalMargin = (297.0f - (labelConfig.getHeight() * labelConfig.getRows())) / 2;
        document.setMargins(7.15f * ApplicationConstants.MM_UNIT, 7.15f * ApplicationConstants.MM_UNIT,
                verticalMargin * ApplicationConstants.MM_UNIT, verticalMargin * ApplicationConstants.MM_UNIT);
        document.open();

        PdfPTable table = new PdfPTable(labelConfig.getColumns());
        table.setWidthPercentage(100f);
        PdfPCell cell;

        int i = 0;
        for (i = 0; i < labelConfig.getOffset(); i++) {
            cell = new PdfPCell();
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setFixedHeight(labelConfig.getHeight() * ApplicationConstants.MM_UNIT);
            table.addCell(cell);
        }

        for (LabelDTO ldto : labels) {
            PdfContentByte cb = writer.getDirectContent();

            String holdingSerial = String.valueOf(ldto.getHoldingSerial());
            while (holdingSerial.length() < 10) {
                holdingSerial = "0" + holdingSerial;
            }
            Barcode39 code39 = new Barcode39();
            code39.setExtended(true);
            code39.setCode(holdingSerial);
            code39.setStartStopText(false);

            Image image39 = code39.createImageWithBarcode(cb, null, null);
            if (labelConfig.getHeight() > 30.0f) {
                image39.scalePercent(110f);
            } else {
                image39.scalePercent(90f);
            }

            Paragraph para = new Paragraph();
            Phrase p1 = new Phrase(StringUtils.left(ldto.getAuthor(), 28) + "\n");
            Phrase p2 = new Phrase(StringUtils.left(ldto.getTitle(), 28) + "\n\n");
            Phrase p3 = new Phrase(new Chunk(image39, 0, 0));
            para.add(p1);
            para.add(p2);
            para.add(p3);

            cell = new PdfPCell(para);
            i++;
            cell.setNoWrap(true);
            cell.setFixedHeight(labelConfig.getHeight() * ApplicationConstants.MM_UNIT);
            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);

            Paragraph para2 = new Paragraph();
            Phrase p5 = new Phrase(ldto.getLocationA() + "\n");
            Phrase p6 = new Phrase(ldto.getLocationB() + "\n");
            Phrase p7 = new Phrase(ldto.getLocationC() + "\n");
            Phrase p8 = new Phrase(ldto.getLocationD() + "\n");
            Phrase p4 = new Phrase(ldto.getAssetHolding() + "\n");
            para2.add(p5);
            para2.add(p6);
            para2.add(p7);
            para2.add(p8);
            para2.add(p4);

            cell = new PdfPCell(para2);
            i++;
            cell.setFixedHeight(labelConfig.getHeight() * ApplicationConstants.MM_UNIT);
            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);
        }
        if ((i % labelConfig.getColumns()) != 0) {
            while ((i % labelConfig.getColumns()) != 0) {
                i++;
                cell = new PdfPCell();
                cell.setBorder(Rectangle.NO_BORDER);
                table.addCell(cell);
            }
        }
        document.add(table);
        writer.flush();
        document.close();
        file.setFileData(baos.toByteArray());
    } catch (Exception de) {
        System.out.println(de.getMessage());
    }
    return file;
}

From source file:com.thed.plugin.QtpZephyrInterceptor.java

/**
 * This method updates the Zbot agent real-time status to <b>'STATUS: Script Successfully Executed'</b> 
 * and makes a Webservice call to update testcase execution result to the server <br/>
 * @see {@link IZBotScriptLauncher#testcaseExecutionResult()}
 */// w ww  .jav  a  2  s  .c o m
public void testcaseExecutionResult() {
    if (testcaseBatchExecution.isParallelExecution()) {
        return;
    }
    if (currentTcExecutionResult == null) {
        try {
            System.out.println(" *********************** Execution Result is null, lets calculate it");
            if (type.equals("qtp")) {
                comments = outputPath;
                logger.info("**************** Output path is " + outputPath);
                currentTcExecutionResult = new Integer(getQTPTCResult(outputPath)); /* 1 = pass */
                File file = new File(outputPath + File.separator + "output.txt");
                if (util != null)
                    util.uploadAttachment(file, "releaseTestSchedule",
                            Long.parseLong(currentTestcaseExecution.getReleaseTestScheduleId()));
            } else {
                currentTcExecutionResult = new Integer(getSeleniumResult(outputPath)); /* 1 = pass */
            }
            comments += " \n Successfully executed on " + agent.getAgentHostAndIp();
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
            currentTcExecutionResult = new Integer(2);
            ; /* 2 = fail */
            comments += " \n Error in parsing response,  TC:" + currentTestcaseExecution.getTcId() + " on "
                    + agent.getAgentHostAndIp();
        }
    }
    status = currentTestcaseExecution.getTcId() + ": " + currentTestcaseExecution.getName()
            + " STATUS: Script Successfully Executed";

    if (currentTcExecutionResult != null) {
        comments = StringUtils.left(comments, 254);
        ScriptUtil.updateTestcaseExecutionResult(url, currentTestcaseExecution, currentTcExecutionResult,
                comments);
    }
}

From source file:com.funambol.foundation.items.dao.PIMNoteDAO.java

public void addItem(NoteWrapper nw) throws DAOException {
    if (log.isTraceEnabled()) {
        log.trace("PIMNoteDAO addItem begin");
    }//from  w  w  w  .ja  v  a  2  s  .  c o m

    Connection con = null;
    PreparedStatement ps = null;

    long id = 0;
    String sId = null;

    Timestamp lastUpdate = nw.getLastUpdate();
    if (lastUpdate == null) {
        lastUpdate = new Timestamp(System.currentTimeMillis());
    }

    try {

        // Looks up the data source when the first connection is created
        con = getUserDataSource().getRoutedConnection(userId);

        // calculate table row id
        sId = nw.getId();
        if (sId == null) { // ...as it should be
            sId = getNextID();
            nw.setId(sId);
        }
        id = Long.parseLong(sId);

        ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_NOTE);

        int k = 1;
        //
        // GENERAL
        //

        if (log.isTraceEnabled()) {
            log.trace("Preparing statement with ID " + id);
        }
        ps.setLong(k++, id);

        if (log.isTraceEnabled()) {
            log.trace("Preparing statement with user ID " + userId);
        }
        ps.setString(k++, userId);

        ps.setLong(k++, lastUpdate.getTime());
        ps.setString(k++, String.valueOf(Def.PIM_STATE_NEW));

        Note note = nw.getNote();

        ps.setString(k++, StringUtils.left(note.getSubject().getPropertyValueAsString(), SQL_SUBJECT_DIM));

        String textDescription = note.getTextDescription().getPropertyValueAsString();
        if (textDescription != null) {
            textDescription = textDescription.replace('\0', ' ');
        }
        String truncatedTextDescription = StringUtils.left(textDescription, SQL_TEXTDESCRIPTION_DIM);
        ps.setString(k++, truncatedTextDescription);

        ps.setString(k++,
                truncateCategoriesField(note.getCategories().getPropertyValueAsString(), SQL_CATEGORIES_DIM));
        ps.setString(k++, truncateFolderField(note.getFolder().getPropertyValueAsString(), SQL_FOLDER_DIM));

        Property color = note.getColor();
        Property height = note.getHeight();
        Property width = note.getWidth();
        Property top = note.getTop();
        Property left = note.getLeft();

        if (Property.isEmptyProperty(color)) {
            ps.setNull(k++, Types.INTEGER);
        } else {
            ps.setInt(k++, Integer.parseInt(color.getPropertyValueAsString()));
        }

        if (Property.isEmptyProperty(height)) {
            ps.setNull(k++, Types.INTEGER);
        } else {
            ps.setInt(k++, Integer.parseInt(height.getPropertyValueAsString()));
        }

        if (Property.isEmptyProperty(width)) {
            ps.setNull(k++, Types.INTEGER);
        } else {
            ps.setInt(k++, Integer.parseInt(width.getPropertyValueAsString()));
        }

        if (Property.isEmptyProperty(top)) {
            ps.setNull(k++, Types.INTEGER);
        } else {
            ps.setInt(k++, Integer.parseInt(top.getPropertyValueAsString()));
        }

        if (Property.isEmptyProperty(left)) {
            ps.setNull(k++, Types.INTEGER);
        } else {
            ps.setInt(k++, Integer.parseInt(left.getPropertyValueAsString()));
        }

        Long crc = calculateCrc(truncatedTextDescription);
        if (crc == null) {
            ps.setNull(k++, Types.BIGINT);
        } else {
            ps.setLong(k++, crc);
        }

        ps.executeUpdate();

    } catch (Exception e) {
        throw new DAOException("Error adding note.", e);
    } finally {
        DBTools.close(con, ps, null);
    }

    if (log.isTraceEnabled()) {
        log.trace("Added item with ID " + id);
        log.trace("PIMNoteDAO addItem end");
    }
}