Example usage for java.io BufferedOutputStream flush

List of usage examples for java.io BufferedOutputStream flush

Introduction

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

Prototype

@Override
public synchronized void flush() throws IOException 

Source Link

Document

Flushes this buffered output stream.

Usage

From source file:com.googlecode.jsfFlex.shared.tasks.sdk.UnzipTask.java

protected void performTask() {

    BufferedOutputStream bufferOutputStream = null;
    ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(_file));
    ZipEntry entry;/*  www . ja  v a 2  s  .  c o m*/

    try {

        while ((entry = zipInputStream.getNextEntry()) != null) {

            ensureDirectoryExists(entry.getName(), entry.isDirectory());

            bufferOutputStream = new BufferedOutputStream(new FileOutputStream(_dest + entry.getName()),
                    BUFFER_SIZE);
            int currRead = 0;
            byte[] dataRead = new byte[BUFFER_SIZE];

            while ((currRead = zipInputStream.read(dataRead, 0, BUFFER_SIZE)) != -1) {
                bufferOutputStream.write(dataRead, 0, currRead);
            }
            bufferOutputStream.flush();
            bufferOutputStream.close();
        }

        _log.debug("UnzipTask performTask has been completed with " + toString());
    } catch (IOException ioExcept) {
        StringBuilder errorMessage = new StringBuilder();
        errorMessage.append("Error in Unzip's performTask with following fields \n");
        errorMessage.append(toString());
        throw new ComponentBuildException(errorMessage.toString(), ioExcept);
    } finally {
        try {
            zipInputStream.close();
            if (bufferOutputStream != null) {
                bufferOutputStream.close();
            }
        } catch (IOException innerIOExcept) {
            _log.info("Error while closing the streams within UnzipTask's finally block");
        }
    }

}

From source file:Human1.java

