Search in sources :

Example 1 with StringUtils.repeat

use of org.apache.commons.lang3.StringUtils.repeat in project twister2 by DSC-SPIDAL.

the class ZKJobLister method listJobs.

/**
 * list jobs from ZooKeeper
 */
public static void listJobs() {
    CuratorFramework client = ZKUtils.connectToServer(ZKContext.serverAddresses(config));
    String rootPath = ZKContext.rootNode(config);
    List<JobWithState> jobs;
    try {
        jobs = JobZNodeManager.getJobs(client, rootPath);
    } catch (Exception e) {
        LOG.log(Level.SEVERE, "Could not get jobs from zookeeper", e);
        return;
    }
    if (jobs.size() == 0) {
        LOG.info("\nNumber of all jobs: " + jobs.size());
        return;
    }
    int maxJobIdLength = jobs.stream().mapToInt(j -> j.getJob().getJobId().length()).max().orElseThrow(() -> new RuntimeException("No valid jobID in jobs"));
    List<JobWithState> finishedJobs = jobs.stream().filter(j -> j.finished()).collect(Collectors.toList());
    List<JobWithState> activeJobs = jobs.stream().filter(j -> j.active()).collect(Collectors.toList());
    int jobIDColumn = maxJobIdLength + 3;
    String format = "%-" + jobIDColumn + "s%-12s%s\n";
    int lineWidth = jobIDColumn + 12 + "Number of workers".length();
    String separator = StringUtils.repeat('=', lineWidth);
    StringBuilder buffer = new StringBuilder();
    Formatter f = new Formatter(buffer);
    f.format("\n\n%s", "Number of all jobs: " + jobs.size());
    f.format("\n%s", "");
    f.format("\n%s", "List of finished jobs: " + finishedJobs.size() + "\n");
    outputJobs(finishedJobs, f, format, separator);
    f.format("\n%s", "");
    f.format("\n%s", "List of active jobs: " + activeJobs.size() + "\n");
    outputJobs(activeJobs, f, format, separator);
    LOG.info(buffer.toString());
}
Also used : WorkerWithState(edu.iu.dsc.tws.common.zk.WorkerWithState) CommandLineParser(org.apache.commons.cli.CommandLineParser) SchedulerContext(edu.iu.dsc.tws.api.config.SchedulerContext) ConfigLoader(edu.iu.dsc.tws.common.config.ConfigLoader) Options(org.apache.commons.cli.Options) ZKUtils(edu.iu.dsc.tws.common.zk.ZKUtils) JobWithState(edu.iu.dsc.tws.common.zk.JobWithState) Config(edu.iu.dsc.tws.api.config.Config) ZKPersStateManager(edu.iu.dsc.tws.common.zk.ZKPersStateManager) Logger(java.util.logging.Logger) HelpFormatter(org.apache.commons.cli.HelpFormatter) Collectors(java.util.stream.Collectors) StringUtils(org.apache.commons.lang3.StringUtils) Formatter(java.util.Formatter) Level(java.util.logging.Level) DefaultParser(org.apache.commons.cli.DefaultParser) List(java.util.List) CuratorFramework(org.apache.curator.framework.CuratorFramework) Context(edu.iu.dsc.tws.api.config.Context) ParseException(org.apache.commons.cli.ParseException) ZKContext(edu.iu.dsc.tws.common.zk.ZKContext) CommandLine(org.apache.commons.cli.CommandLine) JobZNodeManager(edu.iu.dsc.tws.common.zk.JobZNodeManager) Option(org.apache.commons.cli.Option) CuratorFramework(org.apache.curator.framework.CuratorFramework) HelpFormatter(org.apache.commons.cli.HelpFormatter) Formatter(java.util.Formatter) JobWithState(edu.iu.dsc.tws.common.zk.JobWithState) ParseException(org.apache.commons.cli.ParseException)

Example 2 with StringUtils.repeat

use of org.apache.commons.lang3.StringUtils.repeat in project hub-detect by blackducksoftware.

the class DetectConfigurationReporter method printWarnings.

public void printWarnings(ReportWriter writer, final List<DetectOption> detectOptions) {
    final List<DetectOption> sortedOptions = sortOptions(detectOptions);
    final List<DetectOption> allWarnings = sortedOptions.stream().filter(it -> it.getWarnings().size() > 0).collect(Collectors.toList());
    if (allWarnings.size() > 0) {
        writer.writeLine("");
        writer.writeLine(StringUtils.repeat("*", 60));
        if (allWarnings.size() == 1) {
            writer.writeLine("WARNING (" + allWarnings.size() + ")");
        } else {
            writer.writeLine("WARNINGS (" + allWarnings.size() + ")");
        }
        for (final DetectOption option : allWarnings) {
            for (final String warning : option.getWarnings()) {
                writer.writeLine(option.getDetectProperty().getPropertyKey() + ": " + warning);
            }
        }
        writer.writeLine(StringUtils.repeat("*", 60));
        writer.writeLine("");
    }
}
Also used : DetectOption(com.blackducksoftware.integration.hub.detect.help.DetectOption) ReportWriter(com.blackducksoftware.integration.hub.detect.workflow.report.writer.ReportWriter) List(java.util.List) DetectOption(com.blackducksoftware.integration.hub.detect.help.DetectOption) Collectors(java.util.stream.Collectors) StringUtils(org.apache.commons.lang3.StringUtils)

