Example usage for java.io ByteArrayOutputStream flush

List of usage examples for java.io ByteArrayOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:com.farmafene.aurius.mngt.impl.DirectoryWorker.java

/**
 * {@inheritDoc}/*from w ww . ja  v a  2s .co  m*/
 * 
 * @see java.lang.Runnable#run()
 */
@Override
public void run() {
    if (logger.isInfoEnabled()) {
        logger.info(this + "<running>");
    }
    for (;;) {
        CallStatus status = null;
        if (logger.isDebugEnabled()) {
            logger.debug(this + "<waiting>");
        }
        try {
            status = queue.take();
        } catch (InterruptedException e) {
            logger.info(this + ": Interrumpido", e);
            break;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Procesando: " + status);
        }
        Date exDate = new Date(status.getInitTime());
        String fileName = Configuracion.getConfigPath();
        File f = new File(fileName);
        f = f.getParentFile();
        f = new File(f, "logs");
        File dirBase = new File(f, df.format(exDate));
        if (logger.isDebugEnabled()) {
            logger.debug("Log Base: " + f.getPath());
        }
        File logFile = null;
        if (!dirBase.exists()) {
            dirBase.mkdirs();
        }
        try {
            String dirNop = String.format(String.format("%1$08x", status.hashCode()));
            logFile = new File(dirBase, "tx");
            logFile = new File(logFile, dirNop.substring(0, 2));
            logFile = new File(logFile, dirNop.substring(2, 4));
            logFile = new File(logFile, dirNop.substring(4, 6));
            // logFile = new File(logFile, dirNop.substring(6));
            if (!logFile.exists()) {
                logFile.mkdirs();
            }
            String fff = status.getContexto().getId().toString();
            fff = fff + df2.format(exDate) + ".xml";

            logFile = new File(logFile, fff);
            FileOutputStream appendedFile = new FileOutputStream(
                    new File(dirBase, "listado." + df3.format(exDate).substring(0, 4) + "0.html"), true);
            FileWorker work = new FileWorker();
            work.setFile(logFile);
            work.setStatus(status);
            if (logger.isDebugEnabled()) {
                logger.debug("Enviando Status:" + work);
            }
            workManager.scheduleWork(work);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintWriter pf = new PrintWriter(baos);
            pf.print("<a href=\"");
            pf.print(makeRelative(logFile, dirBase.getPath()));
            pf.print("\">");
            pf.print(logFile.getName());
            pf.print("</a><br/>");
            pf.flush();
            baos.flush();
            appendedFile.write(baos.toString().getBytes());
            appendedFile.flush();
            appendedFile.close();
        } catch (FileNotFoundException e) {
            logger.error(e);
        } catch (IOException e) {
            logger.error(e);
        } catch (WorkException e) {
            logger.error(e);
        }

    }

}

From source file:org.kaaproject.avro.ui.sandbox.services.AvroUiSandboxServiceImpl.java

@Override
public String getJsonStringFromRecord(RecordField field) throws AvroUiSandboxServiceException {
    try {//  w ww  . j a v a 2  s . c o m
        GenericRecord record = FormAvroConverter.createGenericRecordFromRecordField(field);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        JsonGenerator jsonGenerator = new JsonFactory().createJsonGenerator(baos, JsonEncoding.UTF8);
        jsonGenerator.useDefaultPrettyPrinter();
        JsonEncoder jsonEncoder = EncoderFactory.get().jsonEncoder(record.getSchema(), jsonGenerator);
        DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(record.getSchema());
        datumWriter.write(record, jsonEncoder);
        jsonEncoder.flush();
        baos.flush();
        return new String(baos.toByteArray(), UTF8);
    } catch (Exception e) {
        throw Utils.handleException(e);
    }
}

From source file:org.alinous.net.mail.MailBodyCommand.java

public void sendCommand(Socket con) throws IOException {
    StringBuffer buffer = new StringBuffer();

    buffer.append("FROM: " + this.fromAddress + "\r\n");
    appendTo(buffer);/*from   w w  w  .ja v  a2  s . com*/
    appendCc(buffer);

    // encoding
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    outStream.write(buffer.toString().getBytes(this.proto.getLangEncoding()));

    appendBody(outStream);

    outStream.flush();
    outStream.close();

    sendCommand(outStream.toByteArray(), con);
}

From source file:net.sf.xmm.moviemanager.http.HttpUtil.java

