Example usage for java.io ByteArrayOutputStream reset

List of usage examples for java.io ByteArrayOutputStream reset

Introduction

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

Prototype

public synchronized void reset() 

Source Link

Document

Resets the count field of this ByteArrayOutputStream to zero, so that all currently accumulated output in the output stream is discarded.

Usage

From source file:org.light.portal.util.StringUtils.java

public static String encode(String s) {
    int maxBytesPerChar = 10;
    StringBuffer out = new StringBuffer(s.length());
    java.io.ByteArrayOutputStream buf = new java.io.ByteArrayOutputStream(maxBytesPerChar);
    java.io.OutputStreamWriter writer = new java.io.OutputStreamWriter(buf);

    for (int i = 0; i < s.length(); i++) {
        int c = (int) s.charAt(i);
        if (dontNeedEncoding.get(c)) {
            out.append((char) c);
        } else {//from   w  ww  . java  2s. c  o  m
            // convert to external encoding before hex conversion
            try {
                writer.write(c);
                writer.flush();
            } catch (java.io.IOException e) {
                buf.reset();
                continue;
            }
            byte[] ba = buf.toByteArray();
            for (int j = 0; j < ba.length; j++) {
                out.append('x');
                char ch = Character.forDigit((ba[j] >> 4) & 0xF, 16);
                // converting to use uppercase letter as part of
                // the hex value if ch is a letter.
                if (Character.isLetter(ch)) {
                    ch -= caseDiff;
                }
                out.append(ch);
                ch = Character.forDigit(ba[j] & 0xF, 16);
                if (Character.isLetter(ch)) {
                    ch -= caseDiff;
                }
                out.append(ch);
            }
            buf.reset();
        }
    }

    return out.toString();
}

From source file:com.applozic.mobicommons.file.FileUtils.java

/**
 * This method will compressed Image to a pre-configured files.
 *
 * @param filePath/*from   ww w.java  2  s  .c  om*/
 * @param newFileName
 * @param maxFileSize
 * @return
 */
public static File compressImageFiles(String filePath, String newFileName, int maxFileSize) {

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);

    int actualHeight = options.outHeight;
    int actualWidth = options.outWidth;
    float imgRatio = actualWidth / actualHeight;
    int maxHeight = (2 * actualHeight) / 3;
    int maxWidth = (2 * actualWidth) / 3;

    float maxRatio = maxWidth / maxHeight;
    if (actualHeight > maxHeight || actualWidth > maxWidth) {
        if (imgRatio < maxRatio) {
            imgRatio = maxHeight / actualHeight;
            actualWidth = (int) (imgRatio * actualWidth);
            actualHeight = (int) maxHeight;
        } else if (imgRatio > maxRatio) {
            imgRatio = maxHeight / actualWidth;
            actualHeight = (int) (imgRatio * actualHeight);
            actualWidth = (int) maxWidth;
        } else {
            actualHeight = (int) maxHeight;
            actualWidth = (int) maxWidth;
        }
    }
    options.inSampleSize = ImageUtils.calculateInSampleSize(options, actualWidth, actualHeight);
    options.inJustDecodeBounds = false;

    options.inTempStorage = new byte[16 * 1024];

    try {
        bitmap = BitmapFactory.decodeFile(filePath, options);
    } catch (OutOfMemoryError exception) {
        exception.printStackTrace();

    }

    int streamLength = maxFileSize;
    int compressQuality = 100;// Maximum 20 loops to retry to maintain quality.
    ByteArrayOutputStream bmpStream = new ByteArrayOutputStream();
    while (streamLength >= maxFileSize && compressQuality > 50) {

        try {
            bmpStream.flush();
            bmpStream.reset();
        } catch (IOException e) {
            e.printStackTrace();
        }
        bitmap.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpStream);
        byte[] bmpPicByteArray = bmpStream.toByteArray();
        streamLength = bmpPicByteArray.length;
        if (BuildConfig.DEBUG) {
            Log.i("test upload", "Quality: " + compressQuality);
            Log.i("test upload", "Size: " + streamLength);
        }
        compressQuality -= 3;

    }

    FileOutputStream fo;
    try {
        fo = new FileOutputStream(newFileName);
        fo.write(bmpStream.toByteArray());
        fo.flush();
        fo.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new File(newFileName);
}

From source file:de.jwic.ecolib.controls.chart.ChartControl.java

