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

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

Introduction

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

Prototype

public static String abbreviateMiddle(final String str, final String middle, final int length) 

Source Link

Document

Abbreviates a String to the length passed, replacing the middle characters with the supplied replacement String.

This abbreviation only occurs if the following criteria is met:

  • Neither the String for abbreviation nor the replacement String are null or empty
  • The length to truncate to is less than the length of the supplied String
  • The length to truncate to is greater than 0
  • The abbreviated String will have enough room for the length supplied replacement String and the first and last characters of the supplied String for abbreviation

Otherwise, the returned String will be the same as the supplied String for abbreviation.

Usage

From source file:kenh.expl.functions.AbbreviateMiddle.java

public String process(String str, String middle, int length) {
    return StringUtils.abbreviateMiddle(str, middle, length);
}

From source file:com.cognifide.aet.job.common.collectors.accessibility.AccessibilityIssueDeserializer.java

@Override
public AccessibilityIssue deserialize(JsonElement json, Type typeOfT,
        JsonDeserializationContext jsonDeserializationContext) {
    JsonObject jo = json.getAsJsonObject();
    String message = jo.get("message").getAsString();
    String code = jo.get("code").getAsString();
    IssueType type = IssueType.byValue(jo.get("type").getAsString());
    JsonElement jsonElement = jo.get("elementString");
    String elementString = NULL_ELEMENT_STRING;
    if (jsonElement != null) {
        elementString = jsonElement.getAsString();
    }/*from   ww  w  . j a v a  2  s .  co  m*/

    String elementStringAbbrv = StringEscapeUtils.escapeHtml4(elementString);
    elementStringAbbrv = StringUtils.abbreviateMiddle(elementStringAbbrv, "...", MAX_PRE_STRING_LENGTH);

    return new AccessibilityIssue(type, message, code, elementString, elementStringAbbrv);
}

From source file:it.cnr.ilc.clavius.controller.TranscriptionController.java

public List<String> getSentences() {
    List<String> ret = new ArrayList<String>();
    for (String sentence : transcriptionManager.getSentences()) {
        ret.add(StringUtils.abbreviateMiddle(sentence, "...", 40));
    }//from www. j a  v a  2s .  com

    return ret;

}

From source file:com.xpn.xwiki.web.PDFAction.java

@Override
public String render(XWikiContext context) throws XWikiException {
    XWikiURLFactory urlf = context.getWiki().getURLFactoryService().createURLFactory(XWikiContext.MODE_PDF,
            context);//from  w  w w .jav a 2 s.c  om
    context.setURLFactory(urlf);
    PdfExportImpl pdfexport = new PdfExportImpl();
    XWikiDocument doc = context.getDoc();
    handleRevision(context);

    try {
        context.getResponse().setContentType(ExportType.PDF.getMimeType());

        // Compute the name of the export. Since it's gong to be saved on the user's file system it needs to be a
        // valid File name. Thus we use the "path" serializer but replace the "/" separator by "_" since we're not
        // computing a directory hierarchy but a file name
        EntityReferenceSerializer<String> serializer = Utils.getComponent(EntityReferenceSerializer.TYPE_STRING,
                "path");
        String filename = serializer.serialize(doc.getDocumentReference()).replaceAll("/", "_");
        // Make sure we don't go over 255 chars since several filesystems don't support filename longer than that!
        filename = StringUtils.abbreviateMiddle(filename, "__", 255);

        context.getResponse().addHeader("Content-disposition",
                String.format("inline; filename=%s.%s", filename, ExportType.PDF.getExtension()));

        pdfexport.export(doc, context.getResponse().getOutputStream(), ExportType.PDF, context);
    } catch (IOException e) {
        throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
                XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION, "Exception while sending response", e);
    }
    return null;
}

From source file:edu.kit.dama.util.update.types.LibraryDiffInformation.java

