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

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

Introduction

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

Prototype

public static String abbreviate(String str, int maxWidth) 

Source Link

Document

Abbreviates a String using ellipses.

Usage

From source file:com.github.restdriver.serverdriver.http.response.DefaultResponse.java

@Override
public String toCompactString() {
    return "status=" + statusCode + "|content="
            + StringUtils.abbreviate(content, Response.MAX_BODY_DISPLAY_LENGTH) + "|headers=["
            + join(headers, ",") + "]";
}

From source file:de.tudarmstadt.lt.lm.app.GenerateNgrams.java

public static File generateNgrams(File src_dir, AbstractStringProvider prvdr, int from_cardinality,
        int to_cardinality, boolean overwrite) {
    final File ngram_file = new File(src_dir, String.format("%s.%s", src_dir.getName(), "ngrams.txt.gz"));
    int n_b = from_cardinality, n_e = to_cardinality;
    if (ngram_file.exists()) {
        LOG.info("Output file already exists: '{}'.", ngram_file.getAbsolutePath());
        if (overwrite) {
            ngram_file.delete();//from   w w  w  .j a v a  2  s  .c o  m
            LOG.info("Overwriting file: '{}'.", ngram_file.getAbsolutePath());
        } else
            return ngram_file;
    }

    File[] src_files = src_dir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File f) {
            return f.isFile() && f.getName().endsWith(".txt") && (!f.equals(ngram_file));
        }
    });

    String[] basenames = new String[src_files.length];
    for (int i = 0; i < basenames.length; i++)
        basenames[i] = src_files[i].getName();

    LOG.info(String.format("Reading txt files from dir: '%s'; Files: %s.", src_dir.getAbsolutePath(),
            StringUtils.abbreviate(Arrays.toString(basenames), 200)));
    LOG.info(String.format("Writing ngrams to file: '%s'.", ngram_file.getAbsolutePath()));

    PrintWriter pw = null;
    try {
        pw = new PrintWriter(
                new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(ngram_file)), "UTF-8"));
    } catch (IOException e) {
        LOG.error("Could not open writer for file: '{}'.", ngram_file.getAbsolutePath(), e);
        return null;
    }

    long num_ngrams = 0l;
    List<String>[] ngrams = null;
    for (int i = 0; i < src_files.length; i++) {
        File src_file = src_files[i];
        LOG.info("Processing file {} / {} ('{}')", i + 1, src_files.length, src_file.getAbsolutePath());
        long num_ngrams_f = 0l;

        try {
            LineIterator liter = new LineIterator(
                    new BufferedReader(new InputStreamReader(new FileInputStream(src_file), "UTF-8")));
            int lc = 0;
            while (liter.hasNext()) {
                if (++lc % 1000 == 0)
                    LOG.debug("Processing line {} ({})", lc, src_file);
                String line = liter.next();
                for (String sentence : prvdr.splitSentences(line)) {
                    for (int n = n_b; n <= n_e; n++) {
                        ngrams = null;
                        try {
                            List<String> tokens = prvdr.tokenizeSentence(sentence);
                            if (tokens.isEmpty())
                                continue;
                            ngrams = AbstractLanguageModel.getNgramSequence(tokens, n);
                        } catch (Exception e) {
                            LOG.warn(
                                    "Could not get ngram of cardinality {} from String '{}' in line '{}' from file '{}'.",
                                    n, StringUtils.abbreviate(line, 100), lc, src_file.getAbsolutePath());
                            continue;
                        }
                        for (List<String> ngram : ngrams)
                            pw.println(StringUtils.join(ngram, " "));
                        pw.flush();
                        num_ngrams_f += ngrams.length;
                    }
                }
            }
            liter.close();
        } catch (Exception e) {
            LOG.warn("Could not read file '{}'.", src_file.getAbsolutePath(), e);
        }
        LOG.debug("Generated {} ngrams from file {}.", num_ngrams_f, src_file);
        num_ngrams += num_ngrams_f;
    }

    if (pw != null)
        pw.close();

    LOG.info("Generated {} ngrams.", num_ngrams);

    return ngram_file;
}

From source file:gov.nih.nci.caarray.web.action.project.ProjectTabAction.java

/**
 * Helper method for creating and saving appropriate error message when a
 * write operation on a project causes a workflow exception.
 *///from   w w w.  ja  v  a  2s .  co m
protected void handleWorkflowError() {
    ActionHelper.saveMessage(getText("project.saveProblem", new String[] {
            StringUtils.abbreviate(getProject().getExperiment().getTitle(), TRUNCATED_TITLE_WIDTH) }));
}

From source file:mobi.chouette.model.Network.java

/**
 * set source identifier <br/>//w w w. j  a v a  2  s.c o m
 * truncated to 255 characters if too long
 * 
 * @param value
 *            New value
 */
public void setSourceIdentifier(String value) {
    sourceIdentifier = StringUtils.abbreviate(value, 255);

}