void snapImageFile(String filename, int width, int height) {
    BufferedImage bImage = doRender(width, height);

    /*//  w w  w .  ja  v a2 s  . co m
     * JAI: RenderedImage fImage = JAI.create("format", bImage,
     * DataBuffer.TYPE_BYTE); JAI.create("filestore", fImage, filename +
     * ".tif", "tiff", null);
     */

    /* No JAI: */
    try {
        FileOutputStream fos = new FileOutputStream(filename + ".jpg");
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        JPEGImageEncoder jie = JPEGCodec.createJPEGEncoder(bos);
        JPEGEncodeParam param = jie.getDefaultJPEGEncodeParam(bImage);
        param.setQuality(1.0f, true);
        jie.setJPEGEncodeParam(param);
        jie.encode(bImage);

        bos.flush();
        fos.close();
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:net.ytbolg.mcxa.MCLaucherXA.java

public static String downloadFile(String remoteFilePath) throws IOException {

    URL urlfile = null;//from w  ww  .j a  va  2s . c o m
    HttpURLConnection httpUrl = null;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    File f = new File(GameInfo.Rundir + GameInfo.tpf + "temp.tmp");
    File xxxx = new File(f.getParent());
    //StringWriter sb=new StringWri();
    xxxx.mkdirs();

    //      f.mkdirs();
    try {
        urlfile = new URL(remoteFilePath);
        httpUrl = (HttpURLConnection) urlfile.openConnection();
        httpUrl.connect();
        bis = new BufferedInputStream(httpUrl.getInputStream());
        bos = new BufferedOutputStream(new FileOutputStream(f));

        int len = 2048;
        byte[] b = new byte[len];
        while ((len = bis.read(b)) != -1) {
            bos.write(b, 0, len);
        }
        bos.flush();
        bis.close();
        httpUrl.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            bis.close();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    String x = ReadFile(GameInfo.Rundir + GameInfo.tpf + "temp.tmp");
    f.deleteOnExit();
    return x;
}

From source file:org.apache.flex.compiler.clients.MXMLJSC.java

/**
 * Main body of this program. This method is called from the public static
 * method's for this program./*from w  w w  . j  a va2 s  .  co m*/
 * 
 * @return true if compiler succeeds
 * @throws IOException
 * @throws InterruptedException
 */
protected boolean compile() {
    boolean compilationSuccess = false;

    try {
        setupJS();
        if (!setupTargetFile())
            return false;

        //if (config.isDumpAst())
        //    dumpAST();

        buildArtifact();

        if (jsTarget != null) {
            jsOutputType = JSOutputType.fromString(((JSConfiguration) config).getJSOutputType());

            Collection<ICompilerProblem> errors = new ArrayList<ICompilerProblem>();
            Collection<ICompilerProblem> warnings = new ArrayList<ICompilerProblem>();

            // Don't create a swf if there are errors unless a 
            // developer requested otherwise.
            if (!config.getCreateTargetWithErrors()) {
                problems.getErrorsAndWarnings(errors, warnings);
                if (errors.size() > 0)
                    return false;
            }

            File outputFolder = null;
            // output type specific pre-compile actions
            switch (jsOutputType) {
            case AMD: {
                //

                break;
            }

            case FLEXJS: {
                //

                break;
            }

            case GOOG: {
                jsPublisher = new JSGoogPublisher(config);

                outputFolder = jsPublisher.getOutputFolder();

                if (outputFolder.exists())
                    org.apache.commons.io.FileUtils.deleteQuietly(outputFolder);

                break;
            }
            default: {
                jsPublisher = new JSPublisher(config);

                outputFolder = new File(getOutputFilePath()).getParentFile();
            }
            }

            List<ICompilationUnit> reachableCompilationUnits = project
                    .getReachableCompilationUnitsInSWFOrder(ImmutableSet.of(mainCU));
            for (final ICompilationUnit cu : reachableCompilationUnits) {
                if (cu.getCompilationUnitType() == ICompilationUnit.UnitType.AS_UNIT) {
                    final File outputClassFile = getOutputClassFile(cu.getQualifiedNames().get(0),
                            outputFolder);

                    System.out.println("Compiling file: " + outputClassFile);

                    ICompilationUnit unit = cu;
                    IASWriter jswriter = JSSharedData.backend.createWriter(project,
                            (List<ICompilerProblem>) errors, unit, false);

                    // XXX (mschmalle) hack what is CountingOutputStream?
                    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outputClassFile));
                    jswriter.writeTo(out);
                    out.flush();
                    out.close();
                    jswriter.close();
                }
            }

            // output type specific post-compile actions
            switch (jsOutputType) {
            case AMD: {
                //

                break;
            }

            case FLEXJS: {
                //

                break;
            }

            case GOOG: {
                //

                break;
            }
            }

            jsPublisher.publish();

            compilationSuccess = true;
        }
    } catch (Exception e) {
        final ICompilerProblem problem = new InternalCompilerProblem(e);
        problems.add(problem);
    }

    return compilationSuccess;
}

From source file:edu.ku.brc.helpers.HTTPGetter.java

/**
 * Performs a "generic" HTTP request and fill member variable with results
 * use "getDigirResultsetStr" to get the results as a String
 *
 * @param url URL to be executed//from ww  w .  j  av a 2  s  .  c  o  m
 * @param fileCache the file to place the results
 * @return returns an error code
 */
public byte[] doHTTPRequest(final String url, final File fileCache) {
    byte[] bytes = null;
    Exception excp = null;
    status = ErrorCode.NoError;

    // Create an HttpClient with the MultiThreadedHttpConnectionManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());

    GetMethod method = null;
    try {
        method = new GetMethod(url);

        //log.debug("getting " + method.getURI()); //$NON-NLS-1$
        httpClient.executeMethod(method);

        // get the response body as an array of bytes
        long bytesRead = 0;
        if (fileCache == null) {
            bytes = method.getResponseBody();
            bytesRead = bytes.length;

        } else {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileCache));
            bytes = new byte[4096];
            InputStream ins = method.getResponseBodyAsStream();
            BufferedInputStream bis = new BufferedInputStream(ins);
            while (bis.available() > 0) {
                int numBytes = bis.read(bytes);
                if (numBytes > 0) {
                    bos.write(bytes, 0, numBytes);
                    bytesRead += numBytes;
                }
            }

            bos.flush();
            bos.close();

            bytes = null;
        }

        log.debug(bytesRead + " bytes read"); //$NON-NLS-1$

    } catch (ConnectException ce) {
        excp = ce;
        log.error(String.format("Could not make HTTP connection. (%s)", ce.toString())); //$NON-NLS-1$
        status = ErrorCode.HttpError;

    } catch (HttpException he) {
        excp = he;
        log.error(String.format("Http problem making request.  (%s)", he.toString())); //$NON-NLS-1$
        status = ErrorCode.HttpError;

    } catch (IOException ioe) {
        excp = ioe;
        log.error(String.format("IO problem making request.  (%s)", ioe.toString())); //$NON-NLS-1$
        status = ErrorCode.IOError;

    } catch (java.lang.IllegalArgumentException ioe) {
        excp = ioe;
        log.error(String.format("IO problem making request.  (%s)", ioe.toString())); //$NON-NLS-1$
        status = ErrorCode.IOError;

    } catch (Exception e) {
        excp = e;
        log.error("Error: " + e); //$NON-NLS-1$
        status = ErrorCode.Error;

    } finally {
        // always release the connection after we're done
        if (isThrowingErrors && status != ErrorCode.NoError) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(HTTPGetter.class, excp);
        }

        if (method != null)
            method.releaseConnection();
        //log.debug("Connection released"); //$NON-NLS-1$
    }

    if (listener != null) {
        if (status == ErrorCode.NoError) {
            listener.completed(this);
        } else {
            listener.completedWithError(this, status);
        }
    }

    return bytes;
}

