Example usage for javax.tools FileObject openInputStream

List of usage examples for javax.tools FileObject openInputStream

Introduction

In this page you can find the example usage for javax.tools FileObject openInputStream.

Prototype

InputStream openInputStream() throws IOException;

Source Link

Document

Returns an InputStream for this file object.

Usage

From source file:org.callimachusproject.rewrite.ProxyPostAdvice.java

protected HttpUriRequest createRequest(String location, Header[] headers, ObjectMessage message,
        FluidBuilder fb) throws IOException, FluidException {
    Object target = message.getTarget();
    Integer bodyIndex = getBodyIndex(message.getMethod());
    if (bodyIndex == null && target instanceof FileObject && contains(headers, "Content-Type")) {
        FileObject file = (FileObject) target;
        InputStream in = file.openInputStream();
        if (in != null) {
            HttpPost req = new HttpPost(location);
            req.setHeaders(headers);/*  w ww  . j  a v  a2s  . c om*/
            if (!contains(headers, "Content-Location")) {
                String uri = file.toUri().toASCIIString();
                req.setHeader("Content-Location", uri);
            }
            req.setEntity(new StreamEntity(in));
            return req;
        }
    }
    if (bodyIndex == null) {
        HttpPost req = new HttpPost(location);
        req.setHeaders(headers);
        return req;
    }
    HttpPost req = new HttpPost(location);
    req.setHeaders(headers);
    Object body = message.getParameters()[bodyIndex];
    Fluid fluid = fb.consume(body, getSystemId(), bodyFluidType);
    req.setEntity(fluid.asHttpEntity());
    return req;
}

From source file:io.druid.storage.s3.S3DataSegmentPuller.java

/**
 * Returns the "version" (aka last modified timestamp) of the URI
 *
 * @param uri The URI to check the last timestamp
 *
 * @return The time in ms of the last modification of the URI in String format
 *
 * @throws IOException//from w  ww. j  a v  a2s.  co m
 */
@Override
public String getVersion(URI uri) throws IOException {
    try {
        final FileObject object = buildFileObject(uri, s3Client);
        // buildFileObject has a hidden input stream that gets open deep in jets3t. This helps prevent resource leaks
        try (InputStream nullStream = object.openInputStream()) {
            return String.format("%d", object.getLastModified());
        }
    } catch (S3ServiceException e) {
        if (S3Utils.isServiceExceptionRecoverable(e)) {
            // The recoverable logic is always true for IOException, so we want to only pass IOException if it is recoverable
            throw new IOException(
                    String.format("Could not fetch last modified timestamp from URI [%s]", uri.toString()), e);
        } else {
            throw Throwables.propagate(e);
        }
    }
}