From source file:com.sfs.captor.model.StakeholderRequest.java

/**
 * @return the description
 */
public String getDescriptionAbbrv() {
    return StringUtils.abbreviate(description, 80);
}

From source file:com.sfs.ucm.controller.ProjectPackageAction.java

/**
 * Action: remove object//from  w w  w  . j a  v a  2  s . c o  m
 * 
 * @throws UCMException
 */
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void remove() throws UCMException {
    try {
        this.project.removeProjectPackage(projectPackage);
        em.remove(this.projectPackage);
        logger.info("deleted {}", this.projectPackage.getName());
        this.facesContextMessage.infoMessage("{0} deleted successfully",
                StringUtils.abbreviate(this.projectPackage.getName(), 25));

        // refresh list
        loadList();

        this.selected = false;
    } catch (Exception e) {
        throw new UCMException(e);
    }
}

From source file:com.balero.models.BlogDAO.java

@Transactional
public String postTitle(int id) {
    String postitle = null;//from   www  .  j  a  v  a2  s  . c  o m
    Session session = sessionFactory.getCurrentSession();
    List<Blog> Blog = session.createQuery("from Blog where id = '" + id + "'").list();
    for (Blog obj : Blog) {
        postitle = obj.getPosttitle();
    }
    String title = null;
    title = StringUtils.substringBetween(postitle, "<h3>", "</h3>");
    if (title == null) {
        title = StringUtils.substringBetween(postitle, "<p>", "</p>");
    }
    return StringUtils.abbreviate(title + "...", 150);
}

From source file:com.sfs.captor.model.BusinessProcess.java

/**
 * @return the goal abbreviated
 */
public String getGoalAbbrv() {
    return StringUtils.abbreviate(this.goal, Constants.ABBRV_DESC_LEN);
}

From source file:it.av.youeat.web.page.MessageListPage.java

public MessageListPage() {
    super();//from w  ww.  j  a  va 2s .c  om
    add(getFeedbackPanel());
    final Label noYetMessages = new Label("noYetMessages", getString("noMessages")) {
        @Override
        protected void onBeforeRender() {
            super.onBeforeRender();
            setVisible(getLastMessages().size() == 0);
        }
    };
    noYetMessages.setOutputMarkupId(true);
    noYetMessages.setOutputMarkupPlaceholderTag(true);
    add(noYetMessages);

    final WebMarkupContainer messagesListContainer = new WebMarkupContainer("messagesListContainer");
    messagesListContainer.setOutputMarkupPlaceholderTag(true);
    add(messagesListContainer);
    messageList = new PropertyListView<Message>("messagesList", new MessagesModel()) {

        @Override
        protected void populateItem(final ListItem<Message> item) {
            // if the dialog contains unread message, use a different CSS style
            if (!(item.getModelObject().getSender().equals(getLoggedInUser()))
                    && item.getModelObject().getReadTime() == null) {
                item.add(new AttributeAppender("class", new Model<String>("rowMessageUnread"), " "));
            }
            Eater sender = item.getModelObject().getSender();
            Eater recipient = item.getModelObject().getDialog().checkCounterpart(sender);
            item.add(ImagesAvatar.getAvatar("avatar", sender, this.getPage(), true));
            item.add(new BookmarkablePageLink("linkToUser", EaterViewPage.class,
                    EaterUtil.createParamsForEater(sender)).add(new Label(Message.SENDER_FIELD)));
            BookmarkablePageLink recipientLink = new BookmarkablePageLink("linkToRecipientUser",
                    EaterViewPage.class, EaterUtil.createParamsForEater(recipient));
            recipientLink.add(new Label("recipient", recipient.toString()));
            //visible only on Sent page
            recipientLink.setVisible(!inBox);
            item.add(recipientLink);
            item.add(new Label(Message.SENTTIME_FIELD));
            item.add(new OpenMessage("openMessageTitle", new Model<Message>(item.getModelObject()), item)
                    .add(new Label(Message.TITLE_FIELD)));
            String messageBodyShort = StringUtils.abbreviate(
                    templateUtil.resolveTemplateEater(item.getModelObject(), false, null, getWebPage()), 150);
            item.add(new OpenMessage("openMessage", new Model<Message>(item.getModelObject()), item)
                    .add(new Label(Message.BODY_FIELD, messageBodyShort)));
            item.add(new AjaxFallbackLink<Message>("remove", new Model<Message>(item.getModelObject())) {

                @Override
                public void onClick(AjaxRequestTarget target) {
                    try {
                        ((MessageListPage) getPage()).dialogService.delete(getModelObject().getDialog(),
                                getLoggedInUser());
                        noYetMessages.setVisible(getLastMessages().size() == 0);
                        info(getString("info.userRelationRemoved"));
                    } catch (YoueatException e) {
                        error(new StringResourceModel("genericErrorMessage", this, null).getString());
                    }
                    if (target != null) {
                        target.addComponent(getFeedbackPanel());
                        target.addComponent((noYetMessages));
                        target.addComponent((messagesListContainer));
                        target.addComponent(((MessageListPage) target.getPage()).getFeedbackPanel());
                    }
                }
            });
            item.add(new OpenMessage("open", new Model<Message>(item.getModelObject()), item));
        }
    };
    messagesListContainer.add(messageList);

    add(new BookmarkablePageLink("goSearchFriendPage", SearchFriendPage.class));

    long numberUnreadMsgs = messageService.countUnreadMessages(getLoggedInUser());
    final WebMarkupContainer separator = new WebMarkupContainer("separator");
    separator.setVisible(numberUnreadMsgs > 0);

    final Label unreadMsgs = new Label("unreadMessages", new Model<Long>(numberUnreadMsgs));
    unreadMsgs.setOutputMarkupPlaceholderTag(true);
    unreadMsgs.setVisible(numberUnreadMsgs > 0);

    AjaxFallbackLink<String> inboxButton = new AjaxFallbackLink<String>("inbox") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            inBox = true;
            noYetMessages.setVisible(getLastMessages().size() == 0);
            if (target != null) {
                target.addComponent((messagesListContainer));
                target.addComponent((noYetMessages));
            }
        }
    };
    add(inboxButton);
    add(new Label("numberMessages", Integer.toString(messageList.getModel().getObject().size())));
    add(unreadMsgs);
    add(separator);
    add(new AjaxFallbackLink<String>("sentitems") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            inBox = false;
            noYetMessages.setVisible(getLastMessages().size() == 0);
            if (target != null) {
                target.addComponent((messagesListContainer));
                target.addComponent((noYetMessages));
            }
        }
    });
    long numberSentMsgs = dialogService.countCreatedDialogs(getLoggedInUser());
    add(new Label("numberSentMessages", Long.toString(numberSentMsgs)));
}