From source file:org.apache.drill.exec.vector.complex.writer.TestJsonReader.java

License:asdf

@Test
public void testSumMultipleBatches() throws Exception {
    String dfs_temp = getDfsTestTmpSchemaLocation();
    File table_dir = new File(dfs_temp, "multi_batch");
    table_dir.mkdir();//from w w w.jav  a 2  s .  co m
    BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(new File(table_dir, "a.json")));
    for (int i = 0; i < 10000; i++) {
        os.write("{ type : \"map\", data : { a : 1 } }\n".getBytes());
        os.write("{ type : \"bigint\", data : 1 }\n".getBytes());
    }
    os.flush();
    os.close();
    String query = "select sum(cast(case when `type` = 'map' then t.data.a else data end as bigint)) `sum` from dfs_test.tmp.multi_batch t";
    try {
        testBuilder().sqlQuery(query).ordered()
                .optionSettingQueriesForTestQuery("alter session set `exec.enable_union_type` = true")
                .baselineColumns("sum").baselineValues(20000L).go();
    } finally {
        testNoResult("alter session set `exec.enable_union_type` = false");
    }
}

From source file:net.wastl.webmail.plugins.SendMessage.java

public HTMLDocument handleURL(String suburl, HTTPSession sess1, HTTPRequestHeader head)
        throws WebMailException, ServletException {
    if (sess1 == null) {
        throw new WebMailException(
                "No session was given. If you feel this is incorrect, please contact your system administrator");
    }/*w w  w . j  a  v  a  2  s .c o m*/
    WebMailSession session = (WebMailSession) sess1;
    UserData user = session.getUser();
    HTMLDocument content;

    Locale locale = user.getPreferredLocale();

    /* Save message in case there is an error */
    session.storeMessage(head);

    if (head.isContentSet("SEND")) {
        /* The form was submitted, now we will send it ... */
        try {
            MimeMessage msg = new MimeMessage(mailsession);

            Address from[] = new Address[1];
            try {
                /**
                 * Why we need
                 * org.bulbul.util.TranscodeUtil.transcodeThenEncodeByLocale()?
                 *
                 * Because we specify client browser's encoding to UTF-8, IE seems
                 * to send all data encoded in UTF-8. We have to transcode all byte
                 * sequences we received to UTF-8, and next we encode those strings
                 * using MimeUtility.encodeText() depending on user's locale. Since
                 * MimeUtility.encodeText() is used to convert the strings into its
                 * transmission format, finally we can use the strings in the
                 * outgoing e-mail which relies on receiver's email agent to decode
                 * the strings.
                 *
                 * As described in JavaMail document, MimeUtility.encodeText() conforms
                 * to RFC2047 and as a result, we'll get strings like "=?Big5?B......".
                 */
                /**
                 * Since data in session.getUser() is read from file, the encoding
                 * should be default encoding.
                 */
                // from[0]=new InternetAddress(MimeUtility.encodeText(session.getUser().getEmail()),
                //                  MimeUtility.encodeText(session.getUser().getFullName()));
                from[0] = new InternetAddress(
                        TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("FROM"), null, locale),
                        TranscodeUtil.transcodeThenEncodeByLocale(session.getUser().getFullName(), null,
                                locale));
            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                from[0] = new InternetAddress(head.getContent("FROM"), session.getUser().getFullName());
            }

            StringTokenizer t;
            try {
                /**
                 * Since data in session.getUser() is read from file, the encoding
                 * should be default encoding.
                 */
                // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("TO")).trim(),",");
                t = new StringTokenizer(
                        TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("TO"), null, locale).trim(),
                        ",");
            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                t = new StringTokenizer(head.getContent("TO").trim(), ",;");
            }

            /* Check To: field, when empty, throw an exception */
            if (t.countTokens() < 1) {
                throw new MessagingException("The recipient field must not be empty!");
            }
            Address to[] = new Address[t.countTokens()];
            int i = 0;
            while (t.hasMoreTokens()) {
                to[i] = new InternetAddress(t.nextToken().trim());
                i++;
            }

            try {
                /**
                 * Since data in session.getUser() is read from file, the encoding
                 * should be default encoding.
                 */
                // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("CC")).trim(),",");
                t = new StringTokenizer(
                        TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("CC"), null, locale).trim(),
                        ",");
            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                t = new StringTokenizer(head.getContent("CC").trim(), ",;");
            }
            Address cc[] = new Address[t.countTokens()];
            i = 0;
            while (t.hasMoreTokens()) {
                cc[i] = new InternetAddress(t.nextToken().trim());
                i++;
            }

            try {
                /**
                 * Since data in session.getUser() is read from file, the encoding
                 * should be default encoding.
                 */
                // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("BCC")).trim(),",");
                t = new StringTokenizer(
                        TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("BCC"), null, locale).trim(),
                        ",");
            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                t = new StringTokenizer(head.getContent("BCC").trim(), ",;");
            }
            Address bcc[] = new Address[t.countTokens()];
            i = 0;
            while (t.hasMoreTokens()) {
                bcc[i] = new InternetAddress(t.nextToken().trim());
                i++;
            }

            session.setSent(false);

            msg.addFrom(from);
            if (to.length > 0) {
                msg.addRecipients(Message.RecipientType.TO, to);
            }
            if (cc.length > 0) {
                msg.addRecipients(Message.RecipientType.CC, cc);
            }
            if (bcc.length > 0) {
                msg.addRecipients(Message.RecipientType.BCC, bcc);
            }
            msg.addHeader("X-Mailer",
                    WebMailServer.getVersion() + ", " + getName() + " plugin v" + getVersion());

            String subject = null;

            if (!head.isContentSet("SUBJECT")) {
                subject = "no subject";
            } else {
                try {
                    // subject=MimeUtility.encodeText(head.getContent("SUBJECT"));
                    subject = TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("SUBJECT"), "ISO8859_1",
                            locale);
                } catch (UnsupportedEncodingException e) {
                    log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                    subject = head.getContent("SUBJECT");
                }
            }

            msg.addHeader("Subject", subject);

            if (head.isContentSet("REPLY-TO")) {
                // msg.addHeader("Reply-To",head.getContent("REPLY-TO"));
                msg.addHeader("Reply-To", TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("REPLY-TO"),
                        "ISO8859_1", locale));
            }

            msg.setSentDate(new Date(System.currentTimeMillis()));

            String contnt = head.getContent("BODY");

            //String charset=MimeUtility.mimeCharset(MimeUtility.getDefaultJavaCharset());
            String charset = "utf-8";

            MimeMultipart cont = new MimeMultipart();
            MimeBodyPart txt = new MimeBodyPart();

            // Transcode to UTF-8
            contnt = new String(contnt.getBytes("ISO8859_1"), "UTF-8");
            // Encode text
            if (locale.getLanguage().equals("zh") && locale.getCountry().equals("TW")) {
                txt.setText(contnt, "Big5");
                txt.setHeader("Content-Type", "text/plain; charset=\"Big5\"");
                txt.setHeader("Content-Transfer-Encoding", "quoted-printable"); // JavaMail defaults to QP?
            } else {
                txt.setText(contnt, "utf-8");
                txt.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
                txt.setHeader("Content-Transfer-Encoding", "quoted-printable"); // JavaMail defaults to QP?
            }

            /* Add an advertisement if the administrator requested to do so */
            cont.addBodyPart(txt);
            if (store.getConfig("ADVERTISEMENT ATTACH").equals("YES")) {
                MimeBodyPart adv = new MimeBodyPart();
                String file = "";
                if (store.getConfig("ADVERTISEMENT SIGNATURE PATH").startsWith("/")) {
                    file = store.getConfig("ADVERTISEMENT SIGNATURE PATH");
                } else {
                    file = parent.getProperty("webmail.data.path") + System.getProperty("file.separator")
                            + store.getConfig("ADVERTISEMENT SIGNATURE PATH");
                }
                String advcont = "";
                try {
                    BufferedReader fin = new BufferedReader(new FileReader(file));
                    String line = fin.readLine();
                    while (line != null && !line.equals("")) {
                        advcont += line + "\n";
                        line = fin.readLine();
                    }
                    fin.close();
                } catch (IOException ex) {
                }

                /**
                 * Transcode to UTF-8; Since advcont comes from file, we transcode
                 * it from default encoding.
                 */
                // Encode text
                if (locale.getLanguage().equals("zh") && locale.getCountry().equals("TW")) {
                    advcont = new String(advcont.getBytes(), "Big5");
                    adv.setText(advcont, "Big5");
                    adv.setHeader("Content-Type", "text/plain; charset=\"Big5\"");
                    adv.setHeader("Content-Transfer-Encoding", "quoted-printable");
                } else {
                    advcont = new String(advcont.getBytes(), "UTF-8");
                    adv.setText(advcont, "utf-8");
                    adv.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
                    adv.setHeader("Content-Transfer-Encoding", "quoted-printable");
                }

                cont.addBodyPart(adv);
            }
            for (String attachmentKey : session.getAttachments().keySet()) {
                ByteStore bs = session.getAttachment(attachmentKey);
                InternetHeaders ih = new InternetHeaders();
                ih.addHeader("Content-Transfer-Encoding", "BASE64");

                PipedInputStream pin = new PipedInputStream();
                PipedOutputStream pout = new PipedOutputStream(pin);

                /* This is used to write to the Pipe asynchronously to avoid blocking */
                StreamConnector sconn = new StreamConnector(pin, (int) (bs.getSize() * 1.6) + 1000);
                BufferedOutputStream encoder = new BufferedOutputStream(MimeUtility.encode(pout, "BASE64"));
                encoder.write(bs.getBytes());
                encoder.flush();
                encoder.close();
                //MimeBodyPart att1=sconn.getResult();
                MimeBodyPart att1 = new MimeBodyPart(ih, sconn.getResult().getBytes());

                if (bs.getDescription() != "") {
                    att1.setDescription(bs.getDescription(), "utf-8");
                }
                /**
                 * As described in FileAttacher.java line #95, now we need to
                 * encode the attachment file name.
                 */
                // att1.setFileName(bs.getName());
                String fileName = bs.getName();
                String localeCharset = getLocaleCharset(locale.getLanguage(), locale.getCountry());
                String encodedFileName = MimeUtility.encodeText(fileName, localeCharset, null);
                if (encodedFileName.equals(fileName)) {
                    att1.addHeader("Content-Type", bs.getContentType());
                    att1.setFileName(fileName);
                } else {
                    att1.addHeader("Content-Type", bs.getContentType() + "; charset=" + localeCharset);
                    encodedFileName = encodedFileName.substring(localeCharset.length() + 5,
                            encodedFileName.length() - 2);
                    encodedFileName = encodedFileName.replace('=', '%');
                    att1.addHeaderLine("Content-Disposition: attachment; filename*=" + localeCharset + "''"
                            + encodedFileName);
                }
                cont.addBodyPart(att1);
            }
            msg.setContent(cont);
            //              }

            msg.saveChanges();

            boolean savesuccess = true;

            msg.setHeader("Message-ID", session.getUserModel().getWorkMessage().getAttribute("msgid"));
            if (session.getUser().wantsSaveSent()) {
                String folderhash = session.getUser().getSentFolder();
                try {
                    Folder folder = session.getFolder(folderhash);
                    Message[] m = new Message[1];
                    m[0] = msg;
                    folder.appendMessages(m);
                } catch (MessagingException e) {
                    savesuccess = false;
                } catch (NullPointerException e) {
                    // Invalid folder:
                    savesuccess = false;
                }
            }

            boolean sendsuccess = false;

            try {
                Transport.send(msg);
                Address sent[] = new Address[to.length + cc.length + bcc.length];
                int c1 = 0;
                int c2 = 0;
                for (c1 = 0; c1 < to.length; c1++) {
                    sent[c1] = to[c1];
                }
                for (c2 = 0; c2 < cc.length; c2++) {
                    sent[c1 + c2] = cc[c2];
                }
                for (int c3 = 0; c3 < bcc.length; c3++) {
                    sent[c1 + c2 + c3] = bcc[c3];
                }
                sendsuccess = true;
                throw new SendFailedException("success", new Exception("success"), sent, null, null);
            } catch (SendFailedException e) {
                session.handleTransportException(e);
            }

            //session.clearMessage();

            content = new XHTMLDocument(session.getModel(),
                    store.getStylesheet("sendresult.xsl", user.getPreferredLocale(), user.getTheme()));
            //              if(sendsuccess) session.clearWork();
        } catch (Exception e) {
            log.error("Could not send messsage", e);
            throw new DocumentNotFoundException("Could not send message. (Reason: " + e.getMessage() + ")");
        }

    } else if (head.isContentSet("ATTACH")) {
        /* Redirect request for attachment (unfortunately HTML forms are not flexible enough to
           have two targets without Javascript) */
        content = parent.getURLHandler().handleURL("/compose/attach", session, head);
    } else {
        throw new DocumentNotFoundException("Could not send message. (Reason: No content given)");
    }
    return content;
}

