Example usage for java.io Writer Writer

List of usage examples for java.io Writer Writer

Introduction

In this page you can find the example usage for java.io Writer Writer.

Prototype

protected Writer() 

Source Link

Document

Creates a new character-stream writer whose critical sections will synchronize on the writer itself.

Usage

From source file:org.apache.tika.parser.pdf.OCR2XHTML.java

/**
 * Converts the given PDF document (and related metadata) to a stream
 * of XHTML SAX events sent to the given content handler.
 *
 * @param document PDF document//from  w ww. ja va 2s  .com
 * @param handler  SAX content handler
 * @param metadata PDF metadata
 * @throws SAXException  if the content handler fails to process SAX events
 * @throws TikaException if there was an exception outside of per page processing
 */
public static void process(PDDocument document, ContentHandler handler, ParseContext context, Metadata metadata,
        PDFParserConfig config) throws SAXException, TikaException {
    OCR2XHTML ocr2XHTML = null;
    try {
        ocr2XHTML = new OCR2XHTML(document, handler, context, metadata, config);
        ocr2XHTML.writeText(document, new Writer() {
            @Override
            public void write(char[] cbuf, int off, int len) {
            }

            @Override
            public void flush() {
            }

            @Override
            public void close() {
            }
        });
    } catch (IOException e) {
        if (e.getCause() instanceof SAXException) {
            throw (SAXException) e.getCause();
        } else {
            throw new TikaException("Unable to extract PDF content", e);
        }
    }
    if (ocr2XHTML.exceptions.size() > 0) {
        //throw the first
        throw new TikaException("Unable to extract all PDF content", ocr2XHTML.exceptions.get(0));
    }
}

From source file:org.usrz.libs.webtools.utils.JsonMessageBodyWriter.java

@Override
protected void writeTo(Object instance, Annotation[] annotations, Writer writer)
        throws IOException, WebApplicationException {
    mapper.writeValue(new Writer() {

        @Override//from   w  ww.j  a  v a 2  s.  c  o m
        public void write(int c) throws IOException {
            writer.write(c);
        }

        @Override
        public void write(char[] buf, int off, int len) throws IOException {
            writer.write(buf, off, len);
        }

        @Override
        public void flush() throws IOException {
            writer.flush();
        }

        @Override
        public void close() {
            /* Avoid bug in Jackson always closing */
        }

    }, instance);
}

From source file:org.apache.directory.studio.ldapbrowser.core.jobs.ExecuteLdifRunnable.java

public static void executeLdif(IBrowserConnection browserConnection, String ldif, boolean updateIfEntryExists,
        boolean continueOnError, StudioProgressMonitor monitor) {
    monitor.beginTask(BrowserCoreMessages.jobs__execute_ldif_task, 2);
    monitor.reportProgress(" "); //$NON-NLS-1$
    monitor.worked(1);/*from   w  w  w. ja v  a 2 s  . c om*/

    try {
        Reader ldifReader = new StringReader(ldif);
        LdifParser parser = new LdifParser();
        LdifEnumeration enumeration = parser.parse(ldifReader);

        Writer logWriter = new Writer() {
            public void close() {
            }

            public void flush() {
            }

            public void write(char[] cbuf, int off, int len) {
            }
        };

        ImportLdifRunnable.importLdif(browserConnection, enumeration, logWriter, updateIfEntryExists,
                continueOnError, monitor);

        logWriter.close();
        ldifReader.close();
    } catch (Exception e) {
        monitor.reportError(e);
    }
}

From source file:org.eclipse.wst.xsl.jaxp.debug.debugger.AbstractDebugger.java

public synchronized void setTarget(final Writer writer) {
    result = new StreamResult(new Writer() {
        public void write(char[] cbuf, int off, int len) throws IOException {
            writer.write(cbuf, off, len);
            generatedWriter.write(cbuf, off, len);
        }//from  w  w w .  java  2 s.  c om

        public void close() throws IOException {
            writer.close();
            generatedWriter.close();
        }

        public void flush() throws IOException {
            writer.flush();
            generatedWriter.flush();
        }
    });
}