Example 3 with StringUtils.repeat

use of org.apache.commons.lang3.StringUtils.repeat in project ASCIIGenome by dariober.

the class Utils method roundNumbers.

/**
 *Parse string x and round the numbers it contains to d decimal places.
 * Typically, x is a raw line read from BED, GFF whatever. What makes a number
 * is guessed from context without too much sophistication.
 * With d < 0, do nothing and return x as it is.
 */
public static String roundNumbers(final String x, int d, TrackFormat trackFormat) {
    if (d < 0) {
        return x;
    }
    // Capture any substring that looks like a number with decimals. Integers are left untouched.
    Pattern p = Pattern.compile("-?\\d+\\.\\d+");
    String xm = x;
    if (trackFormat.equals(TrackFormat.GTF)) {
        // We consider "123.123" in double quotes as a number to comply with cufflinks/StringTie.
        xm = xm.replaceAll("\"", " ");
    }
    Matcher m = p.matcher(xm);
    List<Integer> starts = new ArrayList<Integer>();
    List<Integer> ends = new ArrayList<Integer>();
    List<String> repls = new ArrayList<String>();
    while (m.find()) {
        if (m.group().replace("-", "").startsWith("00")) {
            // We treat something like "000.123" as NaN.
            continue;
        }
        // If these chars precede the captured string, then the string may be an actual number
        if (m.start() == 0 || xm.charAt(m.start() - 1) == '=' || xm.charAt(m.start() - 1) == ' ' || xm.charAt(m.start() - 1) == ',' || xm.charAt(m.start() - 1) == '\t') {
            // If these chars follow the captured string, then the string is an actual number
            if (m.end() == xm.length() || xm.charAt(m.end()) == ';' || xm.charAt(m.end()) == ' ' || xm.charAt(m.end()) == ',' || xm.charAt(m.end()) == '\t') {
                DecimalFormat format;
                if (d == 0) {
                    format = new DecimalFormat("0");
                } else {
                    format = new DecimalFormat("0." + StringUtils.repeat("#", d));
                }
                String newval = format.format(Double.valueOf(m.group()));
                starts.add(m.start());
                ends.add(m.end());
                repls.add(newval);
            }
        }
    }
    if (starts.size() == 0) {
        return x;
    }
    StringBuilder formattedX = new StringBuilder();
    for (int i = 0; i < starts.size(); i++) {
        if (i == 0) {
            formattedX.append(x.substring(0, starts.get(i)));
        } else {
            formattedX.append(x.substring(ends.get(i - 1), starts.get(i)));
        }
        formattedX.append(repls.get(i));
    }
    formattedX.append(x.substring(ends.get(ends.size() - 1)));
    return formattedX.toString();
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) PathMatcher(java.nio.file.PathMatcher) StrMatcher(org.apache.commons.lang3.text.StrMatcher) DecimalFormat(java.text.DecimalFormat) ArrayList(java.util.ArrayList)

Example 4 with StringUtils.repeat

use of org.apache.commons.lang3.StringUtils.repeat in project midpoint by Evolveum.

the class InternalsCachePanel method getCacheInformation.