From source file:com.vangent.hieos.services.xds.repository.transactions.ProvideAndRegisterDocumentSet.java

/**
 *
 * @param m/*from   www  .  j  av a  2  s .  c om*/
 * @param doc
 * @param is
 * @throws com.vangent.hieos.xutil.exception.MetadataException
 * @throws com.vangent.hieos.xutil.exception.XdsIOException
 * @throws com.vangent.hieos.xutil.exception.XdsInternalException
 * @throws com.vangent.hieos.xutil.exception.XdsConfigurationException
 * @throws com.vangent.hieos.xutil.exception.XdsException
 */
private void store_document_swa_xop(Metadata m, XDSDocument doc, InputStream is) throws MetadataException,
        XdsIOException, XdsInternalException, XdsConfigurationException, XdsException {
    this.validateDocumentMetadata(doc, m); // Validate that all is present.

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    BufferedOutputStream bos = new BufferedOutputStream(os);
    int length = 8192; // 8K chunks.
    byte[] buf = new byte[length];
    int size = 0;
    byte[] bytes = null;
    try {
        do {
            size = is.read(buf, 0, length);
            if (size > 0) {
                bos.write(buf, 0, size);
            }
        } while (size > 0);
        bos.flush();
        bytes = os.toByteArray();
    } catch (IOException e) {
        throw new XdsIOException("Error reading from input stream: " + e.getMessage());
    } finally {
        try {
            is.close(); // A bit of a side effect, but OK for now.
            os.close();
            bos.close();
        } catch (IOException e) {
            // Eat exceptions.
            logger.error("Problem closing a stream", e);
        }
    }

    // Set document vitals and store.
    this.setDocumentVitals(bytes, doc, m);
    this.storeDocument(doc);
}

