Example usage for com.google.gwt.dev.resource Resource openContents

List of usage examples for com.google.gwt.dev.resource Resource openContents

Introduction

In this page you can find the example usage for com.google.gwt.dev.resource Resource openContents.

Prototype

public abstract InputStream openContents() throws IOException;

Source Link

Document

Returns the contents of the resource.

Usage

From source file:cc.alcina.framework.entity.gen.SimpleCssResourceGenerator.java

License:Apache License

private String replaceWithDataUrls(ResourceContext context, String toWrite) throws Exception {
    Pattern urlPat = Pattern.compile("url\\s*\\((?!'?data:)(?!http:)(.+?)\\)");
    Matcher m = urlPat.matcher(toWrite);
    while (m.find()) {
        String url = m.group(1);/*from   w w w .  j a v a 2  s  . c o m*/
        int qIdx = url.indexOf('?');
        if (qIdx != -1) {
            url = url.substring(0, qIdx);
        }
        // url = url.replaceFirst("(.+?)\\?.*", "$1");
        url = url.replace("'", "").replace("\"", "");
        StandardGeneratorContext generatorContext = (StandardGeneratorContext) context.getGeneratorContext();
        Field compilerContextField = StandardGeneratorContext.class.getDeclaredField("compilerContext");
        compilerContextField.setAccessible(true);
        CompilerContext compilerContext = (CompilerContext) compilerContextField.get(generatorContext);
        Field moduleField = CompilerContext.class.getDeclaredField("module");
        moduleField.setAccessible(true);
        ModuleDef module = (ModuleDef) moduleField.get(compilerContext);
        Resource resource = module.findPublicFile(url);
        if (resource == null) {
            resource = module.findPublicFile("gwt/standard/" + url);
        }
        if (resource == null) {
            if (url.contains("://")) {
                continue;
            } else {
                if (logMissingUrlResources) {
                    String[] pub = getAllPublicFiles(module);
                    // System.out.println("missing url resource - " + url);
                    for (String path : pub) {
                        if (path.contains(url)) {
                            System.out.format("Maybe - %s : %s\n", url, path);
                        }
                    }
                }
                continue;
            }
        }
        InputStream contents = resource.openContents();
        byte[] bytes = ResourceUtilities.readStreamToByteArray(contents);
        String out = Base64.encodeBytes(bytes);
        String fileName = url.replaceFirst(".+/", "");
        String extension = fileName.replaceFirst(".+\\.", "");
        String mimeType = null;
        if (extension.toLowerCase().equals("gif")) {
            mimeType = "image/gif";
        } else if (extension.toLowerCase().equals("jpeg")) {
            mimeType = "image/jpeg";
        } else if (extension.toLowerCase().equals("jpg")) {
            mimeType = "image/jpeg";
        } else if (extension.toLowerCase().equals("png")) {
            mimeType = "image/png";
        }
        if (mimeType != null) {
            String encoded = String.format("url(data:%s;base64,%s)", mimeType, out.replace("\n", ""));
            if (encoded.length() > 5000) {
                // System.out.println("warn - large css sprite - " + url);
            }
            if (encoded.length() < MAX_DATA_URL_LENGTH) {
                toWrite = m.replaceFirst(encoded);
                m = urlPat.matcher(toWrite);
            }
        } else {
            System.out.println("unable to resolve mime type - " + url);
            // continue on
        }
    }
    return toWrite;
}

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  w w  w. j a v a2 s . c o m
        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 {/*from w w w. j a  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.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();
    }//from   ww w . j  ava2  s . c o 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

private StorageSerialization parseXmlResource(Resource resource) throws UnableToCompleteException {
    InputStream input = null;/*from ww  w.ja  va  2s .c  om*/
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(StorageSerialization.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        Source source = createSAXSource(input = resource.openContents());
        StorageSerialization storageSerialization = (StorageSerialization) unmarshaller.unmarshal(source);
        storageSerialization.setPath(resource.getPath());
        return storageSerialization;
    } catch (Exception e) {
        logger.branch(TreeLogger.Type.WARN, "Error while parsing xml resource at " + resource.getPath(), e);
        throw new UnableToCompleteException();
    } finally {
        try {
            if (input != null)
                input.close();
        } catch (Exception e) {
            //To ignore
        }
    }
}

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  www.java  2s.  co  m
        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.GwtResourceEntityResolver.java