public HTTPResult readData(URL url) throws TimeoutException, Exception {

    if (!isSetup())
        setup();//from  w ww  .  jav a 2 s  .  c  om

    GetMethod method = new GetMethod(url.toString());
    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {
        log.debug("HTTP StatusCode not HttpStatus.SC_OK:" + method.getStatusLine());
        log.debug("For url:" + url.toString());
    }

    if (statusCode == HttpStatus.SC_REQUEST_TIMEOUT) {
        throw new TimeoutException();
    }

    //java.io.BufferedReader stream = new java.io.BufferedReader(new java.io.InputStreamReader(method.getResponseBodyAsStream(), "ISO-8859-1"));

    StringBuffer data = new StringBuffer();

    // Saves the page data in a string buffer... 
    String chrSet = method.getResponseCharSet();
    InputStream input = method.getResponseBodyAsStream();
    ByteArrayOutputStream temp = new ByteArrayOutputStream();
    byte[] buff = new byte[1500];
    int read;
    while ((read = input.read(buff)) >= 0) {
        temp.write(buff, 0, read);
    }
    input.close();
    temp.flush();
    buff = temp.toByteArray();
    temp.close();
    data.append(new String(buff, chrSet));

    return new HTTPResult(url, statusCode == HttpStatus.SC_OK ? data : null, method.getStatusLine());
}

From source file:be.solidx.hot.test.TestScriptExecutors.java

@Test
public void testScriptEncodingGroovy() throws Exception {
    Script<CompiledScript> script = new Script<CompiledScript>(
            IOUtils.toByteArray(getClass().getResourceAsStream("/frenchScript.groovy")), "french");
    FileOutputStream fileOutputStream = new FileOutputStream(new File("testiso.txt"));
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(bos, "ISO8859-1");

    groovyScriptExecutor.execute(script, outputStreamWriter);
    outputStreamWriter.flush();// w ww . j  a  v  a2 s.co  m
    bos.flush();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    OutputStreamWriter writer = new OutputStreamWriter(outputStream, "ISO8859-1");
    writer.append(new String(bos.toByteArray(), "iso8859-1"));
    writer.flush();
    writer.close();
    fileOutputStream.write(outputStream.toByteArray());
    fileOutputStream.close();
    new File("testiso.txt").delete();
}

From source file:com.liferay.mobile.android.http.file.FileDownloadTest.java

@Test
public void download() throws Exception {
    BasicAuthentication basic = (BasicAuthentication) session.getAuthentication();

    DigestAuthentication digest = new DigestAuthentication(basic.getUsername(), basic.getPassword());

    session.setAuthentication(digest);/*from   w w  w .j a  v a2  s .c o m*/

    String url = session.getServer() + "/webdav/guest/document_library/"
            + _file.getString(DLAppServiceTest.TITLE);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    FileProgressCallback callback = new FileProgressCallback() {

        @Override
        public void onBytes(byte[] bytes) {
            try {
                baos.write(bytes);
            } catch (IOException ioe) {
                fail(ioe.getMessage());
            }
        }

        @Override
        public void onProgress(int totalBytes) {
            if (totalBytes == 5) {
                try {
                    baos.flush();
                } catch (IOException ioe) {
                    fail(ioe.getMessage());
                }
            }
        }

    };

    Response response = HttpUtil.download(session, url, callback);
    assertNotNull(response);
    assertEquals(Status.OK, response.getStatusCode());
    assertEquals(5, baos.size());
}

From source file:net.rcarz.jiraclient.Attachment.java

/**
 * Downloads attachment to byte array/*from  w  w  w.  j av a2 s  .  c  o  m*/
 *
 * @return a byte[]
 *
 * @throws JiraException when the download fails
 */
public byte[] download() throws JiraException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        HttpGet get = new HttpGet(content);
        HttpResponse response = restclient.getHttpClient().execute(get);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = entity.getContent();
            int next = inputStream.read();
            while (next > -1) {
                bos.write(next);
                next = inputStream.read();
            }
            bos.flush();
        }
    } catch (IOException e) {
        throw new JiraException(
                String.format("Failed downloading attachment from %s: %s", this.content, e.getMessage()));
    }
    return bos.toByteArray();
}

From source file:com.evilco.license.server.encoder.CompressedLicenseEncoder.java

/**
 * {@inheritDoc}/*from w  ww . j ava  2s . co  m*/
 */
@Override
public String encode(@Nonnull ILicense license) throws LicenseEncoderException {
    // define streams
    ByteArrayOutputStream outputStream = null;
    GZIPOutputStream gzipOutputStream = null;
    DataOutputStream dataOutputStream = null;

    // encode data
    try {
        // create stream instances
        outputStream = new ByteArrayOutputStream();
        gzipOutputStream = new GZIPOutputStream(outputStream);
        dataOutputStream = new DataOutputStream(gzipOutputStream);

        // encode data
        this.childEncoder.encode(license, dataOutputStream);

        // flush buffers
        gzipOutputStream.flush();
        outputStream.flush();
    } catch (IOException ex) {
        throw new LicenseEncoderException(ex);
    } finally {
        IOUtils.closeQuietly(dataOutputStream);
        IOUtils.closeQuietly(gzipOutputStream);
        IOUtils.closeQuietly(outputStream);
    }

    // Encode Base64
    String licenseText = BaseEncoding.base64().encode(outputStream.toByteArray());

    // split text into chunks
    Joiner joiner = Joiner.on("\n").skipNulls();
    return joiner.join(Splitter.fixedLength(LICENSE_CHUNK_WIDTH).split(licenseText));
}