private String getCacheInformation() {
    StringBuilder sb = new StringBuilder();
    CachesStateInformationType state = MidPointApplication.get().getCacheRegistry().getStateInformation();
    List<KeyValueTreeNode<String, SizeInformation>> trees = new ArrayList<>();
    for (SingleCacheStateInformationType entry : state.getEntry()) {
        KeyValueTreeNode<String, SizeInformation> root = new KeyValueTreeNode<>(entry.getName(), new SizeInformation(entry));
        trees.add(root);
        addComponents(root, entry.getComponent());
    }
    Holder<Integer> maxLabelLength = new Holder<>(0);
    // to avoid issues with log10
    Holder<Integer> maxSize = new Holder<>(1);
    // to avoid issues with log10
    Holder<Integer> maxSecondarySize = new Holder<>(1);
    trees.forEach(tree -> tree.acceptDepthFirst(node -> {
        int labelLength = node.getUserObject().getKey().length() + node.getDepth() * 2;
        int size = node.getUserObject().getValue().size;
        int secondarySize = node.getUserObject().getValue().secondarySize;
        if (labelLength > maxLabelLength.getValue()) {
            maxLabelLength.setValue(labelLength);
        }
        if (size > maxSize.getValue()) {
            maxSize.setValue(size);
        }
        if (secondarySize > maxSecondarySize.getValue()) {
            maxSecondarySize.setValue(secondarySize);
        }
    }));
    int labelSize = Math.max(maxLabelLength.getValue() + 1, 30);
    int sizeSize = Math.max((int) Math.log10(maxSize.getValue()) + 2, 7);
    int secondarySizeSize = Math.max((int) Math.log10(maxSecondarySize.getValue()) + 2, 8);
    int firstPart = labelSize + 3;
    int secondPart = sizeSize + 2;
    int thirdPart = secondarySizeSize + 3;
    String headerFormatString = "  %-" + labelSize + "s | %" + sizeSize + "s | %" + secondarySizeSize + "s\n";
    String valueFormatString = "  %-" + labelSize + "s | %" + sizeSize + "d | %" + secondarySizeSize + "s\n";
    sb.append("\n");
    sb.append(String.format(headerFormatString, "Cache", "Size", "Sec. size"));
    sb.append(StringUtils.repeat("=", firstPart)).append("+").append(StringUtils.repeat("=", secondPart)).append("+").append(StringUtils.repeat("=", thirdPart)).append("\n");
    trees.forEach(tree -> {
        tree.acceptDepthFirst(node -> printNode(sb, valueFormatString, node));
        sb.append(StringUtils.repeat("-", firstPart)).append("+").append(StringUtils.repeat("-", secondPart)).append("+").append(StringUtils.repeat("-", thirdPart)).append("\n");
    });
    return sb.toString();
}
Also used : Holder(com.evolveum.midpoint.util.Holder) SingleCacheStateInformationType(com.evolveum.midpoint.xml.ns._public.common.common_3.SingleCacheStateInformationType) AjaxButton(com.evolveum.midpoint.web.component.AjaxButton) Trace(com.evolveum.midpoint.util.logging.Trace) ObjectUtils.defaultIfNull(org.apache.commons.lang3.ObjectUtils.defaultIfNull) TreeNode(com.evolveum.midpoint.util.TreeNode) StringUtils(org.apache.commons.lang3.StringUtils) MidPointApplication(com.evolveum.midpoint.web.security.MidPointApplication) CachesStateInformationType(com.evolveum.midpoint.xml.ns._public.common.common_3.CachesStateInformationType) ComponentSizeInformationType(com.evolveum.midpoint.xml.ns._public.common.common_3.ComponentSizeInformationType) ArrayList(java.util.ArrayList) List(java.util.List) BasePanel(com.evolveum.midpoint.gui.api.component.BasePanel) Pair(org.apache.commons.lang3.tuple.Pair) AceEditor(com.evolveum.midpoint.web.component.AceEditor) AjaxRequestTarget(org.apache.wicket.ajax.AjaxRequestTarget) IModel(org.apache.wicket.model.IModel) KeyValueTreeNode(com.evolveum.midpoint.util.KeyValueTreeNode) TraceManager(com.evolveum.midpoint.util.logging.TraceManager) KeyValueTreeNode(com.evolveum.midpoint.util.KeyValueTreeNode) Holder(com.evolveum.midpoint.util.Holder) ArrayList(java.util.ArrayList) CachesStateInformationType(com.evolveum.midpoint.xml.ns._public.common.common_3.CachesStateInformationType) SingleCacheStateInformationType(com.evolveum.midpoint.xml.ns._public.common.common_3.SingleCacheStateInformationType)

Example 5 with StringUtils.repeat

use of org.apache.commons.lang3.StringUtils.repeat in project hub-detect by blackducksoftware.

the class DetectConfigurationPrinter method print.

