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.ctriposs.rest4j.client.Request.java

@Override
public String toString() {
    final StringBuilder sb = new StringBuilder();
    sb.append(getClass().getName());/* w w w . j  a v a 2 s  . c o  m*/
    sb.append("{_headers=").append(_headers);
    sb.append(", _input=").append(_inputRecord);
    sb.append(", _method=").append(_method);
    if (_hasUri) {
        // request was constructed using an old constructor
        sb.append(", _uri=").append(StringUtils.abbreviate(_uri.toString(), 256));
        sb.append("}");
    } else {
        sb.append(", _baseUriTemplate=").append(_baseUriTemplate);
        sb.append(", _methodName=").append(_methodName);
        sb.append(", _pathKeys=").append(_pathKeys);
        sb.append(", _queryParams=").append(_queryParams);
        sb.append(", _requestOptions=").append(_requestOptions);
        sb.append('}');
    }
    return sb.toString();
}

From source file:com.intuit.tank.tools.debugger.AgentDebuggerFrame.java

private void updateStepLabel(TestStep testStep) {

    if (testStep instanceof RequestStep) {
        StringBuilder label = new StringBuilder();
        RequestStep step = (RequestStep) testStep;
        label.append(step.getRequest().getProtocol()).append("://").append(step.getRequest().getHost())
                .append(step.getRequest().getPath());

        int qsCount = 0;
        if (step.getRequest().getQueryString() != null) {
            for (Header qs : step.getRequest().getQueryString()) {
                label.append(qsCount == 0 ? "?" : "&");
                label.append(qs.getKey()).append("=").append(qs.getValue());
                qsCount++;//from   ww  w .  j  av a  2s  . co  m
            }
        }
        step.getRequest().setLabel(StringUtils.abbreviate(label.toString(), 1024));
    }
    return;
}

From source file:com.haulmont.cuba.web.LoginWindow.java

protected void login() {
    String login = loginField.getValue();
    String password = passwordField.getValue() != null ? passwordField.getValue() : "";

    if (StringUtils.isEmpty(login) || StringUtils.isEmpty(password)) {
        String message = messages.getMainMessage("loginWindow.emptyLoginOrPassword", resolvedLocale);
        Notification notification = new Notification(message, Type.WARNING_MESSAGE);
        notification.setDelayMsec(WebWindowManager.WARNING_NOTIFICATION_DELAY_MSEC);
        notification.show(ui.getPage());
        return;/*  ww w  .j av a2 s  .  c om*/
    }

    if (!bruteForceProtectionCheck(login, app.getClientAddress())) {
        return;
    }

    try {
        Locale locale = getUserLocale();
        app.setLocale(locale);

        PasswordEncryption passwordEncryption = AppBeans.get(PasswordEncryption.NAME);

        if (loginByRememberMe && rememberMeAllowed) {
            loginByRememberMe(login, password, locale);
        } else if (configuration.getConfig(WebAuthConfig.class).getExternalAuthentication()) {
            // try to login as externally authenticated user, fallback to regular authentication
            // we use resolved locale for error messages
            if (authenticateExternally(login, password, resolvedLocale)) {
                login = convertLoginString(login);

                ((ExternallyAuthenticatedConnection) connection).loginAfterExternalAuthentication(login,
                        locale);
            } else {
                login(login, passwordEncryption.getPlainHash(password), locale);
            }
        } else {
            login(login, passwordEncryption.getPlainHash(password), locale);
        }
        // locale could be set on the server
        if (connection.getSession() != null) {
            app.setLocale(connection.getSession().getLocale());
            if (globalConfig.getLocaleSelectVisible()) {
                app.addCookie(COOKIE_LOCALE, locale.toLanguageTag());
            }
        }
    } catch (LoginException e) {
        log.info("Login failed: {}", e.toString());

        String message = StringUtils.abbreviate(e.getMessage(), 1000);
        String bruteForceMsg = registerUnsuccessfulLoginAttempt(login, app.getClientAddress());
        if (!Strings.isNullOrEmpty(bruteForceMsg)) {
            message = bruteForceMsg;
        }
        showLoginException(message);
    } catch (Exception e) {
        log.warn("Unable to login", e);
        showException(e);
    }
}

From source file:net.certiv.authmgr.task.section.core.classifier.BayesPartitionClassifier.java

@SuppressWarnings("unused")
private void report(String category, String partition, String word, double pBi, double pEoB, double wordProb) {
    BigDecimal pBiBD = new BigDecimal(pBi).setScale(5, BigDecimal.ROUND_HALF_UP);
    BigDecimal pEoBiBD = new BigDecimal(pEoB).setScale(8, BigDecimal.ROUND_HALF_UP);
    BigDecimal probBD = new BigDecimal(wordProb).setScale(8, BigDecimal.ROUND_HALF_UP);
    String wordAbbr = StringUtils.abbreviate(word, 13);
    wordAbbr = StringUtils.rightPad(wordAbbr, 14);
    Log.warn(this, "Bayes: " + wordAbbr + pEoBiBD + " (" + probBD + ":" + pBiBD + ")");
}

