Search in sources :

Example 66 with Formatter

use of java.util.Formatter in project bnd by bndtools.

the class JustAnotherPackageManager method listSupportFiles.

private String listSupportFiles(List<File> toDelete) throws Exception {
    try (Formatter f = new Formatter()) {
        if (toDelete == null) {
            toDelete = new ArrayList<File>();
        }
        int precount = toDelete.size();
        File confFile = IO.getFile(platform.getConfigFile()).getCanonicalFile();
        if (confFile.exists()) {
            f.format("    * %s \t0 Config file%n", confFile);
            toDelete.add(confFile);
        }
        String result = (toDelete.size() > precount) ? f.toString() : null;
        return result;
    }
}
Also used : Formatter(java.util.Formatter) JarFile(java.util.jar.JarFile) IO.createTempFile(aQute.lib.io.IO.createTempFile) File(java.io.File)

Example 67 with Formatter

use of java.util.Formatter in project bnd by bndtools.

the class RepoIndex method generateResource.

private Tag generateResource(File file, Map<String, String> config) throws Exception {
    JarResource resource = new JarResource(file);
    List<Capability> caps = new AddOnlyList<Capability>(new LinkedList<Capability>());
    List<Requirement> reqs = new AddOnlyList<Requirement>(new LinkedList<Requirement>());
    Tag resourceTag = new Tag(Schema.ELEM_RESOURCE);
    try {
        // Read config settings and save in thread local state
        if (config != null) {
            URL rootURL;
            String rootURLStr = config.get(ResourceIndexer.ROOT_URL);
            if (rootURLStr != null) {
                File rootDir = new File(rootURLStr);
                if (rootDir.isDirectory())
                    rootURL = rootDir.toURI().toURL();
                else
                    rootURL = new URL(rootURLStr);
            } else
                rootURL = new File(System.getProperty("user.dir")).toURI().toURL();
            String urlTemplate = config.get(ResourceIndexer.URL_TEMPLATE);
            bundleAnalyzer.setStateLocal(new GeneratorState(rootURL.toURI().normalize(), urlTemplate, resolvers));
        } else {
            bundleAnalyzer.setStateLocal(null);
        }
        // Iterate over the analyzers
        try {
            synchronized (analyzers) {
                for (Pair<ResourceAnalyzer, Filter> entry : analyzers) {
                    ResourceAnalyzer analyzer = entry.getFirst();
                    Filter filter = entry.getSecond();
                    if (filter == null || filter.match(resource.getProperties())) {
                        try {
                            analyzer.analyzeResource(resource, caps, reqs);
                        } catch (Exception e) {
                            log(LogService.LOG_ERROR, MessageFormat.format("Error calling analyzer \"{0}\" on resource {1}.", analyzer.getClass().getName(), resource.getLocation()), e);
                            StringWriter writer = new StringWriter();
                            Formatter comment = new Formatter(writer);
                            comment.format("Error calling analyzer \"%s\" on resource %s with message %s and stack: ", analyzer.getClass().getName(), resource.getLocation(), e);
                            comment.close();
                            e.printStackTrace(new PrintWriter(writer));
                            resourceTag.addComment(writer.toString());
                        }
                    }
                }
            }
        } finally {
            bundleAnalyzer.setStateLocal(null);
        }
    } finally {
        resource.close();
    }
    for (Capability cap : caps) {
        Tag capTag = new Tag(Schema.ELEM_CAPABILITY);
        capTag.addAttribute(Schema.ATTR_NAMESPACE, cap.getNamespace());
        appendAttributeAndDirectiveTags(capTag, cap.getAttributes(), cap.getDirectives());
        resourceTag.addContent(capTag);
    }
    for (Requirement req : reqs) {
        Tag reqTag = new Tag(Schema.ELEM_REQUIREMENT);
        reqTag.addAttribute(Schema.ATTR_NAMESPACE, req.getNamespace());
        appendAttributeAndDirectiveTags(reqTag, req.getAttributes(), req.getDirectives());
        resourceTag.addContent(reqTag);
    }
    return resourceTag;
}
Also used : ResourceAnalyzer(org.osgi.service.indexer.ResourceAnalyzer) Capability(org.osgi.service.indexer.Capability) Formatter(java.util.Formatter) URL(java.net.URL) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) Requirement(org.osgi.service.indexer.Requirement) AddOnlyList(org.osgi.service.indexer.impl.util.AddOnlyList) StringWriter(java.io.StringWriter) Filter(org.osgi.framework.Filter) FrameworkUtil.createFilter(org.osgi.framework.FrameworkUtil.createFilter) Tag(org.osgi.service.indexer.impl.util.Tag) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 68 with Formatter

use of java.util.Formatter in project bnd by bndtools.

the class AbstractConsoleApp method __main.

/**
	 * Initialize the repository and other global vars.
	 * 
	 * @param opts the options
	 * @throws IOException
	 */