public void renderImage() throws IOException {
    // create image to draw into
    BufferedImage bi = new BufferedImage(width < 10 ? 10 : width, height < 10 ? 10 : height,
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = bi.createGraphics();

    if (chart != null) {
        chart.setBackgroundPaint(Color.WHITE);
        chart.draw(g2d, new Rectangle2D.Double(0, 0, width < 10 ? 10 : width, height < 10 ? 10 : height));
    } else {/*  w  w  w . j  a  v a 2s. c om*/
        g2d.setColor(Color.BLACK);
        g2d.drawString("No chart has been assigned.", 1, 20);
    }
    // finish drawing
    g2d.dispose();

    // write image data into output stream
    ByteArrayOutputStream out = getImageOutputStream();
    out.reset();
    // create a PNG image
    ImageWriter imageWriter = new PNGImageWriter(null);
    ImageWriteParam param = imageWriter.getDefaultWriteParam();
    imageWriter.setOutput(new MemoryCacheImageOutputStream(out));
    imageWriter.write(null, new IIOImage(bi, null, null), param);
    imageWriter.dispose();

    setMimeType(MIME_TYPE_PNG);
}

From source file:com.cloudbees.jenkins.support.api.FileContentTest.java

@Test
public void truncation() throws Exception {
    File f = tmp.newFile();/*from   ww  w.j a v  a2 s  .  c  o  m*/
    FileUtils.writeStringToFile(f, "hello world\n");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    new FileContent("-", f).writeTo(baos);
    assertEquals("hello world\n", baos.toString());
    baos.reset();
    new FileContent("-", f, 10).writeTo(baos);
    assertEquals("hello worl", baos.toString());
    baos.reset();
    new FileContent("-", f, 20).writeTo(baos);
    assertEquals("hello world\n", baos.toString());
}

From source file:com.nary.Debug.java

public static Object loadClass(InputStream _inStream, boolean _uncompress) {
    ObjectInputStream ois;/*from w w w.j ava 2s.c o m*/
    try {
        if (_uncompress) {
            // we need to get the input as a byte [] so we can decompress (inflate) it.  
            Inflater inflater = new Inflater();
            ByteArrayOutputStream bos;
            int bytesAvail = _inStream.available();
            if (bytesAvail > 0) {
                bos = new ByteArrayOutputStream(bytesAvail);
            } else {
                bos = new ByteArrayOutputStream();
            }

            byte[] buffer = new byte[1024];
            int read = _inStream.read(buffer);
            while (read > 0) {
                bos.write(buffer, 0, read);
                read = _inStream.read(buffer);
            }
            bos.flush();
            inflater.setInput(bos.toByteArray());

            bos.reset();
            buffer = new byte[1024];
            int inflated = inflater.inflate(buffer);
            while (inflated > 0) {
                bos.write(buffer, 0, inflated);
                inflated = inflater.inflate(buffer);
            }

            bos.flush();
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());

            ois = new ObjectInputStream(bis);

        } else {
            ois = new ObjectInputStream(_inStream);
        }

        return ois.readObject();
    } catch (Exception E) {
        return null;
    } finally {
        try {
            _inStream.close();
        } catch (Exception ioe) {
        }
    }
}

From source file:com.github.ukase.service.PdfRenderer.java

private void addSampleWatermark(ByteArrayOutputStream baos, char pdfVersion)
        throws IOException, DocumentException {
    PdfReader reader = new PdfReader(baos.toByteArray());
    baos.reset();
    Phrase phrase = new Phrase(waterMark.getText(), font);
    PdfStamper stamper = new PdfStamper(reader, baos, pdfVersion);
    for (int i = 1; i <= reader.getNumberOfPages(); i++) {
        PdfContentByte canvas = stamper.getUnderContent(i);
        ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase, waterMark.getX(), waterMark.getY(),
                waterMark.getDegree());//from   w w w . j a  va  2  s.  c o  m
    }
    stamper.close();
    reader.close();
}

From source file:com.joyent.manta.http.entity.DigestedEntityTest.java

public void testWriteToProducesReliableDigest() throws Exception {
    String content = STRING_GENERATOR.generate(100);
    DigestedEntity entity = new DigestedEntity(new ExposedStringEntity(content, StandardCharsets.UTF_8),
            new FastMD5Digest());

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    entity.writeTo(out);//from  w  w  w . ja  va 2  s .com
    byte[] initialDigest = entity.getDigest();

    // connection reset, httpclient performs a retry reusing the same entity
    out.reset();
    entity.writeTo(out);
    byte[] retryDigest = entity.getDigest();

    Assert.assertTrue(Arrays.equals(initialDigest, retryDigest),
            "Reuse of DigestedEntity produced differing digest for first retry");

    // connection reset again
    out.reset();
    entity.writeTo(out);
    byte[] extraRetryDigest = entity.getDigest();

    Assert.assertTrue(Arrays.equals(initialDigest, extraRetryDigest),
            "Reuse of DigestedEntity produced differing digest for second retry");
}

From source file:com.gameminers.mav.firstrun.TeachSphinxThread.java