public void print(final PrintStream printStream, final DetectInfo detectInfo, final DetectConfiguration detectConfiguration, final List<DetectOption> detectOptions) throws IllegalArgumentException, IllegalAccessException {
    printStream.println("");
    printStream.println("Current property values:");
    printStream.println("--property = value [notes]");
    printStream.println(StringUtils.repeat("-", 60));
    List<Field> annotatedProperties = new ArrayList<>();
    final Field[] propertyFields = DetectConfiguration.class.getDeclaredFields();
    for (final Field propertyField : propertyFields) {
        final Optional<Annotation> foundField = Arrays.stream(propertyField.getAnnotations()).filter(annotation -> annotation.annotationType() == Value.class).findFirst();
        final int modifiers = propertyField.getModifiers();
        if (foundField.isPresent() && !Modifier.isStatic(modifiers) && Modifier.isPrivate(modifiers)) {
            annotatedProperties.add(propertyField);
        }
    }
    annotatedProperties = annotatedProperties.stream().sorted(new Comparator<Field>() {

        @Override
        public int compare(final Field field1, final Field field2) {
            return field1.getName().compareTo(field2.getName());
        }
    }).collect(Collectors.toList());
    for (final Field field : annotatedProperties) {
        field.setAccessible(true);
        final String fieldName = field.getName();
        Object rawFieldValue;
        rawFieldValue = field.get(detectConfiguration);
        String fieldValue = "";
        if (field.getType().isArray()) {
            fieldValue = String.join(", ", (String[]) rawFieldValue);
        } else {
            if (rawFieldValue != null) {
                fieldValue = rawFieldValue.toString();
            }
        }
        if (!StringUtils.isEmpty(fieldName) && !StringUtils.isEmpty(fieldValue) && "metaClass" != fieldName) {
            final boolean containsPassword = fieldName.toLowerCase().contains("password") || fieldName.toLowerCase().contains("apitoken");
            if (containsPassword) {
                fieldValue = StringUtils.repeat("*", fieldValue.length());
            }
            DetectOption option = null;
            for (final DetectOption opt : detectOptions) {
                if (opt.getFieldName().equals(fieldName)) {
                    option = opt;
                }
            }
            if (option != null && !option.getResolvedValue().equals(fieldValue) && !containsPassword) {
                if (option.interactiveValue != null) {
                    printStream.println(fieldName + " = " + fieldValue + " [interactive]");
                } else if (option.getResolvedValue().equals("latest")) {
                    printStream.println(fieldName + " = " + fieldValue + " [latest]");
                } else if (option.getResolvedValue().trim().length() == 0) {
                    printStream.println(fieldName + " = " + fieldValue + " [calculated]");
                } else {
                    printStream.println(fieldName + " = " + fieldValue + " + [" + option.getResolvedValue() + "]");
                }
            } else {
                printStream.println(fieldName + " = " + fieldValue);
            }
        }
        field.setAccessible(false);
    }
    printStream.println(StringUtils.repeat("-", 60));
    printStream.println("");
}
Also used : PrintStream(java.io.PrintStream) Arrays(java.util.Arrays) DetectOption(com.blackducksoftware.integration.hub.detect.help.DetectOption) Field(java.lang.reflect.Field) Collectors(java.util.stream.Collectors) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) Value(org.springframework.beans.factory.annotation.Value) List(java.util.List) Modifier(java.lang.reflect.Modifier) Annotation(java.lang.annotation.Annotation) Optional(java.util.Optional) Comparator(java.util.Comparator) DetectConfiguration(com.blackducksoftware.integration.hub.detect.DetectConfiguration) DetectInfo(com.blackducksoftware.integration.hub.detect.DetectInfo) ArrayList(java.util.ArrayList) Annotation(java.lang.annotation.Annotation) DetectOption(com.blackducksoftware.integration.hub.detect.help.DetectOption) Field(java.lang.reflect.Field)

Aggregations

List (java.util.List)6 StringUtils (org.apache.commons.lang3.StringUtils)6 DetectOption (com.blackducksoftware.integration.hub.detect.help.DetectOption)2 ArrayList (java.util.ArrayList)2 Collectors (java.util.stream.Collectors)2 DetectConfiguration (com.blackducksoftware.integration.hub.detect.DetectConfiguration)1 DetectInfo (com.blackducksoftware.integration.hub.detect.DetectInfo)1 ReportWriter (com.blackducksoftware.integration.hub.detect.workflow.report.writer.ReportWriter)1 BasePanel (com.evolveum.midpoint.gui.api.component.BasePanel)1 Holder (com.evolveum.midpoint.util.Holder)1 KeyValueTreeNode (com.evolveum.midpoint.util.KeyValueTreeNode)1 TreeNode (com.evolveum.midpoint.util.TreeNode)1 Trace (com.evolveum.midpoint.util.logging.Trace)1 TraceManager (com.evolveum.midpoint.util.logging.TraceManager)1 AceEditor (com.evolveum.midpoint.web.component.AceEditor)1 AjaxButton (com.evolveum.midpoint.web.component.AjaxButton)1 MidPointApplication (com.evolveum.midpoint.web.security.MidPointApplication)1 CachesStateInformationType (com.evolveum.midpoint.xml.ns._public.common.common_3.CachesStateInformationType)1 ComponentSizeInformationType (com.evolveum.midpoint.xml.ns._public.common.common_3.ComponentSizeInformationType)1 SingleCacheStateInformationType (com.evolveum.midpoint.xml.ns._public.common.common_3.SingleCacheStateInformationType)1