Example usage for com.google.gwt.core.ext GeneratorContext getResourcesOracle

List of usage examples for com.google.gwt.core.ext GeneratorContext getResourcesOracle

Introduction

In this page you can find the example usage for com.google.gwt.core.ext GeneratorContext getResourcesOracle.

Prototype

ResourceOracle getResourcesOracle();

Source Link

Document

Returns a resource oracle containing all resources that are mapped into the module's source (or super-source) paths.

Usage

From source file:com.ait.ext4j.rebind.TemplateGenerator.java

License:Apache License

protected InputStream getTemplateResource(GeneratorContext context, TreeLogger l, String markerPath)
        throws UnableToCompleteException {
    // look for a local file first
    String path = slashify(markerPath);
    l.log(Type.INFO, "Current resource path : " + markerPath);
    Resource res = context.getResourcesOracle().getResourceMap().get(path);
    // if not a local path, try an absolute one
    if (res == null) {
        l.log(Type.INFO, "Resource is Null trying with URL ");
        URL url = Thread.currentThread().getContextClassLoader().getResource(markerPath);
        if (url == null) {
            l.log(Type.INFO, "URL seems to be null here ... hmmmmss");
            return null;
        }/*from  ww w  .  j a  v a 2s  . c om*/
        try {
            return url.openStream();
        } catch (IOException e) {
            l.log(Type.ERROR, "IO Exception occured", e);
            throw new UnableToCompleteException();
        }
    }
    try {
        return res.openContents();
    } catch (Exception e) {
        l.log(Type.ERROR, "Exception occured reading " + path, e);
        throw new UnableToCompleteException();
    }
}

From source file:com.ait.toolkit.rebind.TemplateGenerator.java

License:Open Source License

protected InputStream getTemplateResource(GeneratorContext context, TreeLogger l, String markerPath)
        throws UnableToCompleteException {
    // look for a local file first
    String path = slashify(markerPath);
    l.log(Type.INFO, "Current resource path : " + markerPath);
    Resource res = context.getResourcesOracle().getResourceMap().get(path);
    // if not a local path, try an absolute one
    if (res == null) {
        l.log(Type.INFO, "Resource is Null trying with URL ");
        URL url = Thread.currentThread().getContextClassLoader().getResource(markerPath);
        if (url == null) {
            l.log(Type.INFO, "URL seems to be null here ... hmmmmss");
            return null;
        } else {//  w w w .  ja va 2  s .c o m
            l.log(Type.INFO, "URL seems to be NOT null.");
        }
        try {
            return url.openStream();
        } catch (IOException e) {
            l.log(Type.ERROR, "IO Exception occured", e);
            throw new UnableToCompleteException();
        }
    }
    try {
        return res.openContents();
    } catch (Exception e) {
        l.log(Type.ERROR, "Exception occured reading " + path, e);
        throw new UnableToCompleteException();
    }
}

From source file:com.guit.rebind.common.AbstractGenerator.java

License:Apache License

protected void saveVariables(TreeLogger logger, GeneratorContext context, String typeName) {
    this.logger = logger;
    this.context = context;
    this.typeName = typeName;

    typeOracle = context.getTypeOracle();
    resourceOracle = context.getResourcesOracle();
    propertiesOracle = context.getPropertyOracle();
}

From source file:com.msco.mil.server.com.sencha.gxt.explorer.rebind.SampleGenerator.java