From source file:de.tudarmstadt.lt.lm.service.UimaStringProvider.java

public List<String>[] getNgramsInner(String text, String language_code, String docid, int splitcount,
        int casExceptionCount) throws RemoteException, Exception {
    int maxLengthSplitHeuristic = Properties.maxLengthSplitHeuristic();
    if (maxLengthSplitHeuristic > 0 && text.length() > maxLengthSplitHeuristic) {
        List<String>[] result = null;
        Iterator<String> text_splits_iter = applySplitHeuristic(text, splitcount);
        for (int i = 0; text_splits_iter.hasNext(); i++) {
            String docid_i = String.format("%s.%d", docid, i);
            List<String>[] intermediate_result = getNgramsInner(text_splits_iter.next().trim(), language_code,
                    docid_i, splitcount + 1, 0);
            if (result == null)
                result = intermediate_result;
            else//from   w  w w .j  a v  a2s  .co m
                result = ArrayUtils.getConcatinatedArray(result, intermediate_result);
        }
        return result;
    }

    synchronized (_processing_engine_lck) {
        List<String>[] result = null;
        JCas aJCas = null;
        try {
            aJCas = _processing_engine.newJCas();
        } catch (Throwable t) {
            for (int i = 0; t != null; i++) {
                LOG.error(
                        String.format("Failed to initialize cas: %s '%s' (%d-%s: %s).)", docid,
                                StringUtils.abbreviate(text, 50), i, t.getClass().getName(), t.getMessage()),
                        t);
                t = t.getCause();
            }
            return EMPTY_NGRAM_LIST;
        }

        aJCas.setDocumentText(text);
        DocumentMetaData meta = DocumentMetaData.create(aJCas);
        meta.setDocumentId(docid);
        meta.setDocumentTitle(StringUtils.abbreviate(text, 30));
        aJCas.getCas().setDocumentLanguage(language_code);
        // aJCas.setDocumentLanguage(language_code);
        meta.setLanguage(language_code);

        LOG.debug("[{}] Pre-processing text '{}'...", docid, StringUtils.abbreviate(text, 50));
        try {
            _processing_engine.process(aJCas);
        } catch (Throwable t) {
            for (int i = 0; t != null; i++) {
                LOG.error(
                        String.format("Failed to process cas: %s '%s' (%d-%s: %s).)", docid,
                                StringUtils.abbreviate(text, 50), i, t.getClass().getName(), t.getMessage()),
                        t);
                t = t.getCause();
            }
            LOG.error("Reactivating cas engine.");
            setEngineDescription(getEngineDescription());
            LOG.error("Cas engine reactivated.");
            if (casExceptionCount++ < 1) {
                LOG.error("Reprocessing cas {}.", docid);
                return getNgramsInner(text, language_code, docid, splitcount, casExceptionCount);
            }
            LOG.error("Cas engine exception counter has reached its limit. Cas {} will be skipped.", docid);
            return EMPTY_NGRAM_LIST;
        }

        result = getNgramsFromSentencesFromCas(aJCas);
        return result;
    }

}