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

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

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:edu.kit.dama.transfer.client.impl.CLUploadClient.java

private String formatString(String pString) {
    return StringUtils.abbreviateMiddle(pString, "(...)", 20);
}

From source file:edu.kit.dama.transfer.client.impl.CLDownloadClient.java

/**
 * String format helper for abbreviation.
 *
 * @param pString The string./*w w  w  .j a  v a  2 s  . c  o  m*/
 *
 * @return The string limited to 20 characters.
 */
private String formatString(String pString) {
    return StringUtils.abbreviateMiddle(pString, "(...)", 20);
}

From source file:com.heliosphere.demeter.base.runner.AbstractRunner.java

@SuppressWarnings("nls")
@Override// w w  w .jav a2 s.co  m
public void start() throws RunnerException {
    log.info(String.format("Runner started: dispatching [%1d] context(s) across [%2d] thread(s).",
            contexts.size(), threadCount));
    log.info(" ");

    ExecutorService executor = Executors.newFixedThreadPool(this.threadCount);
    for (IContext context : contexts) {
        callables.add(context.getProcessor());
    }

    try {
        futures = executor.invokeAll(callables);
    } catch (InterruptedException e) {
        throw new RunnerException("An error occurred due to: " + e.getMessage(), e);
    }

    log.info(
            "*********************************************************************************************************");
    log.info("EXECUTION SUMMARY:");
    log.info(" ");
    log.info(String.format(" Thread pool size..: [%1d]", threadCount));
    log.info(String.format(" Configuration file: [%1s]", configuration.getResource().getFile().getName()));
    log.info(String.format(" Execution file....: [%1s]", execution.getResource().getFile().getName()));
    log.info(String.format("        Description: %1s", execution.getHeader().getDescription()));
    log.info(String.format("       Parameter(s):"));
    IParameterConfiguration configuration = null;
    for (IParameterExecution p : execution.getContent().getElements()) {
        configuration = p.getConfiguration();
        log.info(String.format("               type:[%1s], name:[%2s], value:[%3s], description:[%4s]",
                p.getType(), p.getName(), p.getValue(), configuration.getDescription()));
    }
    log.info(" ");

    for (Future<IExecutionResult> future : futures) {
        try {
            IExecutionResult result = future.get();

            // Dump the execution result of the execution of a processor.
            String message = String.format("Context name:[%1s], status:[%2s], execution:[%4s]",
                    StringUtils.abbreviateMiddle(result.getName(), "...", 50), result.getStatus().toString(),
                    result.getElapsed());
            log.error(message);

            // If process has failed, then dump the exceptions!
            if (result.getStatus() == ExecutionStatusType.FAILED) {
                for (Exception exception : result.getExceptions()) {
                    log.error(String.format("   Exception caught -> %1s", exception.getMessage()), exception);
                }
            }
        } catch (InterruptedException | ExecutionException e) {
            throw new RunnerException("An error occurred due to: " + e.getMessage(), e);
        }
    }

    executor.shutdown();
    watch.stop();

    log.info(" ");
    log.info(String.format("Runner finished processing: [%1d] context(s) in a total of: [%2s]", contexts.size(),
            watch.toString()));
    log.info(
            "*********************************************************************************************************");
}

From source file:org.apache.ambari.server.serveraction.upgrades.AutoSkipFailedSummaryAction.java

/**
 * {@inheritDoc}/*from   www.  j av  a 2s .c  om*/
 */