@Override
public String toString() {
    StringBuilder b = new StringBuilder();
    String caption = "Library Diff Information";
    int maxWidth = 72;
    b.append(StringUtils.center(caption, maxWidth)).append("\n");
    b.append(StringUtils.rightPad("", maxWidth, "-")).append("\n");
    for (JavaLibrary lib : added) {
        b.append(StringUtils.abbreviateMiddle("(+) " + lib, "[...]", maxWidth)).append("\n");
    }/*from   w  w w  . j  av  a 2 s .co  m*/
    if (!changed.isEmpty()) {
        b.append("\n");
    }
    for (JavaLibrary lib : changed) {
        b.append(StringUtils.abbreviateMiddle("(U) " + lib, "[...]", maxWidth)).append("\n");
    }
    if (!unknown.isEmpty()) {
        b.append("\n");
    }
    for (JavaLibrary lib : unknown) {
        b.append(StringUtils.abbreviateMiddle("(?) " + lib, "[...]", maxWidth)).append("\n");
    }
    if (!deprecated.isEmpty()) {
        b.append("\n");
    }
    for (JavaLibrary lib : deprecated) {
        b.append(StringUtils.abbreviateMiddle("(-) " + lib, "[...]", maxWidth)).append("\n");
    }
    if (!ignored.isEmpty()) {
        b.append("\n");
    }
    for (File file : ignored) {
        b.append(StringUtils.abbreviateMiddle("(X) " + file.getAbsolutePath(), "[...]", maxWidth)).append("\n");
    }
    b.append("\n");
    b.append(StringUtils.rightPad("", maxWidth, "-")).append("\n");
    b.append("Added     : ").append(StringUtils.leftPad(String.valueOf(added.size()), 6)).append("\n");
    b.append("Changed   : ").append(StringUtils.leftPad(String.valueOf(changed.size()), 6)).append("\n");
    b.append("Deprecated: ").append(StringUtils.leftPad(String.valueOf(deprecated.size()), 6)).append("\n");
    b.append("Unknown   : ").append(StringUtils.leftPad(String.valueOf(unknown.size()), 6)).append("\n");
    b.append("Snapshots : ").append(StringUtils.leftPad(String.valueOf(detectedSnapshots), 6)).append("\n");
    b.append("Ignored   : ").append(StringUtils.leftPad(String.valueOf(ignored.size()), 6)).append("\n");
    b.append("Unchanged : ").append(StringUtils.leftPad(String.valueOf(unchanged.size()), 6)).append("\n");
    b.append(StringUtils.rightPad("", maxWidth, "-")).append("\n");
    return b.toString();
}

From source file:fr.gouv.culture.thesaurus.util.TextUtils.java

/**
 * Permet d'abbrger et de surligner une occurrence dans un texte. Le code
 * HTML  insrer autour de la partie  surligner ne le sera pas si la
 * partie  surligner est vide.//from w  w  w.  j a  va 2s .  c om
 * 
 * @param texte
 *            Texte  abbrger et contenant l'occurrence  surligner (peut
 *            tre <code>null</code>)
 * @param occurrenceStart
 *            Position de dbut de l'occurrence  surligner
 * @param occurrenceEnd
 *            Position de fin de l'occurrence  surligner (exclusif)
 * @param occurrenceMaxLength
 *            Taille max en nombre de caractres de l'occurrence
 * @param contextMaxLength
 *            Taille max en nombre de caractres du contexte (texte
 *            prcdant et suivant l'occurrence, chacun des deux constituant
 *            un contexte)
 * @param hlPreTag
 *            Code HTML  insrer avant l'occurrence (peut tre
 *            <code>null</code>)
 * @param hlPostTag
 *            Code HTML  insrer aprs l'occurrence (peut tre
 *            <code>null</code>)
 * @return Code HTML contenant le texte abbrg et l'occurrence surlign
 *         avec le code mentionn, ou <code>null</code> si le texte en
 *         entre tait <code>null</code>
 */