From source file:com.edgenius.wiki.search.service.AbstractSearchService.java

/**
 * Match all given name-value pairs, return combined fragment. For example, spaceUname and space desc have matched
 * fragment, then these 2 pieces are merge into one String fragment and return.
 * @param namedValues/*  w w  w . j av  a  2 s.c  om*/
 * @return
 * @throws IOException
 */
private String createFragment(Highlighter hl, String content) throws IOException {
    if (content == null)
        return "";

    if (hl == null)
        return content;

    TokenStream tokenStream = searcherFactory.getAnalyzer().tokenStream(FieldName.CONTENT,
            new StringReader(content));
    String frag;
    try {
        frag = hl.getBestFragments(tokenStream, content, 3, "...");
    } catch (InvalidTokenOffsetsException e) {
        log.error("Highlight fragment error", e);
        frag = StringUtils.abbreviate(content, FRAGMENT_LEN);
    }

    return frag;
}

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

void listNgrams() {
    if (_providerService == null) {
        System.out.println("LM Server is not runnning.");
        return;/*www  .j  av  a  2 s.  c  o m*/
    }

    try {
        LanguageModel<String> lm = _providerService.getLanguageModel();
        Iterator<List<String>> iter = lm.getNgramIterator();
        if (!iter.hasNext()) {
            System.out.println("No ngrams in Language Model.");
            return;
        }

        double log10_prob, prob10, log2_prob;
        int i = 0;
        for (List<String> ngram = null; iter.hasNext();) {
            ngram = iter.next();
            if (++i % 30 == 0)
                if (":q".equals(readInput(String.format(
                        "press <enter> to show next 30 ngrams, type ':q' if you want to quit showing ngrams: %n%s $> ",
                        _name))))
                    break;

            log10_prob = _providerService.getNgramLog10Probability(ngram);
            prob10 = Math.pow(10, log10_prob);
            log2_prob = log10_prob / Math.log10(2);

            System.out.format("%-50.50s [%g (log10=%g, log2=%g)] %n",
                    StringUtils.abbreviate(StringUtils.join(ngram, ' '), 50), prob10, log10_prob, log2_prob);
        }

    } catch (Exception e) {
        LOG.warn(e.getMessage());
    }

}

From source file:com.google.ie.business.service.impl.IdeaServiceImpl.java

/**
 * Create a linked list from the list of ideas received.Removes the data not
 * required on the homepage.This method is intended to create
 * list for Recent ideas and Popular ideas method
 * //ww  w  .  jav  a  2  s. c  o m
 * @param ideas list of ideas
 * @return a {@link LinkedList} object containing the ideas
 */
private LinkedList<Idea> createLinkedListFromTheFetchedData(List<Idea> ideas) {
    LinkedList<Idea> linkedList = new LinkedList<Idea>();
    Iterator<Idea> iterator = ideas.iterator();
    Idea originalIdea = null;
    Idea ideaWithTheRequiredDataOnly = null;
    while (iterator.hasNext()) {
        originalIdea = iterator.next();
        if (originalIdea.getStatus().equals(Idea.STATUS_OBJECTIONABLE))
            continue;
        ideaWithTheRequiredDataOnly = new Idea();
        ideaWithTheRequiredDataOnly
                .setTitle(StringUtils.abbreviate(originalIdea.getTitle(), ServiceConstants.FIFTY));
        /* Limit the description to hundred characters */
        ideaWithTheRequiredDataOnly.setDescription(
                StringUtils.abbreviate(originalIdea.getDescription(), ServiceConstants.HUNDRED));
        ideaWithTheRequiredDataOnly.setKey(originalIdea.getKey());
        /* Add the idea to the linked list */
        linkedList.add(ideaWithTheRequiredDataOnly);
    }
    return linkedList;
}

From source file:io.hops.ha.common.TransactionStateImpl.java