License:sencha.com license

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    // Get access to metadata about the type to be generated
    TypeOracle oracle = context.getTypeOracle();
    JClassType toGenerate = oracle.findType(typeName).isClass();

    // Get the name of the new type
    String packageName = toGenerate.getPackage().getName();
    String simpleSourceName = toGenerate.getName().replace('.', '_') + "Impl";
    PrintWriter pw = context.tryCreate(logger, packageName, simpleSourceName);
    if (pw == null) {
        return packageName + "." + simpleSourceName;
    }/* w w w.jav  a 2s.  co m*/

    // Generate an HTML file resource for every example and write the source
    JClassType[] types = oracle.getTypes();

    // Build a ResourceOracle capable of reading java files
    sourceOracle = new ResourceOracleImpl(logger.branch(Type.DEBUG, "Gathering sources"));

    // Clean up these prefixes to not have filters
    PathPrefixSet prefixes = ((ResourceOracleImpl) context.getResourcesOracle()).getPathPrefixes();
    sourceOracle.setPathPrefixes(new PathPrefixSet());
    for (PathPrefix p : prefixes.values()) {
        sourceOracle.getPathPrefixes().add(new PathPrefix(p.getPrefix(), null));
    }
    ResourceOracleImpl.refresh(logger, sourceOracle);

    // Load the header and footer HTML content
    try {
        String slashyPackageName = getClass().getPackage().getName().replace('.', '/');
        javaHeader = Utility.getFileFromClassPath(slashyPackageName + "/header.html");
        footer = Utility.getFileFromClassPath(slashyPackageName + "/footer.html");
    } catch (IOException e) {
        logger.log(Type.ERROR, "Header or Footer failed to be read", e);
        throw new UnableToCompleteException();
    }

    // Find all examples, annotated with @Detail
    Set<ExampleDetailModel> examples = new HashSet<ExampleDetailModel>();
    Map<String, List<ExampleDetailModel>> hierarchy = new HashMap<String, List<ExampleDetailModel>>();

    Set<SourceModel> exampleSources = new HashSet<SourceModel>();
    for (JClassType type : types) {
        Example.Detail detail = type.getAnnotation(Example.Detail.class);
        if (detail != null) {
            ExampleDetailModel example = new ExampleDetailModel(logger, context, type, detail);

            // Collect sources to be built into html
            exampleSources.addAll(example.getAllSources());

            List<ExampleDetailModel> exampleList = hierarchy.get(detail.category());
            if (exampleList == null) {
                exampleList = new ArrayList<ExampleDetailModel>();
                hierarchy.put(detail.category(), exampleList);
            }
            examples.add(example);
            exampleList.add(example);
        }
    }

    // Sort folders, sort within those folders
    List<String> folders = new ArrayList<String>(hierarchy.keySet());
    Collections.sort(folders);
    for (List<ExampleDetailModel> contents : hierarchy.values()) {
        Collections.sort(contents);
    }

    // Actually build source for each type
    for (SourceModel type : exampleSources) {
        TreeLogger l = logger.branch(Type.DEBUG, "Writing HTML file for " + type.getName());

        // attempt to create the output file
        if (type.getType() == FileType.JAVA) {
            writeTypeToHtml(l, context, type.getJClassType());
        } else {
            writeFileToHtml(l, context, type.getPath());
        }
    }

    // Start making the class, with basic imports
    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleSourceName);
    factory.setSuperclass(typeName);
    factory.addImport(Name.getSourceNameForClass(Category.class));
    factory.addImport(Name.getSourceNameForClass(ImageResource.class));
    factory.addImport(Name.getSourceNameForClass(GWT.class));
    factory.addImport(Name.getSourceNameForClass(Example.class));
    factory.addImport(Name.getSourceNameForClass(Source.class));
    factory.addImport(Name.getSourceNameForClass(Source.FileType.class));
    SourceWriter sw = factory.createSourceWriter(context, pw);

    // Write the ctor
    sw.println("public %1$s() {", simpleSourceName);
    sw.indent();
    // Declare variables that will be used
    sw.println("Category c;");
    sw.println("ImageResource icon;");
    sw.println("Example e;");
    sw.println("Source dir;");
    Set<String> names = new HashSet<String>();
    Map<JClassType, String> bundles = new HashMap<JClassType, String>();
    for (String folder : folders) {
        // TODO escape name
        sw.println("c = new Category(\"%1$s\");", folder);
        for (ExampleDetailModel example : hierarchy.get(folder)) {
            // make sure the bundle to be used exists
            if (!bundles.containsKey(example.getClientBundleType())) {
                String bundleName = getNextName("bundle", names);
                sw.println("%1$s %2$s = GWT.create(%1$s.class);",
                        example.getClientBundleType().getQualifiedSourceName(), bundleName);

                bundles.put(example.getClientBundleType(), bundleName);
            }

            // write out the example, adding it to the current category
            writeExample(sw, bundles.get(example.getClientBundleType()), example);
        }
        sw.println("categories.add(c);");
    }
    sw.outdent();
    sw.println("}");// end ctor

    sw.commit(logger);

    return factory.getCreatedClassName();
}

From source file:com.msco.mil.server.com.sencha.gxt.explorer.rebind.SampleGenerator.java

License:sencha.com license