From source file:org.unitime.timetable.server.script.ScriptExecution.java

@Override
protected void execute() throws Exception {
    org.hibernate.Session hibSession = ScriptDAO.getInstance().getSession();

    Transaction tx = hibSession.beginTransaction();
    try {//  w  w  w  .java2  s . co m
        setStatus("Starting up...", 3);

        Script script = ScriptDAO.getInstance().get(iRequest.getScriptId(), hibSession);

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName(script.getEngine());
        engine.put("hibSession", hibSession);
        engine.put("session", SessionDAO.getInstance().get(getSessionId()));
        engine.put("log", this);

        incProgress();

        engine.getContext().setWriter(new Writer() {
            @Override
            public void write(char[] cbuf, int off, int len) throws IOException {
                String line = String.valueOf(cbuf, off, len);
                if (line.endsWith("\n"))
                    line = line.substring(0, line.length() - 1);
                if (!line.isEmpty())
                    info(line);
            }

            @Override
            public void flush() throws IOException {
            }

            @Override
            public void close() throws IOException {
            }
        });
        engine.getContext().setErrorWriter(new Writer() {
            @Override
            public void write(char[] cbuf, int off, int len) throws IOException {
                String line = String.valueOf(cbuf, off, len);
                if (line.endsWith("\n"))
                    line = line.substring(0, line.length() - 1);
                if (!line.isEmpty())
                    warn(line);
            }

            @Override
            public void flush() throws IOException {
            }

            @Override
            public void close() throws IOException {
            }
        });

        incProgress();

        debug("Engine: " + engine.getFactory().getEngineName() + " (ver. "
                + engine.getFactory().getEngineVersion() + ")");
        debug("Language: " + engine.getFactory().getLanguageName() + " (ver. "
                + engine.getFactory().getLanguageVersion() + ")");

        for (ScriptParameter parameter : script.getParameters()) {
            String value = iRequest.getParameters().get(parameter.getName());

            if ("file".equals(parameter.getType()) && iFile != null) {
                debug(parameter.getName() + ": " + iFile.getName() + " (" + iFile.getSize() + " bytes)");
                engine.put(parameter.getName(), iFile);
                continue;
            }

            if (value == null)
                value = parameter.getDefaultValue();
            if (value == null) {
                engine.put(parameter.getName(), null);
                continue;
            }
            debug(parameter.getName() + ": " + value);

            if (parameter.getType().equalsIgnoreCase("boolean")) {
                engine.put(parameter.getName(), "true".equalsIgnoreCase(value));
            } else if (parameter.getType().equalsIgnoreCase("long")) {
                engine.put(parameter.getName(), Long.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("int")
                    || parameter.getType().equalsIgnoreCase("integer")) {
                engine.put(parameter.getName(), Integer.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("double")) {
                engine.put(parameter.getName(), Double.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("float")) {
                engine.put(parameter.getName(), Float.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("short")) {
                engine.put(parameter.getName(), Short.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("byte")) {
                engine.put(parameter.getName(), Byte.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("department")) {
                engine.put(parameter.getName(),
                        DepartmentDAO.getInstance().get(Long.valueOf(value), hibSession));
            } else if (parameter.getType().equalsIgnoreCase("departments")) {
                List<Department> departments = new ArrayList<Department>();
                for (String id : value.split(","))
                    if (!id.isEmpty())
                        departments.add(DepartmentDAO.getInstance().get(Long.valueOf(id), hibSession));
                engine.put(parameter.getName(), departments);
            } else if (parameter.getType().equalsIgnoreCase("subject")) {
                engine.put(parameter.getName(),
                        SubjectAreaDAO.getInstance().get(Long.valueOf(value), hibSession));
            } else if (parameter.getType().equalsIgnoreCase("subjects")) {
                List<SubjectArea> subjects = new ArrayList<SubjectArea>();
                for (String id : value.split(","))
                    if (!id.isEmpty())
                        subjects.add(SubjectAreaDAO.getInstance().get(Long.valueOf(id), hibSession));
                engine.put(parameter.getName(), subjects);
            } else if (parameter.getType().equalsIgnoreCase("building")) {
                engine.put(parameter.getName(), BuildingDAO.getInstance().get(Long.valueOf(value), hibSession));
            } else if (parameter.getType().equalsIgnoreCase("buildings")) {
                List<Building> buildings = new ArrayList<Building>();
                for (String id : value.split(","))
                    if (!id.isEmpty())
                        buildings.add(BuildingDAO.getInstance().get(Long.valueOf(id), hibSession));
                engine.put(parameter.getName(), buildings);
            } else if (parameter.getType().equalsIgnoreCase("room")) {
                engine.put(parameter.getName(), RoomDAO.getInstance().get(Long.valueOf(value), hibSession));
            } else if (parameter.getType().equalsIgnoreCase("rooms")) {
                List<Room> rooms = new ArrayList<Room>();
                for (String id : value.split(","))
                    if (!id.isEmpty())
                        rooms.add(RoomDAO.getInstance().get(Long.valueOf(id), hibSession));
                engine.put(parameter.getName(), rooms);
            } else if (parameter.getType().equalsIgnoreCase("location")) {
                engine.put(parameter.getName(), LocationDAO.getInstance().get(Long.valueOf(value), hibSession));
            } else if (parameter.getType().equalsIgnoreCase("locations")) {
                List<Location> locations = new ArrayList<Location>();
                for (String id : value.split(","))
                    if (!id.isEmpty())
                        locations.add(LocationDAO.getInstance().get(Long.valueOf(id), hibSession));
                engine.put(parameter.getName(), locations);
            } else {
                engine.put(parameter.getName(), value);
            }
        }

        incProgress();

        if (engine instanceof Compilable) {
            setStatus("Compiling script...", 1);
            CompiledScript compiled = ((Compilable) engine).compile(script.getScript());
            incProgress();
            setStatus("Running script...", 100);
            compiled.eval();
        } else {
            setStatus("Running script...", 100);
            engine.eval(script.getScript());
        }

        hibSession.flush();
        tx.commit();

        setStatus("All done.", 1);
        incProgress();
    } catch (Exception e) {
        tx.rollback();
        error("Execution failed: " + e.getMessage(), e);
    } finally {
        hibSession.close();
    }
}

From source file:org.apache.struts2.components.template.FreemarkerTemplateEngine.java

public void renderTemplate(TemplateRenderingContext templateContext) throws Exception {
    // get the various items required from the stack
    ValueStack stack = templateContext.getStack();
    Map context = stack.getContext();
    ServletContext servletContext = (ServletContext) context.get(ServletActionContext.SERVLET_CONTEXT);
    HttpServletRequest req = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
    HttpServletResponse res = (HttpServletResponse) context.get(ServletActionContext.HTTP_RESPONSE);

    // prepare freemarker
    Configuration config = freemarkerManager.getConfiguration(servletContext);

    // get the list of templates we can use
    List templates = templateContext.getTemplate().getPossibleTemplates(this);

    // find the right template
    freemarker.template.Template template = null;
    String templateName = null;// w  w  w. j  a  v  a2  s .co m
    Exception exception = null;
    for (Iterator iterator = templates.iterator(); iterator.hasNext();) {
        Template t = (Template) iterator.next();
        templateName = getFinalTemplateName(t);
        try {
            // try to load, and if it works, stop at the first one
            template = config.getTemplate(templateName);
            break;
        } catch (IOException e) {
            if (exception == null) {
                exception = e;
            }
        }
    }

    if (template == null) {
        LOG.error("Could not load template " + templateContext.getTemplate());
        if (exception != null) {
            throw exception;
        } else {
            return;
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Rendering template " + templateName);
    }

    ActionInvocation ai = ActionContext.getContext().getActionInvocation();

    Object action = (ai == null) ? null : ai.getAction();
    SimpleHash model = freemarkerManager.buildTemplateModel(stack, action, servletContext, req, res,
            config.getObjectWrapper());

    model.put("tag", templateContext.getTag());
    model.put("themeProperties", getThemeProps(templateContext.getTemplate()));

    // the BodyContent JSP writer doesn't like it when FM flushes automatically --
    // so let's just not do it (it will be flushed eventually anyway)
    Writer writer = templateContext.getWriter();
    if (bodyContent != null && bodyContent.isAssignableFrom(writer.getClass())) {
        final Writer wrapped = writer;
        writer = new Writer() {
            public void write(char cbuf[], int off, int len) throws IOException {
                wrapped.write(cbuf, off, len);
            }

            public void flush() throws IOException {
                // nothing!
            }

            public void close() throws IOException {
                wrapped.close();
            }
        };
    }

    try {
        stack.push(templateContext.getTag());
        template.process(model, writer);
    } finally {
        stack.pop();
    }
}

From source file:com.google.gdt.eclipse.designer.actions.AbstractModuleAction.java

/**
 * Shows the {@link Throwable} to user.//www  .  j av a  2 s  .  c om
 */
public static void showException(final Throwable exception) {
    // log
    DesignerPlugin.log(exception);
    // show
    {
        final Throwable rootCause = DesignerExceptionUtils.getDesignerCause(exception);
        final Status status = new Status(IStatus.ERROR, DesignerPlugin.getDefault().toString(), IStatus.ERROR,
                "Parse error or internal Designer error.", rootCause);
        ErrorDialog dialog = new ErrorDialog(DesignerPlugin.getShell(), "Exception happened",
                "Designer error occurred.\nSelect Details>> for more information.\nSee the Error Log for more information.",
                status, IStatus.ERROR) {
            private Clipboard clipboard;

            @Override
            protected org.eclipse.swt.widgets.List createDropDownList(Composite parent) {
                final org.eclipse.swt.widgets.List list = super.createDropDownList(parent);
                list.removeAll();
                // populate list using custom PrintWriter
                list.add("Plug-in Provider: Google");
                list.add("Plug-in Name: " + BrandingUtils.getBranding().getProductName());
                list.add("Plug-in ID: org.eclipse");
                //list.add("Plug-in Version: " + String.valueOf(product.getVersion()));
                list.add("");
                final PrintWriter printWriter = new PrintWriter(new Writer() {
                    @Override
                    public void write(char[] cbuf, int off, int len) throws IOException {
                        if (len != 2 && !(cbuf[0] == '\r' || cbuf[0] == '\n')) {
                            list.add(StringUtils.replace(new String(cbuf, off, len), "\t", "    "));
                        }
                    }

                    @Override
                    public void flush() throws IOException {
                    }

                    @Override
                    public void close() throws IOException {
                    }
                });
                if (rootCause != null) {
                    rootCause.printStackTrace(printWriter);
                    list.add("");
                    list.add("Full stack trace (to see full context):");
                }
                exception.printStackTrace(printWriter);
                // print config
                list.add("");
                // install own context menu
                Menu menu = list.getMenu();
                menu.dispose();
                Menu copyMenu = new Menu(list);
                MenuItem copyItem = new MenuItem(copyMenu, SWT.NONE);
                copyItem.setText(JFaceResources.getString("copy")); //$NON-NLS-1$
                copyItem.addSelectionListener(new SelectionListener() {
                    public void widgetSelected(SelectionEvent e) {
                        copyList(list);
                    }

                    public void widgetDefaultSelected(SelectionEvent e) {
                        copyList(list);
                    }
                });
                list.setMenu(copyMenu);
                return list;
            }

            private void copyList(org.eclipse.swt.widgets.List list) {
                if (clipboard != null) {
                    clipboard.dispose();
                }
                StringBuffer statusBuffer = new StringBuffer();
                for (int i = 0; i < list.getItemCount(); ++i) {
                    statusBuffer.append(list.getItem(i));
                    statusBuffer.append("\r\n");
                }
                clipboard = new Clipboard(list.getDisplay());
                clipboard.setContents(new Object[] { statusBuffer.toString() },
                        new Transfer[] { TextTransfer.getInstance() });
            }

            @Override
            public boolean close() {
                if (clipboard != null) {
                    clipboard.dispose();
                }
                return super.close();
            }
        };
        dialog.open();
    }
}

From source file:org.apache.tika.parser.pdf.PDF2XHTML.java

/**
 * Converts the given PDF document (and related metadata) to a stream
 * of XHTML SAX events sent to the given content handler.
 *
 * @param document PDF document//from w w w.  ja  v a 2s.  c o m
 * @param handler  SAX content handler
 * @param metadata PDF metadata
 * @throws SAXException  if the content handler fails to process SAX events
 * @throws TikaException if the PDF document can not be processed
 */
public static void process(PDDocument document, ContentHandler handler, ParseContext context, Metadata metadata,
        PDFParserConfig config) throws SAXException, TikaException {
    try {
        // Extract text using a dummy Writer as we override the
        // key methods to output to the given content
        // handler.
        PDF2XHTML pdf2XHTML = new PDF2XHTML(handler, context, metadata, config);

        config.configure(pdf2XHTML);

        pdf2XHTML.writeText(document, new Writer() {
            @Override
            public void write(char[] cbuf, int off, int len) {
            }

            @Override
            public void flush() {
            }

            @Override
            public void close() {
            }
        });

    } catch (IOException e) {
        if (e.getCause() instanceof SAXException) {
            throw (SAXException) e.getCause();
        } else {
            throw new TikaException("Unable to extract PDF content", e);
        }
    }
}

From source file:org.apache.directory.studio.ldapbrowser.core.jobs.ImportLdifRunnable.java

/**
 * {@inheritDoc}//from   w w  w  .jav  a  2s  .c om
 */
public void run(StudioProgressMonitor monitor) {
    monitor.beginTask(BrowserCoreMessages.jobs__import_ldif_task, 2);
    monitor.reportProgress(" "); //$NON-NLS-1$
    monitor.worked(1);

    try {
        Reader ldifReader = new BufferedReader(new FileReader(this.ldifFile));
        LdifParser parser = new LdifParser();
        LdifEnumeration enumeration = parser.parse(ldifReader);

        Writer logWriter;
        if (this.logFile != null) {
            logWriter = new BufferedWriter(new FileWriter(this.logFile));
        } else {
            logWriter = new Writer() {
                public void close() throws IOException {
                }

                public void flush() throws IOException {
                }

                public void write(char[] cbuf, int off, int len) throws IOException {
                }
            };
        }

        importLdif(browserConnection, enumeration, logWriter, updateIfEntryExists, continueOnError, monitor);

        logWriter.close();
        ldifReader.close();
    } catch (Exception e) {
        monitor.reportError(e);
    }
}

From source file:org.ajax4jsf.webapp.CacheContent.java

public PrintWriter getWriter() {
    if (null == servletWriter) {
        stringOutputWriter = new FastBufferWriter(1024);
        Writer out = new Writer() {

            public void write(char[] cbuf, int off, int len) throws IOException {
                stringOutputWriter.write(cbuf, off, len);
            }//w ww .j av  a2s.c o  m

            public void flush() throws IOException {
            }

            public void close() throws IOException {
                // / writerContent = stringOutputWriter.toString();
                filledOutputWriter = true;
                writerContent = null;
            }

        };
        servletWriter = new PrintWriter(out);
    }
    return servletWriter;
}