From source file:ch.rasc.extclassgenerator.ModelAnnotationProcessor.java

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    this.processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,
            "Running " + getClass().getSimpleName());

    if (roundEnv.processingOver() || annotations.size() == 0) {
        return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
    }//  w  w  w.j  a  va 2 s. c  o m

    if (roundEnv.getRootElements() == null || roundEnv.getRootElements().isEmpty()) {
        this.processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "No sources to process");
        return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
    }

    OutputConfig outputConfig = new OutputConfig();

    outputConfig.setDebug(!"false".equals(this.processingEnv.getOptions().get(OPTION_DEBUG)));
    boolean createBaseAndSubclass = "true"
            .equals(this.processingEnv.getOptions().get(OPTION_CREATEBASEANDSUBCLASS));

    String outputFormatString = this.processingEnv.getOptions().get(OPTION_OUTPUTFORMAT);
    outputConfig.setOutputFormat(OutputFormat.EXTJS4);
    if (StringUtils.hasText(outputFormatString)) {
        if (OutputFormat.TOUCH2.name().equalsIgnoreCase(outputFormatString)) {
            outputConfig.setOutputFormat(OutputFormat.TOUCH2);
        } else if (OutputFormat.EXTJS5.name().equalsIgnoreCase(outputFormatString)) {
            outputConfig.setOutputFormat(OutputFormat.EXTJS5);
        }
    }

    String includeValidationString = this.processingEnv.getOptions().get(OPTION_INCLUDEVALIDATION);
    outputConfig.setIncludeValidation(IncludeValidation.NONE);
    if (StringUtils.hasText(includeValidationString)) {
        if (IncludeValidation.ALL.name().equalsIgnoreCase(includeValidationString)) {
            outputConfig.setIncludeValidation(IncludeValidation.ALL);
        } else if (IncludeValidation.BUILTIN.name().equalsIgnoreCase(includeValidationString)) {
            outputConfig.setIncludeValidation(IncludeValidation.BUILTIN);
        }
    }

    outputConfig.setUseSingleQuotes("true".equals(this.processingEnv.getOptions().get(OPTION_USESINGLEQUOTES)));
    outputConfig.setSurroundApiWithQuotes(
            "true".equals(this.processingEnv.getOptions().get(OPTION_SURROUNDAPIWITHQUOTES)));

    for (TypeElement annotation : annotations) {
        Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(annotation);
        for (Element element : elements) {

            try {
                TypeElement typeElement = (TypeElement) element;

                String qualifiedName = typeElement.getQualifiedName().toString();
                Class<?> modelClass = Class.forName(qualifiedName);

                String code = ModelGenerator.generateJavascript(modelClass, outputConfig);

                Model modelAnnotation = element.getAnnotation(Model.class);
                String modelName = modelAnnotation.value();
                String fileName;
                String packageName = "";
                if (StringUtils.hasText(modelName)) {
                    int lastDot = modelName.lastIndexOf('.');
                    if (lastDot != -1) {
                        fileName = modelName.substring(lastDot + 1);
                        int firstDot = modelName.indexOf('.');
                        if (firstDot < lastDot) {
                            packageName = modelName.substring(firstDot + 1, lastDot);
                        }
                    } else {
                        fileName = modelName;
                    }
                } else {
                    fileName = typeElement.getSimpleName().toString();
                }

                if (createBaseAndSubclass) {
                    code = code.replaceFirst("(Ext.define\\([\"'].+?)([\"'],)", "$1Base$2");
                    FileObject fo = this.processingEnv.getFiler().createResource(StandardLocation.SOURCE_OUTPUT,
                            packageName, fileName + "Base.js");
                    OutputStream os = fo.openOutputStream();
                    os.write(code.getBytes(ModelGenerator.UTF8_CHARSET));
                    os.close();

                    try {
                        fo = this.processingEnv.getFiler().getResource(StandardLocation.SOURCE_OUTPUT,
                                packageName, fileName + ".js");
                        InputStream is = fo.openInputStream();
                        is.close();
                    } catch (FileNotFoundException e) {
                        String subClassCode = generateSubclassCode(modelClass, outputConfig);
                        fo = this.processingEnv.getFiler().createResource(StandardLocation.SOURCE_OUTPUT,
                                packageName, fileName + ".js");
                        os = fo.openOutputStream();
                        os.write(subClassCode.getBytes(ModelGenerator.UTF8_CHARSET));
                        os.close();
                    }

                } else {
                    FileObject fo = this.processingEnv.getFiler().createResource(StandardLocation.SOURCE_OUTPUT,
                            packageName, fileName + ".js");
                    OutputStream os = fo.openOutputStream();
                    os.write(code.getBytes(ModelGenerator.UTF8_CHARSET));
                    os.close();
                }

            } catch (ClassNotFoundException e) {
                this.processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage());
            } catch (IOException e) {
                this.processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage());
            }

        }
    }

    return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
}

From source file:org.callimachusproject.behaviours.ZipArchiveSupport.java