private void writeFileToHtml(TreeLogger l, GeneratorContext ctx, String path) throws UnableToCompleteException {
    Resource file = ctx.getResourcesOracle().getResourceMap().get(path);
    if (file == null) {
        l.log(Type.ERROR, "File cannot be found.");
        throw new UnableToCompleteException();
    }//  www  .  j a  va2s . co  m
    OutputStream stream = ctx.tryCreateResource(l, "code/" + path.replace('/', '.') + ".html");
    if (stream == null) {
        // file already exists for this compile
        return;
    }
    try {
        InputStream input = file.openContents();
        byte[] bytes = new byte[input.available()];
        input.read(bytes);
        input.close();

        // Write out the HTML file
        // TODO change this header
        stream.write(javaHeader.getBytes());
        stream.write(bytes);
        stream.write(footer.getBytes());

        stream.close();

    } catch (Exception e) {
        l.log(Type.ERROR, "An error occured writing out a file into html", e);
        throw new UnableToCompleteException();
    }

    ctx.commitResource(l, stream);
}

From source file:com.seanchenxi.gwt.storage.rebind.TypeXmlFinder.java

License:Apache License

TypeXmlFinder(GeneratorContext context, TreeLogger logger) {
    this.typeOracle = context.getTypeOracle();
    this.resourceOracle = context.getResourcesOracle();
    this.logger = logger;

    JClassType[] _collectionOrMap = new JClassType[2];
    try {//from   w w  w.  ja  v a 2  s  . c om
        _collectionOrMap[0] = typeOracle.getType(Collection.class.getName());
        _collectionOrMap[1] = typeOracle.getType(Map.class.getName());
    } catch (NotFoundException e) {
        _collectionOrMap = null;
    }
    collectionOrMap = _collectionOrMap;
}

From source file:com.sencha.gxt.core.rebind.XTemplatesGenerator.java

License:sencha.com license

protected InputStream getTemplateResource(GeneratorContext context, JClassType toGenerate, TreeLogger l,
        String markerPath) throws UnableToCompleteException {
    // look for a local file first
    // TODO remove this assumption
    String path = slashify(toGenerate.getPackage().getName()) + "/" + markerPath;
    Resource res = context.getResourcesOracle().getResource(path);
    // if not a local path, try an absolute one
    if (res == null) {
        URL url = Thread.currentThread().getContextClassLoader().getResource(markerPath);
        if (url == null) {
            return null;
        }//from  ww w.j  a va2s  .com
        try {
            return url.openStream();
        } catch (IOException e) {
            logger.log(Type.ERROR, "IO Exception occured", e);
            throw new UnableToCompleteException();
        }
    }
    try {
        return res.openContents();
    } catch (Exception e) {
        logger.log(Type.ERROR, "Exception occured reading " + path, e);
        throw new UnableToCompleteException();
    }
}

From source file:fr.onevu.gwt.uibinder.rebind.UiBinderGenerator.java

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext genCtx, String fqInterfaceName)
        throws UnableToCompleteException {
    TypeOracle oracle = genCtx.getTypeOracle();
    ResourceOracle resourceOracle = genCtx.getResourcesOracle();

    JClassType interfaceType;//w  w w.  ja va 2s . co  m
    try {
        interfaceType = oracle.getType(fqInterfaceName);
    } catch (NotFoundException e) {
        throw new RuntimeException(e);
    }

    DesignTimeUtils designTime;
    if (DesignTimeUtilsImpl.isDesignTime(fqInterfaceName)) {
        designTime = new DesignTimeUtilsImpl();
    } else {
        designTime = DesignTimeUtilsStub.EMPTY;
    }

    String implName = interfaceType.getName().replace('.', '_') + "Impl";
    implName = designTime.getImplName(implName);

    String packageName = interfaceType.getPackage().getName();
    PrintWriterManager writers = new PrintWriterManager(genCtx, logger, packageName);
    PrintWriter printWriter = writers.tryToMakePrintWriterFor(implName);

    if (printWriter != null) {
        generateOnce(interfaceType, implName, printWriter, logger, oracle, resourceOracle,
                genCtx.getPropertyOracle(), writers, designTime);
    }
    return packageName + "." + implName;
}

From source file:fr.putnami.pwt.core.widget.rebind.UiBinderLocalizedCreator.java

License:Open Source License

private Resource getTemplateResource(GeneratorContext context) {
    String packageResourcePath = this.targetType.getPackage().getName().replace('.', '/') + "/";
    ResourceOracle resourceOracle = context.getResourcesOracle();
    Map<String, Resource> reourceMap = new HashMap<>();
    for (Resource resource : resourceOracle.getResources()) {
        reourceMap.put(resource.getPath(), resource);
    }//ww  w  . j  a va 2s . co m
    String templatePath = packageResourcePath + this.templateName + "_" + this.locale
            + UiBinderLocalizedCreator.TEMPLATE_SUFFIX;
    Resource templateResource = reourceMap.get(templatePath);
    if (templateResource == null) {
        this.locale = null;
        templatePath = packageResourcePath + this.templateName + UiBinderLocalizedCreator.TEMPLATE_SUFFIX;
        templateResource = reourceMap.get(templatePath);
    }
    if (templateResource != null) {
        this.templateName = templatePath.replace(packageResourcePath, "");
    }
    return templateResource;
}