@Override
public void run() {
    try {/*from   w  w w .j  a  v a  2 s . co  m*/
        File training = new File(Mav.configDir, "training-data");
        training.mkdirs();
        while (Mav.silentFrames < 30) {
            sleep(100);
        }
        Mav.listening = true;
        InputStream prompts = ClassLoader.getSystemResourceAsStream("resources/sphinx/train/arcticAll.prompts");
        List<String> arctic = IOUtils.readLines(prompts);
        IOUtils.closeQuietly(prompts);
        Mav.audioManager.playClip("listen1");
        byte[] buf = new byte[2048];
        int start = 0;
        int end = 21;
        AudioInputStream in = Mav.audioManager.getSource().getAudioInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while (true) {
            for (int i = start; i < end; i++) {
                baos.reset();
                String prompt = arctic.get(i);
                RenderState.setText("\u00A7LRead this aloud:\n" + Fonts.wrapStringToFit(
                        prompt.substring(prompt.indexOf(':') + 1), Fonts.base[1], Display.getWidth()));
                File file = new File(training, prompt.substring(0, prompt.indexOf(':')) + ".wav");
                file.createNewFile();
                int read = 0;
                while (Mav.silentListenFrames > 0) {
                    read = Mav.audioManager.getSource().getAudioInputStream().read(buf);
                }
                baos.write(buf, 0, read);
                while (Mav.silentListenFrames < 60) {
                    in.read(buf);
                    if (read == -1) {
                        RenderState.setText(
                                "\u00A7LAn error occurred\nUnexpected end of stream\nPlease restart Mav");
                        RenderState.targetHue = 0;
                        return;
                    }
                    baos.write(buf, 0, read);
                }
                AudioSystem.write(new AudioInputStream(new ByteArrayInputStream(baos.toByteArray()),
                        in.getFormat(), baos.size() / 2), AudioFileFormat.Type.WAVE, file);
                Mav.audioManager.playClip("notif2");
            }
            Mav.ttsInterface.say(Mav.phoneticUserName
                    + ", that should be enough for now. Do you want to keep training anyway?");
            RenderState.setText("\u00A7LOkay, " + Mav.userName
                    + "\nI think that should be\nenough. Do you want to\nkeep training anyway?\n\u00A7s(Say 'Yes' or 'No' out loud)");
            break;
            //start = end+1;
            //end += 20;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.officefloor.tutorial.exceptionhttpserver.ExceptionHttpServerTest.java

public void testExceptionHandling() throws Exception {

    // Override stderr
    ByteArrayOutputStream error = new ByteArrayOutputStream();
    System.setErr(new PrintStream(error, true));

    // Start server
    WoofOfficeFloorSource.start();/*from  w  w w. j ava2 s  .c  o  m*/

    // Clear setup log
    error.reset();

    // Submit to trigger the exception
    this.client.execute(new HttpGet("http://localhost:7878/template-submit.woof"));

    // Ensure handling by logging the failure
    String log = new String(error.toByteArray()).trim();
    assertEquals("Should log error", "Test", log);
}

From source file:org.apache.cocoon.util.NetUtils.java

/**
 * Encode a path as required by the URL specification (<a href="http://www.ietf.org/rfc/rfc1738.txt">
 * RFC 1738</a>). This differs from <code>java.net.URLEncoder.encode()</code> which encodes according
 * to the <code>x-www-form-urlencoded</code> MIME format.
 *
 * @param path the path to encode//w w w  .ja  va 2s . com
 * @return the encoded path
 */
public static String encodePath(String path) {
    // stolen from org.apache.catalina.servlets.DefaultServlet ;)

    /**
     * Note: This code portion is very similar to URLEncoder.encode.
     * Unfortunately, there is no way to specify to the URLEncoder which
     * characters should be encoded. Here, ' ' should be encoded as "%20"
     * and '/' shouldn't be encoded.
     */

    int maxBytesPerChar = 10;
    StringBuffer rewrittenPath = new StringBuffer(path.length());
    ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);
    OutputStreamWriter writer = null;
    try {
        writer = new OutputStreamWriter(buf, "UTF8");
    } catch (Exception e) {
        e.printStackTrace();
        writer = new OutputStreamWriter(buf);
    }

    for (int i = 0; i < path.length(); i++) {
        int c = path.charAt(i);
        if (safeCharacters.get(c)) {
            rewrittenPath.append((char) c);
        } else {
            // convert to external encoding before hex conversion
            try {
                writer.write(c);
                writer.flush();
            } catch (IOException e) {
                buf.reset();
                continue;
            }
            byte[] ba = buf.toByteArray();
            for (int j = 0; j < ba.length; j++) {
                // Converting each byte in the buffer
                byte toEncode = ba[j];
                rewrittenPath.append('%');
                int low = (toEncode & 0x0f);
                int high = ((toEncode & 0xf0) >> 4);
                rewrittenPath.append(hexadecimal[high]);
                rewrittenPath.append(hexadecimal[low]);
            }
            buf.reset();
        }
    }
    return rewrittenPath.toString();
}