@Override
public CommandReport execute(ConcurrentMap<String, Object> requestSharedDataContext)
        throws AmbariException, InterruptedException {

    HostRoleCommand hostRoleCommand = getHostRoleCommand();
    long requestId = hostRoleCommand.getRequestId();
    long stageId = hostRoleCommand.getStageId();

    // use the host role command to get to the parent upgrade group
    UpgradeItemEntity upgradeItem = m_upgradeDAO.findUpgradeItemByRequestAndStage(requestId, stageId);
    UpgradeGroupEntity upgradeGroup = upgradeItem.getGroupEntity();

    // find all of the stages in this group
    long upgradeGroupId = upgradeGroup.getId();
    UpgradeGroupEntity upgradeGroupEntity = m_upgradeDAO.findUpgradeGroup(upgradeGroupId);
    List<UpgradeItemEntity> groupUpgradeItems = upgradeGroupEntity.getItems();
    TreeSet<Long> stageIds = new TreeSet<>();
    for (UpgradeItemEntity groupUpgradeItem : groupUpgradeItems) {
        stageIds.add(groupUpgradeItem.getStageId());
    }

    // for every stage, find all tasks that have been SKIPPED_FAILED - we use a
    // bit of trickery here since within any given request, the stage ID are
    // always sequential. This allows us to make a simple query instead of some
    // overly complex IN or NESTED SELECT query
    long minStageId = stageIds.first();
    long maxStageId = stageIds.last();

    List<HostRoleCommandEntity> skippedTasks = m_hostRoleCommandDAO.findByStatusBetweenStages(
            hostRoleCommand.getRequestId(), HostRoleStatus.SKIPPED_FAILED, minStageId, maxStageId);

    if (skippedTasks.isEmpty()) {
        return createCommandReport(0, HostRoleStatus.COMPLETED, "{}", "There were no skipped failures", null);
    }

    StringBuilder buffer = new StringBuilder("The following steps failed and were automatically skipped:\n");

    for (HostRoleCommandEntity skippedTask : skippedTasks) {
        try {
            ServiceComponentHostEventWrapper eventWrapper = new ServiceComponentHostEventWrapper(
                    skippedTask.getEvent());

            ServiceComponentHostEvent event = eventWrapper.getEvent();

            String hostName = skippedTask.getHostName();
            if (null != hostName) {
                Map<String, Object> failures = m_structuredFailures.get(hostName);
                if (null == failures) {
                    failures = new HashMap<>();
                    m_structuredFailures.put(hostName, failures);
                }

                failures.put("id", skippedTask.getTaskId());
                failures.put("exit_code", skippedTask.getExitcode());
                failures.put("output_log", skippedTask.getOutputLog());
                failures.put("error_log", skippedTask.getErrorLog());

                String stdOut = StringUtils.abbreviateMiddle(new String(skippedTask.getStdOut()),
                        MIDDLE_ELLIPSIZE_MARKER, 1000);

                String stderr = StringUtils.abbreviateMiddle(new String(skippedTask.getStdError()),
                        MIDDLE_ELLIPSIZE_MARKER, 1000);

                failures.put("stdout", stdOut);
                failures.put("stderr", stderr);
            }

            buffer.append(event.getServiceComponentName());
            if (null != event.getHostName()) {
                buffer.append(" on ");
                buffer.append(event.getHostName());
            }

            buffer.append(": ");
            buffer.append(skippedTask.getCommandDetail());
            buffer.append("\n");
        } catch (Exception exception) {
            LOG.warn("Unable to extract failure information for {}", skippedTask);
            buffer.append(": ");
            buffer.append(skippedTask);
        }
    }

    String structuredOutput = m_gson.toJson(m_structuredFailures);
    String standardOutput = MessageFormat.format(FAILURE_STD_OUT_TEMPLATE, skippedTasks.size());
    String standardError = buffer.toString();

    return createCommandReport(0, HostRoleStatus.HOLDING, structuredOutput, standardOutput, standardError);
}

From source file:org.apache.tapestry.finder.utils.UrlUtils.java

/**
 * Shorten the given Url string// ww  w .j av a  2  s.  c om
 * 
 * @param url
 * @return
 */
public static String shorten(String url, int length) {

    if (url == null) {
        return "";
    }

    String newUrl = removeProtocol(url);

    if (newUrl.startsWith(CORE_DOCUMENTATION_URL_PREFIX)) {
        return "..." + newUrl.substring(CORE_DOCUMENTATION_URL_PREFIX.length());
    }
    return StringUtils.abbreviateMiddle(newUrl, "...", length);
}

From source file:org.apache.tapestry.unicorn.utils.UrlUtils.java

/**
 * Shorten the given Url string/* www .j a  v a 2s.  c  o m*/
 * 
 * @param url
 * @return
 */
public static String shorten(String url, int length) {

    if (url == null) {
        return "";
    }

    // remove leading http:// or https://
    String newUrl = removeProtocol(url);

    // remove trailing slash, if any
    if (newUrl.endsWith("/")) {
        newUrl = newUrl.substring(0, newUrl.length() - 1);
    }

    if (newUrl.startsWith(CORE_DOCUMENTATION_URL_PREFIX)) {
        return "..." + newUrl.substring(CORE_DOCUMENTATION_URL_PREFIX.length());
    }
    return StringUtils.abbreviateMiddle(newUrl, "...", length);
}

From source file:org.dkpro.lab.engine.impl.BatchTaskEngine.java