@Description("")
public void __main(MainOptions opts) throws IOException {
    try {
        setExceptions(opts.exceptions());
        setTrace(opts.trace());
        setPedantic(opts.pedantic());
        if (opts.base() != null)
            setBase(IO.getFile(getBase(), opts.base()));
        else
            setBase(IO.work);
        if (opts.width() > 0)
            this.width = opts.width();
        CommandLine handler = opts._command();
        List<String> arguments = opts._arguments();
        if (arguments.isEmpty()) {
            Justif j = new Justif();
            Formatter f = j.formatter();
            handler.help(f, this);
            err.println(j.wrap());
        } else {
            String cmd = arguments.remove(0);
            String help = handler.execute(this, cmd, arguments);
            if (help != null) {
                err.println(help);
            }
        }
    } catch (InvocationTargetException t) {
        Throwable tt = t;
        while (tt instanceof InvocationTargetException) tt = ((InvocationTargetException) tt).getTargetException();
        exception(tt, "%s", tt);
    } catch (Throwable t) {
        exception(t, "Failed %s", t);
    } finally {
        // Check if we need to wait for it to finish
        if (opts.key()) {
            System.out.println("Hit a key to continue ...");
            System.in.read();
        }
    }
    if (!check(opts.failok())) {
        System.exit(getErrors().size());
    }
}
Also used : CommandLine(aQute.lib.getopt.CommandLine) Justif(aQute.lib.justif.Justif) Formatter(java.util.Formatter) InvocationTargetException(java.lang.reflect.InvocationTargetException) Description(aQute.lib.getopt.Description)

Example 69 with Formatter

use of java.util.Formatter in project bnd by bndtools.

the class Data method validate.

public static String validate(Object o) throws Exception {
    StringBuilder sb = new StringBuilder();
    try (Formatter formatter = new Formatter(sb)) {
        Field[] fields = o.getClass().getFields();
        for (Field f : fields) {
            Validator patternValidator = f.getAnnotation(Validator.class);
            Numeric numericValidator = f.getAnnotation(Numeric.class);
            AllowNull allowNull = f.getAnnotation(AllowNull.class);
            Object value = f.get(o);
            if (value == null) {
                if (allowNull == null)
                    formatter.format("Value for %s must not be null%n", f.getName());
            } else {
                if (patternValidator != null) {
                    Pattern p = Pattern.compile(patternValidator.value());
                    Matcher m = p.matcher(value.toString());
                    if (!m.matches()) {
                        String reason = patternValidator.reason();
                        if (reason.length() == 0)
                            formatter.format("Value for %s=%s does not match pattern %s%n", f.getName(), value, patternValidator.value());
                        else
                            formatter.format("Value for %s=%s %s%n", f.getName(), value, reason);
                    }
                }
                if (numericValidator != null) {
                    if (o instanceof String) {
                        try {
                            o = Double.parseDouble((String) o);
                        } catch (Exception e) {
                            formatter.format("Value for %s=%s %s%n", f.getName(), value, "Not a number");
                        }
                    }
                    try {
                        Number n = (Number) o;
                        long number = n.longValue();
                        if (number >= numericValidator.min() && number < numericValidator.max()) {
                            formatter.format("Value for %s=%s not in valid range (%s,%s]%n", f.getName(), value, numericValidator.min(), numericValidator.max());
                        }
                    } catch (ClassCastException e) {
                        formatter.format("Value for %s=%s [%s,%s) is not a number%n", f.getName(), value, numericValidator.min(), numericValidator.max());
                    }
                }
            }
        }
        if (sb.length() == 0)
            return null;
        if (sb.length() > 0)
            sb.delete(sb.length() - 1, sb.length());
        return sb.toString();
    }
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) Formatter(java.util.Formatter) Field(java.lang.reflect.Field)

Example 70 with Formatter

use of java.util.Formatter in project bnd by bndtools.

the class CommandLine method help.

private String help(Object target, String cmd, Class<? extends Options> type) throws Exception {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);
    if (cmd == null)
        help(f, target);
    else if (type == null)
        help(f, target, cmd);
    else
        help(f, target, cmd, type);
    f.flush();
    justif.wrap(sb);
    return sb.toString();
}
Also used : MarkdownFormatter(aQute.lib.markdown.MarkdownFormatter) Formatter(java.util.Formatter)

Aggregations

Formatter (java.util.Formatter)558 ArrayList (java.util.ArrayList)26 File (java.io.File)25 IOException (java.io.IOException)25 Date (java.util.Date)22 Test (org.junit.Test)19 HashMap (java.util.HashMap)16 Map (java.util.Map)16 AlertDialog (android.app.AlertDialog)14 DialogInterface (android.content.DialogInterface)14 MessageDigest (java.security.MessageDigest)14 PrintWriter (java.io.PrintWriter)13 Justif (aQute.lib.justif.Justif)12 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)11 Locale (java.util.Locale)11 BigInteger (java.math.BigInteger)10 PrintStream (java.io.PrintStream)9 Calendar (java.util.Calendar)7 LayoutBuilder (android.text.StaticLayoutTest.LayoutBuilder)6 View (android.view.View)6