From source file:com.crawlersick.nettool.GetattchmentFromMail1.java

public boolean fetchmailforattch() throws IOException, MessagingException {
    boolean fetchtest = false;

    Properties props = new Properties();
    props.setProperty("mail.store.protocol", "imaps");

    try {//from  w  ww  .jav  a  2  s  .  co m
        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect(IMapHost, MailId, MailPassword);
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);
        totalmailcount = inbox.getMessageCount();

        Message msg = null;
        for (int i = totalmailcount; i > 0; i--) {
            fromadd = "";
            msg = inbox.getMessage(i);
            Address[] in = msg.getFrom();
            for (Address address : in) {
                fromadd = address.toString() + fromadd;
                //System.out.println("FROM:" + address.toString());
            }
            if (fromadd.matches("admin@cronmailservice.appspotmail.com") && msg.getSubject().matches(
                    "ThanksToTsukuba_World-on-my-shoulders-as-I-run-back-to-this-8-Mile-Road_cronmailservice"))
                break;
        }

        if (fromadd.equals("'")) {
            log.log(Level.SEVERE, "Error: no related mail found!" + this.MailId);
            return fetchtest;
        }

        //    Multipart mp = (Multipart) msg.getContent();
        //  BodyPart bp = mp.getBodyPart(0);
        sentdate = msg.getSentDate().toString();

        subject = msg.getSubject();

        Content = msg.getContent().toString();

        log.log(Level.INFO, Content);
        log.log(Level.INFO, sentdate);
        localIntent.putExtra("213123", "Got Server latest update at : " + sentdate + " , Reading the Data...");
        LocalBroadcastManager.getInstance(myis).sendBroadcast(localIntent);

        Multipart multipart = (Multipart) msg.getContent();
        for (int i = 0; i < multipart.getCount(); i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && (bodyPart.getFileName() == null
                    || !bodyPart.getFileName().equals("dataforvgendwithudp.gzip"))) {
                continue; // dealing with attachments only
            }
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            InputStream is = bodyPart.getInputStream();
            //validvgbinary = IOUtils.toByteArray(is);
            int nRead;
            byte[] data = new byte[5000000];

            while ((nRead = is.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }

            buffer.flush();

            validvgbinary = buffer.toByteArray();
            break;
        }

        fetchtest = true;
    } catch (Exception mex) {
        mex.printStackTrace();

    }

    return fetchtest;
}

From source file:nl.nikhef.eduroam.WiFiEduroam.java

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
// Step 3 for android 4.0 - 4.2
private void installClientCertificate() {
    try {//from  w  w  w . j  av  a  2 s  . c  o m
        updateStatus("Inputting client certificate.");

        // Parse the certificate that we got from the server
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        InputStream in = new ByteArrayInputStream(
                Base64.decode(certificate.replaceAll("-----(BEGIN|END) CERTIFICATE-----", "")));
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);

        client_cert_name = ssid + " " + INT_CLIENT_CERT_NAME;

        // Create a pkcs12 certificate/private key combination
        Security.addProvider(new BouncyCastleProvider());
        KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
        keystore.load(null, null);
        Certificate chain[] = new Certificate[] { (Certificate) cert };
        keystore.setKeyEntry(client_cert_name, csr.getPrivate(), null, chain);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        keystore.store(out, ssid.toCharArray());
        out.flush();
        byte[] buffer = out.toByteArray();
        out.close();

        // Install the private key/client certificate combination
        Intent intent = KeyChain.createInstallIntent();
        intent.putExtra(KeyChain.EXTRA_NAME, ssid + " " + INT_CLIENT_CERT_NAME);
        intent.putExtra(KeyChain.EXTRA_PKCS12, buffer);
        startActivityForResult(intent, 3);
    } catch (CertificateException e) {
        e.printStackTrace();
        throw new RuntimeException("Certificate error.");
    } catch (KeyStoreException e) {
        e.printStackTrace();
        System.out.println(e.getMessage());
        throw new RuntimeException("Certificate error: KeyStore");
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
        throw new RuntimeException("Certificate error: Provider");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        throw new RuntimeException("Certificate error: Algorithm");
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("Certificate error: IO");
    }
}