@Override
public String run(Task aConfiguration) throws ExecutionException, LifeCycleException {
    if (!(aConfiguration instanceof BatchTask)) {
        throw new ExecutionException("This engine can only execute [" + BatchTask.class.getName() + "]");
    }// w  ww.j  a  va 2s  . c  o  m

    // Create persistence service for injection into analysis components
    TaskContext ctx = null;
    try {
        ctx = contextFactory.createContext(aConfiguration);

        // Now the setup is complete
        ctx.getLifeCycleManager().initialize(ctx, aConfiguration);

        // Start recording
        ctx.getLifeCycleManager().begin(ctx, aConfiguration);

        try {
            BatchTask cfg = (BatchTask) aConfiguration;

            ParameterSpace parameterSpace = cfg.getParameterSpace();

            // Try to calculate the parameter space size.
            int estimatedSize = 1;
            for (Dimension<?> d : parameterSpace.getDimensions()) {
                if (d instanceof FixedSizeDimension) {
                    FixedSizeDimension fsd = (FixedSizeDimension) d;
                    if (fsd.size() > 0) {
                        estimatedSize *= fsd.size();
                    }
                }
            }

            // A subtask execution may apply to multiple parameter space coordinates!
            Set<String> executedSubtasks = new LinkedHashSet<String>();

            ProgressMeter progress = new ProgressMeter(estimatedSize);
            for (Map<String, Object> config : parameterSpace) {
                if (cfg.getConfiguration() != null) {
                    for (Entry<String, Object> e : cfg.getConfiguration().entrySet()) {
                        if (!config.containsKey(e.getKey())) {
                            config.put(e.getKey(), e.getValue());
                        }
                    }
                }

                log.info("== Running new configuration [" + ctx.getId() + "] ==");
                List<String> keys = new ArrayList<String>(config.keySet());
                for (String key : keys) {
                    log.info("[" + key + "]: ["
                            + StringUtils.abbreviateMiddle(Util.toString(config.get(key)), "", 150) + "]");
                }

                executeConfiguration(cfg, ctx, config, executedSubtasks);

                progress.next();
                log.info("Completed configuration " + progress);
            }

            // Set the subtask property and persist again, so the property is available to reports
            cfg.setAttribute(SUBTASKS_KEY, executedSubtasks.toString());
            cfg.persist(ctx);
        } catch (LifeCycleException e) {
            ctx.getLifeCycleManager().fail(ctx, aConfiguration, e);
            throw e;
        } catch (UnresolvedImportException e) {
            // HACK - pass unresolved import exceptions up to the outer batch task
            ctx.getLifeCycleManager().fail(ctx, aConfiguration, e);
            throw e;
        } catch (Throwable e) {
            ctx.getLifeCycleManager().fail(ctx, aConfiguration, e);
            throw new ExecutionException(e);
        }

        // End recording (here the reports will nbe done)
        ctx.getLifeCycleManager().complete(ctx, aConfiguration);

        return ctx.getId();
    } finally {
        if (ctx != null) {
            ctx.getLifeCycleManager().destroy(ctx, aConfiguration);
        }
    }
}

From source file:org.fastmongo.odm.dbobject.mapping.support.classname.ReflectionClassNameResolver.java

@Override
@SuppressWarnings("unchecked")
public String getClassName(Type type, DBObject dbObject, String classPrefix) {
    if (dbObject.containsField(CLASS_KEY)) {
        return restoreClassName((String) dbObject.get(CLASS_KEY), classPrefix);
    }//  w w w .  j  a v  a 2  s . co m

    Class clazz = (Class) type;

    String className = IMPLEMENTATION_BY_INTERFACE.get(clazz);
    if (className == null) {
        Set<Class<?>> subTypes = reflections.getSubTypesOf(clazz);
        if (subTypes.size() == 1) {
            className = subTypes.iterator().next().getName();
        } else {
            className = NO_IMPLEMENTATION;
        }
        IMPLEMENTATION_BY_INTERFACE.put(clazz, className);
    }

    if (!NO_IMPLEMENTATION.equals(className)) {
        return className;
    }

    ResolveStrategy resolveStrategy = findSuitableStrategy(clazz);
    if (resolveStrategy != null) {
        className = resolveStrategy.getClassName(clazz, dbObject);
        className = className.startsWith(classPrefix) ? className : restoreClassName(className, classPrefix);
    }

    if (StringUtils.isEmpty(className)) {
        if (!clazz.isInterface()) {
            return clazz.getName();
        }

        throw new IllegalArgumentException(String.format(
                "Can't find appropriate class name for '%s' and DBObject('%s') with classNamePrefix = %s", type,
                StringUtils.abbreviateMiddle(dbObject.toString(), "<...>", 100), classPrefix));
    }

    return className;
}

From source file:org.gradle.api.internal.tasks.testing.testng.TestNGTestResultProcessorAdapter.java

private String calculateParameterRepresentation(Object parameter) {
    if (parameter == null) {
        return "null";
    } else {/*  w w  w  .j  a  v  a2  s  .c  o m*/
        String toString;
        try {
            toString = parameter.toString();
        } catch (Exception e) {
            return String.format("toString() threw %s", e.toString());
        }

        return StringUtils.abbreviateMiddle(toString, "", 20);
    }
}

From source file:org.zaproxy.zap.extension.spider.ExtensionSpider.java

/**
 * Abbreviates (the middle of) the given display name if greater than 30 characters.
 *
 * @param displayName the display name that might be abbreviated
 * @return the, possibly, abbreviated display name
 *///from   w w w  .ja va 2 s .  co m
private static String abbreviateDisplayName(String displayName) {
    return StringUtils.abbreviateMiddle(displayName, "..", 30);
}