public XMLEventReader createAtomFeedFromArchive(final String id, final String entryPattern) throws IOException {
    final FileObject file = this;
    final XMLEventFactory ef = XMLEventFactory.newInstance();
    final byte[] buf = new byte[1024];
    final ZipArchiveInputStream zip = new ZipArchiveInputStream(file.openInputStream());
    return new XMLEventReaderBase() {
        private boolean started;
        private boolean ended;

        public void close() throws XMLStreamException {
            try {
                zip.close();//from  w w  w . j a v a  2  s .c  o m
            } catch (IOException e) {
                throw new XMLStreamException(e);
            }
        }

        protected boolean more() throws XMLStreamException {
            try {
                ZipArchiveEntry entry;
                if (!started) {
                    Namespace atom = ef.createNamespace(FEED.getPrefix(), FEED.getNamespaceURI());
                    add(ef.createStartDocument());
                    add(ef.createStartElement(FEED, null, Arrays.asList(atom).iterator()));
                    add(ef.createStartElement(TITLE, null, null));
                    add(ef.createCharacters(file.getName()));
                    add(ef.createEndElement(TITLE, null));
                    add(ef.createStartElement(ID, null, null));
                    add(ef.createCharacters(id));
                    add(ef.createEndElement(ID, null));
                    Attribute href = ef.createAttribute("href", file.toUri().toASCIIString());
                    List<Attribute> attrs = Arrays.asList(href, ef.createAttribute("type", "application/zip"));
                    add(ef.createStartElement(LINK, attrs.iterator(), null));
                    add(ef.createEndElement(LINK, null));
                    add(ef.createStartElement(UPDATED, null, null));
                    add(ef.createCharacters(format(new Date(file.getLastModified()))));
                    add(ef.createEndElement(UPDATED, null));
                    started = true;
                    return true;
                } else if (started && !ended && (entry = zip.getNextZipEntry()) != null) {
                    String name = entry.getName();
                    String link = entryPattern.replace("{entry}", PercentCodec.encode(name));
                    MimetypesFileTypeMap mimetypes = new javax.activation.MimetypesFileTypeMap();
                    String type = mimetypes.getContentType(name);
                    if (type == null || type.length() == 0) {
                        type = "application/octet-stream";
                    }
                    add(ef.createStartElement(ENTRY, null, null));
                    add(ef.createStartElement(TITLE, null, null));
                    add(ef.createCharacters(name));
                    add(ef.createEndElement(TITLE, null));
                    Attribute href = ef.createAttribute("href", link);
                    List<Attribute> attrs = Arrays.asList(href, ef.createAttribute("type", type));
                    add(ef.createStartElement(LINK, attrs.iterator(), null));
                    add(ef.createEndElement(LINK, null));
                    long size = entry.getSize();
                    if (size > 0) {
                        zip.skip(size);
                    } else {
                        while (zip.read(buf, 0, buf.length) >= 0)
                            ;
                    }
                    add(ef.createEndElement(ENTRY, null));
                    return true;
                } else if (!ended) {
                    add(ef.createEndElement(FEED, null));
                    add(ef.createEndDocument());
                    ended = true;
                    return true;
                } else {
                    return false;
                }
            } catch (IOException e) {
                throw new XMLStreamException(e);
            }
        }
    };
}

From source file:org.jannocessor.processor.JannocessorProcessorBase.java

private FileInformation readFile(Location location, String pkg, String filename) {
    try {//from   www .ja va2  s  . c  o  m
        FileObject file = filer.getResource(location, pkg, filename);

        InputStream inputStream = file.openInputStream();
        String content = IOUtils.toString(inputStream);
        inputStream.close();

        Date lastModified = new Date(file.getLastModified());

        String name = new File(file.toUri()).getCanonicalPath();

        return new DefaultFileInformation(content, name, lastModified);
    } catch (IOException e) {
        return null;
    }
}

From source file:uniol.apt.compiler.AbstractServiceProcessor.java

/**
 * Function that writes a resource list into the class output directory.
 * Existing entries are preserved. This means that this function only ever adds new entries.
 * @param resourceName Name of the file in which the resource list should be saved.
 * @param entries Entries that should be added to the list.
 * @throws IOException In case I/O errors occur.
 *//* w w w.j  a va  2  s . c om*/
protected void writeResourceList(String resourceName, Collection<String> entries) throws IOException {
    entries = new TreeSet<>(entries);

    // read already listed services
    try {
        FileObject fo = this.filer.getResource(StandardLocation.CLASS_OUTPUT, "", resourceName);
        try (InputStream is = fo.openInputStream()) {
            LineIterator lIter = IOUtils.lineIterator(is, "UTF-8");
            while (lIter.hasNext()) {
                String entry = lIter.next();
                entries.add(entry);
            }
        }
    } catch (IOException ex) {
        /* It's ok if the resource can't get found; we only skip reading it */
    }

    // write new list
    FileObject fo = this.filer.createResource(StandardLocation.CLASS_OUTPUT, "", resourceName);
    Writer writer = fo.openWriter();
    for (String entry : entries) {
        writer.append(entry + "\n");
    }
    writer.close();
}