public void addAllocateResponse(ApplicationAttemptId id, AllocateResponseLock allocateResponse) {
    AllocateResponsePBImpl lastResponse = (AllocateResponsePBImpl) allocateResponse.getAllocateResponse();
    if (lastResponse != null) {
        List<String> allocatedContainers = new ArrayList<String>();
        for (org.apache.hadoop.yarn.api.records.Container container : lastResponse.getAllocatedContainers()) {
            allocatedContainers.add(container.getId().toString());
        }/*from  w  ww  .j  a va 2s. c o m*/

        Map<String, byte[]> completedContainersStatuses = new HashMap<String, byte[]>();
        for (ContainerStatus status : lastResponse.getCompletedContainersStatuses()) {
            ContainerStatus toPersist = status;
            if (status.getDiagnostics().length() > 1000) {
                toPersist = new ContainerStatusPBImpl(((ContainerStatusPBImpl) status).getProto());
                toPersist.setDiagnostics(StringUtils.abbreviate(status.getDiagnostics(), 1000));
            }
            completedContainersStatuses.put(status.getContainerId().toString(),
                    ((ContainerStatusPBImpl) toPersist).getProto().toByteArray());
        }

        AllocateResponsePBImpl toPersist = new AllocateResponsePBImpl();
        toPersist.setAMCommand(lastResponse.getAMCommand());
        toPersist.setAvailableResources(lastResponse.getAvailableResources());
        toPersist.setDecreasedContainers(lastResponse.getDecreasedContainers());
        toPersist.setIncreasedContainers(lastResponse.getIncreasedContainers());
        toPersist.setNumClusterNodes(lastResponse.getNumClusterNodes());
        toPersist.setPreemptionMessage(lastResponse.getPreemptionMessage());
        toPersist.setResponseId(lastResponse.getResponseId());
        toPersist.setUpdatedNodes(lastResponse.getUpdatedNodes());

        this.allocateResponsesToAdd.put(id,
                new AllocateResponse(id.toString(), toPersist.getProto().toByteArray(), allocatedContainers,
                        allocateResponse.getAllocateResponse().getResponseId(), completedContainersStatuses));
        if (toPersist.getProto().toByteArray().length > 1000) {
            LOG.debug("add allocateResponse of size " + toPersist.getProto().toByteArray().length + " for " + id
                    + " content: " + print(toPersist));
        }
        allocateResponsesToRemove.remove(id);
        appIds.add(id.getApplicationId());
    }
}

From source file:mitm.application.djigzo.james.mailets.PDFEncrypt.java

private String createReplyURL(String baseURL, String subject, Collection<MailAddress> recipients, String sender,
        String replyTo, String serverSecret) throws MessagingException {
    String replyURL = null;/*from  w w w .  ja  v a  2  s  .c  o m*/

    if (EmailAddressUtils.INVALID_EMAIL.equals(replyTo) || StringUtils.isEmpty(replyTo)) {
        /*
         * This happens if the sender of the email is an invalid sender. This will normally only happen if
         * the global settings allow PDF reply.
         */
        getLogger().warn("Reply-To of the message is an invalid email address. "
                + "It's not possible to reply to the PDF.");
    } else if (baseURL != null && serverSecret != null) {
        /*
         * The from of the reply (is equal to the recipient of the encrypted PDF)
         */
        String recipient = null;

        if (recipients.size() == 1) {
            String notYetValidatedRecipient = recipients.iterator().next().toString();

            recipient = EmailAddressUtils.canonicalizeAndValidate(notYetValidatedRecipient, true);

            if (recipient == null) {
                getLogger().warn("{} is not a valid recipient.", notYetValidatedRecipient);
            }
        } else {
            getLogger().warn("The mail has multiple recipients.  It's not possible to reply to the PDF.");
        }

        if (recipient != null && !isReplyAllowed(recipient)) {
            getLogger().debug("Recipient {} does not allow reply to PDF.", recipient);

            recipient = null;
        }

        if (sender != null && recipient != null) {
            /*
             * Make sure the subject is not too long
             */
            subject = StringUtils.abbreviate(StringUtils.trimToEmpty(subject), maxSubjectLength);

            URLBuilder uRLBuilder = SystemServices.getURLBuilder();

            PDFReplyURLBuilder replyBuilder = new PDFReplyURLBuilder(uRLBuilder);

            replyBuilder.setBaseURL(baseURL);
            replyBuilder.setUser(sender);
            replyBuilder.setRecipient(replyTo);
            /*
             * The from of the reply message is equal to the original recipient of the PDF (i.e, if the
             * recipient clicks reply, the sender, aka from, of the reply is set to the recipient of the pdf).
             */
            replyBuilder.setFrom(recipient);
            replyBuilder.setSubject(subject);
            replyBuilder.setKey(serverSecret);

            try {
                replyURL = replyBuilder.buildURL();
            } catch (URLBuilderException e) {
                throw new MessagingException("Building reply URL failed.", e);
            }
        }
    }

    return replyURL;
}

From source file:com.google.ie.web.controller.ProjectController.java

/**
 * Shortens the length of title and description fields
 * /*from  www.  j  a  va2  s  .  co m*/
 * @param project
 */
private void shortenFields(Project project) {
    if (null != project) {
        /* 50 chars for title */
        project.setName(StringUtils.abbreviate(project.getName(), 50));
        /* 150 chars for description */
        project.setDescriptionAsString(StringUtils.abbreviate(project.getDescriptionAsString(), 150));
    }
}