From source file:com.esri.gpt.agp.multipart2.MPart.java

/**
 * Stream data from an input to an output.
 * @param source the input stream/*from   ww w  . j  a v  a2  s.  c o m*/
 * @param destination the output stream
 * @throws IOException if an exception occurs
 */
protected long streamData(InputStream source, OutputStream destination) throws IOException {
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        byte buffer[] = new byte[4096];
        int nRead = 0;
        int nMax = buffer.length;
        long nTotal = 0;
        bis = new BufferedInputStream(source);
        bos = new BufferedOutputStream(destination);
        while ((nRead = bis.read(buffer, 0, nMax)) >= 0) {
            bos.write(buffer, 0, nRead);
            nTotal += nRead;
        }
        return nTotal;
    } finally {
        try {
            if (bos != null)
                bos.flush();
        } catch (Exception ef) {
        }
    }
}

From source file:eu.planets_project.tb.gui.backing.DownloadManager.java

/**
 * /*ww w . ja v  a 2  s .co m*/
 * @return
 * @throws IOException
 */
public String downloadExportedExperiment(String expExportID, String downloadName) {
    FacesContext ctx = FacesContext.getCurrentInstance();

    // Decode the file name (might contain spaces and on) and prepare file object.
    try {
        expExportID = URLDecoder.decode(expExportID, "UTF-8");
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return null;
    }
    File file = expCache.getExportedFile(expExportID);

    HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();

    // Check if file exists and can be read:
    if (!file.exists() || !file.isFile() || !file.canRead()) {
        return "fileNotFound";
    }

    // Get content type by filename.
    String contentType = new MimetypesFileTypeMap().getContentType(file);

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    // Prepare streams.
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        // Open the file:
        input = new BufferedInputStream(new FileInputStream(file));
        int contentLength = input.available();

        // Initialise the servlet response:
        response.reset();
        response.setContentType(contentType);
        response.setContentLength(contentLength);
        response.setHeader("Content-disposition", "attachment; filename=\"" + downloadName + ".xml\"");
        output = new BufferedOutputStream(response.getOutputStream());

        // Write file out:
        for (int data; (data = input.read()) != -1;) {
            output.write(data);
        }

        // Flush the stream:
        output.flush();

        // Tell Faces that we're finished:
        ctx.responseComplete();

    } catch (IOException e) {
        // Something went wrong?
        e.printStackTrace();

    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }
    return "success";
}