From source file:org.broadleafcommerce.openadmin.generator.i18nConstantsGenerator.java

License:Apache License

protected Map<String, String> generateDynamicConstantClasses(JClassType clazz, TreeLogger logger,
        GeneratorContext context) throws NotFoundException {
    ResourceOracle resourceOracle = context.getResourcesOracle();
    Map<String, String> generatedClassses = new HashMap<String, String>();
    String myTypeName = clazz.getQualifiedSourceName().replace('.', '/');
    Map<String, Resource> resourceMap = resourceOracle.getResourceMap();
    for (Map.Entry<String, Resource> entry : resourceMap.entrySet()) {
        if (entry.getKey().contains(myTypeName) && entry.getKey().endsWith(".properties")) {
            String noSuffix = entry.getKey().substring(0, entry.getKey().indexOf(".properties"));
            String position1 = null;
            String position2 = null;
            if (noSuffix.contains("_")) {
                String i18nMatch = noSuffix.substring(noSuffix.lastIndexOf("_") + 1, noSuffix.length());
                if (i18nMatch != null && i18nMatch.length() == 2) {
                    position1 = i18nMatch;
                    noSuffix = noSuffix.substring(0, noSuffix.lastIndexOf("_"));
                    if (noSuffix.contains("_")) {
                        i18nMatch = noSuffix.substring(noSuffix.lastIndexOf("_") + 1, noSuffix.length());
                        if (i18nMatch != null && i18nMatch.length() == 2) {
                            position2 = i18nMatch;
                        }//from  ww w. j  a v a2s  . c o  m
                    }
                }
            }
            String packageName = clazz.getPackage().getName();
            StringBuilder suffix = new StringBuilder();
            if (position1 != null) {
                suffix.append("_");
                suffix.append(position1);
            }
            if (position2 != null) {
                suffix.append("_");
                suffix.append(position2);
            }
            if (position1 == null && position2 == null) {
                suffix.append("_default");
            }
            String simpleName = clazz.getName() + suffix.toString();
            SourceWriter sourceWriter = getSourceWriter(packageName, simpleName, context, logger,
                    new String[] {});
            if (sourceWriter != null) {
                Map<String, String> props = new HashMap<String, String>();
                InputStream is = entry.getValue().openContents();
                try {
                    BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    boolean eof = false;
                    while (!eof) {
                        String temp = in.readLine();
                        if (temp == null) {
                            eof = true;
                        } else {
                            temp = temp.trim();
                            if (!temp.startsWith("#") && temp.length() > 0 && temp.contains("=")) {
                                String key = temp.substring(0, temp.indexOf("=")).trim();
                                String value = temp.substring(temp.indexOf("=") + 1, temp.length()).trim();
                                props.put(key, value);
                            }
                        }
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    try {
                        is.close();
                    } catch (Throwable ignored) {
                    }
                }

                logger.log(TreeLogger.INFO, "Emitting localized code for: " + entry.getKey(), null);
                sourceWriter.println(
                        "private java.util.Map<String, String> i18nProperties = new java.util.HashMap<String, String>();");
                sourceWriter.println("public " + simpleName + "() {");
                for (Map.Entry<String, String> prop : props.entrySet()) {
                    sourceWriter.print("i18nProperties.put(\"");
                    sourceWriter.print(prop.getKey());
                    sourceWriter.print("\",\"");
                    sourceWriter.print(prop.getValue().replace("\"", "\\\""));
                    sourceWriter.print("\");\n");
                }
                sourceWriter.println("}");
                sourceWriter.println("");
                sourceWriter.println("public java.util.Map<String, String> getAlli18nProperties() {");
                sourceWriter.println("return i18nProperties;");
                sourceWriter.println("}");
                sourceWriter.commit(logger);
                logger.log(TreeLogger.INFO, "Done Generating source for " + packageName + "." + simpleName,
                        null);

                generatedClassses.put(suffix.toString().substring(1, suffix.toString().length()),
                        packageName + "." + simpleName);
            }
        }
    }

    return generatedClassses;
}