public static String htmlHighlightOccurrence(final String texte, final int occurrenceStart,
        final int occurrenceEnd, final int occurrenceMaxLength, final int contextMaxLength,
        final String hlPreTag, final String hlPostTag) {
    if (occurrenceStart > occurrenceEnd) {
        throw new IllegalArgumentException("Invalid occurrence position.");
    }

    String highlightedVersion;

    if (texte == null) {
        highlightedVersion = null;
    } else {
        final String preCode = StringUtils.defaultString(hlPreTag);
        final String postCode = StringUtils.defaultString(hlPostTag);

        // Partie du texte :
        // 0 : contexte prcdent
        // 1 : occurrence  surligner
        // 2 : contexte suivant
        final String[] parts = new String[3];

        parts[0] = texte.substring(0, occurrenceStart);
        parts[1] = texte.substring(occurrenceStart, occurrenceEnd);
        parts[2] = texte.substring(occurrenceEnd);

        // 1. Abbrviation des termes trouvs si besoin.
        if ((occurrenceEnd - occurrenceStart) > occurrenceMaxLength) {
            parts[1] = StringUtils.abbreviateMiddle(parts[1], ELLIPSIS, occurrenceMaxLength);
        }

        // 2. Abbrviation du contexte.
        parts[0] = rightAbbreviateOnWords(parts[0], contextMaxLength);
        parts[2] = leftAbbreviateOnWords(parts[2], contextMaxLength);

        // HTML.
        final StringBuilder highlightVersionBuilder = new StringBuilder(
                occurrenceMaxLength + contextMaxLength * 2 + preCode.length() + postCode.length());

        highlightVersionBuilder.append(StringEscapeUtils.escapeHtml4(parts[0]));

        if (StringUtils.isNotEmpty(parts[1])) {
            highlightVersionBuilder.append(preCode);
            highlightVersionBuilder.append(StringEscapeUtils.escapeHtml4(parts[1]));
            highlightVersionBuilder.append(postCode);
        }

        highlightVersionBuilder.append(StringEscapeUtils.escapeHtml4(parts[2]));

        highlightedVersion = highlightVersionBuilder.toString();
    }

    return highlightedVersion;
}

From source file:edu.kit.dama.dataworkflow.util.DataWorkflowTaskUtils.java

/**
 * Print the provided list of DataWorkflow tasks to StdOut, either in a basic
 * tabular view or in verbose mode, in a detailed representation.
 *
 * @param pTasks The list of tasks to print out.
 * @param pVerbose TRUE = print detailed view, FALSE = print basic tabular
 * view./*w w w . j  a va 2 s  . com*/
 */