License:Apache License

@Override
public InputSource resolveEntity(String publicId, String systemId) {
    String matchingPrefix = findMatchingPrefix(systemId);

    Resource resource = null;
    Map<String, Resource> map = resourceOracle.getResourceMap();
    if (matchingPrefix != null) {
        resource = map.get(RESOURCES + systemId.substring(matchingPrefix.length()));
    }// w  w w .  ja  v a 2  s  . co m

    if (resource == null) {
        resource = map.get(pathBase + systemId);
    }

    if (resource != null) {
        String content;
        try {
            InputStream resourceStream = resource.openContents();
            content = Util.readStreamAsString(resourceStream);
        } catch (IOException ex) {
            logger.log(TreeLogger.ERROR, "Error reading resource: " + resource.getLocation());
            throw new RuntimeException(ex);
        }
        InputSource inputSource = new InputSource(new StringReader(content));
        inputSource.setPublicId(publicId);
        inputSource.setSystemId(resource.getPath());
        return inputSource;
    }
    /*
     * Let Sax find it on the interweb.
     */
    return null;
}

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

License:Apache License

private Document getW3cDoc(MortalLogger logger, DesignTimeUtils designTime, ResourceOracle resourceOracle,
        String templatePath) throws UnableToCompleteException {

    Resource resource = resourceOracle.getResourceMap().get(templatePath);
    if (null == resource) {
        logger.die("Unable to find resource: " + templatePath);
    }//from   ww  w .  j  a va  2  s  . c  o  m

    Document doc = null;
    try {
        String content = designTime.getTemplateContent(templatePath);
        if (content == null) {
            content = Util.readStreamAsString(resource.openContents());
        }
        doc = new W3cDomHelper(logger.getTreeLogger(), resourceOracle).documentFor(content, resource.getPath());
    } catch (IOException iex) {
        logger.die("Error opening resource:" + resource.getLocation(), iex);
    } catch (SAXParseException e) {
        logger.die("Error parsing XML (line " + e.getLineNumber() + "): " + e.getMessage(), e);
    }
    return doc;
}

From source file:org.cruxframework.crux.core.rebind.crossdevice.CrossDevicesTemplateParser.java

License:Apache License

public Document getDeviceAdaptiveTemplate(Resource resource) {
    if (resource != null) {
        try {/* w ww. ja va  2s .c om*/
            InputStream stream = resource.openContents();
            try {
                return documentBuilder.parse(stream);
            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (IOException e) {
                        // do nothing
                    }
                }
            }
        } catch (Exception e) {
            return null;
        }
    }
    return null;
}

From source file:org.cruxframework.crux.core.rebind.screen.ScreenFactory.java

License:Apache License

/**
 * Factory method for screens./*from w w  w.ja  va2s  .co  m*/
 * @param id
 * @param device device property for this permutation being compiled
 * @return
 * @throws ScreenConfigException
 */
public Screen getScreen(String id, String device) throws ScreenConfigException {
    try {
        String cacheKey = device == null ? id : id + "_" + device;

        Screen screen = screenCache.get(cacheKey);
        if (screen != null) {
            return screen;
        }

        Resource resource = screenLoader.getScreen(id);
        if (resource == null) {
            throw new ScreenConfigException("Error retrieving screen [" + id + "].crux.xml.");
        }
        InputStream inputStream = resource.openContents();
        Document screenView = viewFactory.getViewDocument(id, device, inputStream);
        StreamUtils.safeCloseStream(inputStream);
        if (screenView == null) {
            throw new ScreenConfigException("Screen [" + id + "].crux.xml not found!");
        }
        screen = parseScreen(id, device, screenView, resource.getLastModified());
        if (screen != null) {
            screen.setLastModified(resource.getLastModified());
            screenCache.put(cacheKey, screen);
        }
        return screen;

    } catch (IOException e) {
        throw new ScreenConfigException("Error retrieving screen [" + id + "].crux.xml.", e);
    }
}