public static void printTaskList(List<DataWorkflowTask> pTasks, boolean pVerbose) {
    if (!pVerbose) {
        //do table listing
        //Headers: ID | STATUS | LAST_MODIFIED
        //Lengths: 10 | 34 | 34
        StringBuilder listing = new StringBuilder();
        listing.append(StringUtils.center("Task ID", 10)).append("|").append(StringUtils.center("Status", 34))
                .append("|").append(StringUtils.center("Last Modified", 34)).append("\n");
        for (DataWorkflowTask task : pTasks) {
            listing.append(StringUtils.center(Long.toString(task.getId()), 10)).append("|")
                    .append(StringUtils.center(task.getStatus().toString(), 34)).append("|")
                    .append(StringUtils.center(new SimpleDateFormat().format(task.getLastUpdate()), 34))
                    .append("\n");
        }
        System.out.println(listing.toString());
    } else {
        //do detailed listing
        //ID: <ID>     Status: <STATUS>  Last Update: <LAST_UPDATE>
        //Config: <CONFIG_ID> Environment: <ID> Predecessor: <ID>
        //Group: <GID> Executor: <UID> Contact: <EMAIL>
        //Investigation: <ID>
        //InputDir: <URL>
        //OutputDir: <URL>              
        //WorkingDir: <URL>              
        //TempDir: <URL>
        //Input Objects         
        // Object | View 
        //  OID 1 | default
        //  OID 2 | default
        //Transfers          
        // Object | TransferId 
        //  OID 1 | 123
        //--------------------------------------------------------------
        StringBuilder builder = new StringBuilder();
        for (DataWorkflowTask task : pTasks) {
            builder.append(StringUtils.rightPad("Id: " + task.getId(), 40))
                    .append(StringUtils.rightPad(
                            "Predecessor: "
                                    + ((task.getPredecessor() != null) ? task.getPredecessor().getId() : "-"),
                            40))
                    .append("\n").append(StringUtils.rightPad("Status: " + task.getStatus(), 40))
                    .append(StringUtils.rightPad(
                            "Last Update: " + new SimpleDateFormat().format(task.getLastUpdate()), 40))
                    .append("\n")
                    .append(StringUtils.rightPad("Configuration: "
                            + ((task.getConfiguration() != null) ? task.getConfiguration().getId() : "-"), 40))
                    .append(StringUtils.rightPad("Environment: "
                            + ((task.getExecutionEnvironment() != null) ? task.getExecutionEnvironment().getId()
                                    : "-"),
                            40))
                    .append("\n").append(StringUtils.rightPad("Group: " + task.getExecutorGroupId(), 40))
                    .append(StringUtils.rightPad("User: " + task.getExecutorId(), 40)).append("\n")
                    .append(StringUtils.rightPad("Contact UserId: "
                            + ((task.getContactUserId() != null) ? task.getContactUserId() : "-"), 80))
                    .append("\n")
                    .append(StringUtils.rightPad("InvestigationId: " + task.getInvestigationId(), 80))
                    .append("\n").append(StringUtils.rightPad("Input Dir:", 15))
                    .append(StringUtils.abbreviateMiddle(task.getInputDirectoryUrl(), "...", 65)).append("\n")
                    .append(StringUtils.rightPad("Output Dir:", 15))
                    .append(StringUtils.abbreviateMiddle(task.getOutputDirectoryUrl(), "...", 65)).append("\n")
                    .append(StringUtils.rightPad("Working Dir:", 15))
                    .append(StringUtils.abbreviateMiddle(task.getWorkingDirectoryUrl(), "...", 65)).append("\n")
                    .append(StringUtils.rightPad("Temp Dir:", 15))
                    .append(StringUtils.abbreviateMiddle(task.getTempDirectoryUrl(), "...", 65)).append("\n")
                    .append(StringUtils.rightPad("Input Objects:", 80)).append("\n")
                    .append(StringUtils.center("ObjectId", 39)).append("|")
                    .append(StringUtils.center("View", 40)).append("\n");
            try {
                Properties objectViewMap = task.getObjectViewMapAsObject();
                Set<Entry<Object, Object>> entries = objectViewMap.entrySet();
                if (entries.isEmpty()) {
                    builder.append(StringUtils.center("---", 39)).append("|")
                            .append(StringUtils.center("---", 40)).append("\n");
                } else {
                    for (Entry<Object, Object> entry : entries) {
                        builder.append(StringUtils.center((String) entry.getKey(), 39)).append("|")
                                .append(StringUtils.center((String) entry.getValue(), 40)).append("\n");
                    }
                }
            } catch (IOException ex) {
                LOGGER.error("Failed to deserialize object-view map of DataWorkflow task " + task.getId(), ex);
                builder.append(StringUtils.center("---", 39)).append("|").append(StringUtils.center("---", 40))
                        .append("\n");
            }
            builder.append(StringUtils.rightPad("Transfers:", 80)).append("\n")
                    .append(StringUtils.center("ObjectId", 39)).append("|")
                    .append(StringUtils.center("TransferId", 40)).append("\n");
            try {
                Properties objectTransferMap = task.getObjectTransferMapAsObject();
                Set<Entry<Object, Object>> entries = objectTransferMap.entrySet();
                if (entries.isEmpty()) {
                    builder.append(StringUtils.center("---", 39)).append("|")
                            .append(StringUtils.center("---", 40)).append("\n");
                } else {
                    for (Entry<Object, Object> entry : entries) {
                        builder.append(StringUtils.center((String) entry.getKey(), 39)).append("|")
                                .append(StringUtils.center((String) entry.getValue(), 40)).append("\n");
                    }
                }
            } catch (IOException ex) {
                LOGGER.error("Failed to deserialize object-transfer map of DataWorkflow task " + task.getId(),
                        ex);
                builder.append(StringUtils.center("---", 39)).append("|").append(StringUtils.center("---", 40))
                        .append("\n");
            }
            //add closing line
            builder.append(StringUtils.leftPad("", 80, '-')).append("\n");
        }
        System.out.println(builder.toString());
    }
}

From source file:de.fau.cs.osr.hddiff.utils.HDDiffTreeVisualizer.java

private String abbreviateNodeRep(String label) {
    label = label.replace("\n", "\\\\n");
    label = label.replace("\"", "\\\"");
    label = StringUtils.abbreviateMiddle(label, "...\n...", 24);
    return label;
}

From source file:de.openali.odysseus.chart.framework.util.img.GenericChartLabelRenderer.java

private String fitToFixedWidth(final GC gc, final String line, final int width) {
    if (width < 1)
        return line;

    final int lineWidth = calcTextSize(gc, line).x;
    final int charWidth = lineWidth / line.length();
    if (lineWidth <= width)
        return line;
    int maxChar = width / charWidth;
    if (maxChar < 6)
        return StringUtils.abbreviate(line, 5);
    String s = StringUtils.abbreviateMiddle(line, "..", maxChar); //$NON-NLS-1$
    while (calcTextSize(gc, s).x > width) {
        maxChar -= 1;//from  w  ww.  j  ava 2 s  .  c  om
        s = StringUtils.abbreviateMiddle(line, "..", maxChar); //$NON-NLS-1$
    }
    return s;
}

From source file:fr.inria.atlanmod.neo4emf.neo4jresolver.runtimes.internal.Neo4jZippedInstaller.java

@Override
public void performInstall(IProgressMonitor monitor, IPath dirPath) throws IOException {
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }//from  w w w  . j  a  v  a  2  s  .com

    InputStream urlStream = null;
    try {
        URL url = getUrl();
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(TIMEOUT);
        connection.setReadTimeout(TIMEOUT);

        int length = connection.getContentLength();
        monitor.beginTask(NLS.bind("Reading from {1}", getVersion(), getUrl().toString()),
                length >= 0 ? length : IProgressMonitor.UNKNOWN);

        urlStream = connection.getInputStream();
        ZipInputStream zipStream = new ZipInputStream(urlStream);
        byte[] buffer = new byte[1024 * 8];
        long start = System.currentTimeMillis();
        int total = length;
        int totalRead = 0;
        ZipEntry entry;
        float kBps = -1;
        while ((entry = zipStream.getNextEntry()) != null) {
            if (monitor.isCanceled())
                break;
            String fullFilename = entry.getName();
            IPath fullFilenamePath = new Path(fullFilename);
            int secsRemaining = (int) ((total - totalRead) / 1024 / kBps);
            String textRemaining = secsToText(secsRemaining);
            monitor.subTask(NLS.bind("{0} remaining. Reading {1}",
                    textRemaining.length() > 0 ? textRemaining : "unknown time", StringUtils
                            .abbreviateMiddle(fullFilenamePath.removeFirstSegments(1).toString(), "...", 45)));
            int entrySize = (int) entry.getCompressedSize();
            OutputStream output = null;
            try {
                int len = 0;
                int read = 0;
                String action = null;
                if (jarFiles.contains(fullFilename)) {
                    action = "Copying";
                    String filename = FilenameUtils.getName(fullFilename);
                    output = new FileOutputStream(dirPath.append(filename).toOSString());
                } else {
                    action = "Skipping";
                    output = new NullOutputStream();
                }
                int secs = (int) ((System.currentTimeMillis() - start) / 1000);
                kBps = (float) totalRead / 1024 / secs;

                while ((len = zipStream.read(buffer)) > 0) {
                    if (monitor.isCanceled())
                        break;
                    read += len;
                    monitor.subTask(NLS.bind("{0} remaining. {1} {2} at {3}KB/s ({4}KB / {5}KB)",
                            new Object[] {
                                    String.format("%s",
                                            textRemaining.length() > 0 ? textRemaining : "unknown time"),
                                    action,
                                    StringUtils.abbreviateMiddle(
                                            fullFilenamePath.removeFirstSegments(1).toString(), "...", 45),
                                    String.format("%,.1f", kBps), String.format("%,.1f", (float) read / 1024),
                                    String.format("%,.1f", (float) entry.getSize() / 1024) }));
                    output.write(buffer, 0, len);
                }
                totalRead += entrySize;
                monitor.worked(entrySize);
            } finally {
                IOUtils.closeQuietly(output);
            }
        }
    } finally {
        IOUtils.closeQuietly(urlStream);
        monitor.done();
    }
}