Java Examples for java.io.OutputStream

The following java examples will help you to understand the usage of java.io.OutputStream. These source code samples are taken from different open source projects.

Example 1
Project: oobd-master  File: DERGenerator.java View source code
private void writeLength(OutputStream out, int length) throws IOException {
    if (length > 127) {
        int size = 1;
        int val = length;
        while ((val >>>= 8) != 0) {
            size++;
        }
        out.write((byte) (size | 0x80));
        for (int i = (size - 1) * 8; i >= 0; i -= 8) {
            out.write((byte) (length >> i));
        }
    } else {
        out.write((byte) length);
    }
}
Example 2
Project: ARKOST-master  File: Utils.java View source code
public static void CopyStream(InputStream is, OutputStream os) {
    final int buffer_size = 1024;
    try {
        byte[] bytes = new byte[buffer_size];
        for (; ; ) {
            int count = is.read(bytes, 0, buffer_size);
            if (count == -1)
                break;
            os.write(bytes, 0, count);
        }
    } catch (Exception ex) {
    }
}
Example 3
Project: korsakow-editor-master  File: SrtEncoder.java View source code
public void encode(OutputStream output) throws IOException {
    Collections.sort(subtitles);
    PrintWriter writer = new PrintWriter(output);
    int counter = 0;
    for (ISubtitle subtitle : subtitles) {
        writer.println(counter);
        writer.print(formatTime(subtitle.getStartTime()));
        writer.print(" --> ");
        writer.print(formatTime(subtitle.getEndTime()));
        writer.println();
        writer.println(subtitle.getText());
        writer.println();
    }
    output.close();
}
Example 4
Project: ocr-tools-master  File: TextMerger.java View source code
@Override
public void merge(List<InputStream> inputs, OutputStream output) {
    try {
        OutputStreamWriter osw = new OutputStreamWriter(output, "UTF-8");
        // Ascii page break dec 12, hex 0c
        char pb = (char) 12;
        // Use the platform dependent separator here
        String seperator = System.getProperty("line.separator");
        int f = 0;
        while (f < inputs.size()) {
            InputStreamReader isr = new InputStreamReader(inputs.get(f), "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                osw.write(line);
                osw.write(seperator);
            }
            //osw.write(pb);
            br.close();
            isr.close();
            f++;
        }
        osw.close();
    } catch (IOException e) {
        throw new IllegalStateException("Error while merging files.", e);
    }
}
Example 5
Project: openjdk-master  File: DemultiplexInput.java View source code
@Override
public void run() {
    try {
        while (true) {
            int nameLen = delegate.read();
            if (nameLen == (-1)) {
                break;
            }
            byte[] name = new byte[nameLen];
            DemultiplexInput.this.delegate.readFully(name);
            int dataLen = delegate.read();
            byte[] data = new byte[dataLen];
            DemultiplexInput.this.delegate.readFully(data);
            String chan = new String(name, "UTF-8");
            OutputStream out = io.get(chan);
            if (out == null) {
                debug("Unexpected channel name: %s", chan);
            } else {
                out.write(data);
            }
        }
    } catch (IOException ex) {
        debug(ex, "Failed reading output");
    } finally {
        for (OutputStream out : closeList) {
            try {
                out.close();
            } catch (IOException ex) {
                debug(ex, "Failed reading output");
            }
        }
    }
}
Example 6
Project: trie4j-master  File: CreateTail.java View source code
public static void main(String[] args) throws Exception {
    TailPatriciaTrie trie = new TailPatriciaTrie();
    for (String s : new WikipediaTitles("data/jawiki-20120220-all-titles-in-ns0.gz")) {
        trie.insert(s);
    }
    ConcatTailArrayBuilder ta = new ConcatTailArrayBuilder(trie.size());
    new TailLOUDSTrie(trie, ta);
    OutputStream os = new FileOutputStream("data/jawiki-20120220-tail");
    try {
    /*			CharSequence seq = ta.build().getTails();
			byte[] bytes = seq.toString().getBytes("UTF16");
			System.out.println(seq.length() + "chars.");
			System.out.println(bytes.length + "bytes.");
			os.write(bytes);
*/
    } finally {
        os.close();
    }
}
Example 7
Project: TestingStuff-master  File: ImageUtils.java View source code
public static void copyStream(InputStream is, OutputStream os) {
    final int buffer_size = 1024;
    try {
        byte[] bytes = new byte[buffer_size];
        for (; ; ) {
            int count = is.read(bytes, 0, buffer_size);
            if (count == -1)
                break;
            os.write(bytes, 0, count);
        }
    } catch (Exception ex) {
    }
}
Example 8
Project: download-manager-master  File: IOHelpers.java View source code
/**
     * Closes an outputStream and the FileDescriptor associated with it after ensuring all data as been written to disk.
     */
static void closeAfterWrite(OutputStream out, FileDescriptor outFd) {
    try {
        if (out != null) {
            out.flush();
        }
        if (outFd != null) {
            outFd.sync();
        }
    } catch (IOException e) {
        LLog.e("Fail sync");
    } finally {
        closeQuietly(out);
    }
}
Example 9
Project: O2OMobile_Android-master  File: Transmitter.java View source code
public static void transmit(Command c, Map h, String b, java.io.OutputStream out) throws IOException {
    StringBuffer message = new StringBuffer(c.toString());
    message.append("\n");
    if (h != null) {
        for (Iterator keys = h.keySet().iterator(); keys.hasNext(); ) {
            String key = (String) keys.next();
            String value = (String) h.get(key);
            message.append(key);
            message.append(":");
            message.append(value);
            message.append("\n");
        }
    }
    message.append("\n");
    if (b != null)
        message.append(b);
    message.append("\000");
    out.write(message.toString().getBytes(Command.ENCODING));
}
Example 10
Project: turmeric-eclipse-master  File: TestPropertiesFileUtil.java View source code
/**
	 * Test method for [email protected] [email protected]etPropertyValueByKey(java.io.InputStream, java.lang.String)}.
	 * @throws IOException 
	 */
@Test
public void testGetPropertyValueByKey() throws IOException {
    File tempFile = null;
    InputStream input = null;
    OutputStream output = null;
    try {
        tempFile = File.createTempFile("nikon", "d80");
        output = new FileOutputStream(tempFile);
        Properties props = new Properties();
        props.put("Nikon", "d80,d90,d700,d3s,d3x");
        props.store(output, "Comments");
        IOUtils.closeQuietly(output);
        input = new FileInputStream(tempFile);
        String value = PropertiesFileUtil.getPropertyValueByKey(input, "Nikon");
        Assert.assertNotNull(value);
        Assert.assertEquals("d80,d90,d700,d3s,d3x", value);
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(input);
        tempFile.delete();
    }
}
Example 11
Project: GeoGig-master  File: WriterRepresentation.java View source code
@Override
public void write(OutputStream outputStream) throws IOException {
    Writer writer = null;
    if (getCharacterSet() != null) {
        writer = new OutputStreamWriter(outputStream, getCharacterSet().getName());
    } else {
        // Use the default HTTP character set
        writer = new OutputStreamWriter(outputStream, CharacterSet.UTF_8.getName());
    }
    write(writer);
    writer.flush();
}
Example 12
Project: molgenis-master  File: LogoController.java View source code
/**
	 * Get a file from the logo subdirectory of the filestore
	 *
	 * @param out
	 * @param name
	 * @param extension
	 * @param response
	 * @throws IOException
	 */
@RequestMapping("/logo/{name}.{extension}")
public void getLogo(OutputStream out, @PathVariable("name") String name, @PathVariable("extension") String extension, HttpServletResponse response) throws IOException {
    File f = fileStore.getFile("/logo/" + name + "." + extension);
    if (!f.exists()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    // Try to get contenttype from file
    String contentType = URLConnection.guessContentTypeFromName(f.getName());
    if (contentType != null) {
        response.setContentType(contentType);
    }
    FileCopyUtils.copy(new FileInputStream(f), out);
}
Example 13
Project: hank-master  File: CueballMerger.java View source code
@Override
public void merge(final CueballFilePath base, final List<CueballFilePath> deltas, final String newBasePath, final int keyHashSize, final int valueSize, ValueTransformer transformer, int hashIndexBits, CueballCompressionCodec compressionCodec) throws IOException {
    CueballStreamBufferMergeSort cueballStreamBufferMergeSort = new CueballStreamBufferMergeSort(base, deltas, keyHashSize, valueSize, hashIndexBits, compressionCodec, transformer);
    // Output stream for the new base to be written. intentionally unbuffered, the writer below will do that on its own.
    OutputStream newCueballBaseOutputStream = new FileOutputStream(newBasePath);
    // Note that we intentionally omit the hasher here, since it will *not* be used
    CueballWriter newCueballBaseWriter = new CueballWriter(newCueballBaseOutputStream, keyHashSize, null, valueSize, compressionCodec, hashIndexBits);
    while (true) {
        KeyHashAndValueAndStreamIndex keyValuePair = cueballStreamBufferMergeSort.nextKeyHashAndValueAndStreamIndex();
        if (keyValuePair == null) {
            break;
        }
        // Write next key hash and value
        newCueballBaseWriter.writeHash(keyValuePair.keyHash, keyValuePair.value);
    }
    // Close all buffers and the base writer
    cueballStreamBufferMergeSort.close();
    newCueballBaseWriter.close();
}
Example 14
Project: android-15-master  File: SSLTest.java View source code
public void testCertificate() throws Exception {
    // test www.fortify.net/sslcheck.html
    Socket ssl = SSLCertificateSocketFactory.getDefault().createSocket("www.fortify.net", 443);
    assertNotNull(ssl);
    OutputStream out = ssl.getOutputStream();
    assertNotNull(out);
    InputStream in = ssl.getInputStream();
    assertNotNull(in);
    String get = "GET /sslcheck.html HTTP/1.1\r\nHost: 68.178.217.222\r\n\r\n";
    // System.out.println("going for write...");
    out.write(get.getBytes());
    byte[] b = new byte[1024];
    // System.out.println("going for read...");
    int ret = in.read(b);
// System.out.println(new String(b));
}
Example 15
Project: geoserver-enterprise-master  File: XMLPPIO.java View source code
/**
     * Encodes the internal object representation of a parameter as a string.
     */
public void encode(Object value, OutputStream os) throws Exception {
    // create the document serializer
    TransformerHandler serializer = ((SAXTransformerFactory) SAXTransformerFactory.newInstance()).newTransformerHandler();
    serializer.setResult(new StreamResult(os));
    // cascade on the other encode method
    encode(value, serializer);
}
Example 16
Project: vr-toolkit-master  File: DownloadFiles.java View source code
@Override
protected String doInBackground(String... sUrl) {
    try {
        URL url = new URL(sUrl[0]);
        URLConnection connection = url.openConnection();
        connection.connect();
        // this will be useful so that you can show a typical 0-100% progress bar
        int fileLength = connection.getContentLength();
        // download the file
        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new FileOutputStream(mPath);
        byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....
            publishProgress((int) (total * 100 / fileLength));
            output.write(data, 0, count);
        }
        output.flush();
        output.close();
        input.close();
    } catch (Exception e) {
    }
    return null;
}
Example 17
Project: fastdfs-client-java-master  File: UploadStream.java View source code
/**
	* send file content callback function, be called only once when the file uploaded
	* @param out output stream for writing file content
	* @return 0 success, return none zero(errno) if fail
	*/
public int send(OutputStream out) throws IOException {
    long remainBytes = fileSize;
    byte[] buff = new byte[256 * 1024];
    int bytes;
    while (remainBytes > 0) {
        try {
            if ((bytes = inputStream.read(buff, 0, remainBytes > buff.length ? buff.length : (int) remainBytes)) < 0) {
                return -1;
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            return -1;
        }
        out.write(buff, 0, bytes);
        remainBytes -= bytes;
    }
    return 0;
}
Example 18
Project: richfaces-master  File: MediaOutputBean.java View source code
public void createContent(OutputStream os, Object data) {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream stream = classLoader.getResourceAsStream("org/richfaces/demo/" + data);
    try {
        ResourceUtils.copyStreamContent(stream, os);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Example 19
Project: extension-aws-master  File: Mp4Generator.java View source code
protected InputStream streamBinary(WebPageRequest inReq, Page inPage, InputStream in, long start, long end, long length, Output inOut) throws IOException {
    if (start == -1) {
        //Only used for flash flv files never used for mp4
        String startbytes = inReq.getRequestParameter("start");
        if (startbytes != null) {
            double timeoffset = Double.parseDouble(startbytes);
            OutputStream stream = inOut.getStream();
            getVideoEditor().split(inPage, timeoffset, stream);
            stream.flush();
            return in;
        }
    }
    return super.streamBinary(inReq, inPage, in, start, end, length, inOut);
}
Example 20
Project: milton2-master  File: MemoryMessageResource.java View source code
public void writeTo(OutputStream out) {
    MimeMessage mm = new MimeMessage((Session) null);
    factory.toMimeMessage(message, mm);
    try {
        mm.writeTo(out);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } catch (MessagingException ex) {
        throw new RuntimeException(ex);
    }
}
Example 21
Project: polly-master  File: BandwidthManager.java View source code
public BandwidthOutputStream newManagedOutput(OutputStream out, AllocationStrategy subStrategy) {
    final BandwidthOutputStream r = new BandwidthOutputStream(out, this.outputStrategy);
    this.setSubStrategy(r, subStrategy);
    this.outputEvents.addListener(StrategyChangedListener.class, r);
    return r;
}
Example 22
Project: fdroidclient-master  File: AssetUtils.java View source code
@Nullable
public static File copyAssetToDir(Context context, String assetName, File directory) {
    File tempFile = null;
    InputStream input = null;
    OutputStream output = null;
    try {
        tempFile = File.createTempFile(assetName, ".testasset", directory);
        Log.i(TAG, "Copying asset file " + assetName + " to directory " + directory);
        input = context.getAssets().open(assetName);
        output = new FileOutputStream(tempFile);
        Utils.copy(input, output);
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        Utils.closeQuietly(output);
        Utils.closeQuietly(input);
    }
    return tempFile;
}
Example 23
Project: Katari-master  File: ScriptExecutionControllerTest.java View source code
@Test
public void testHandleRequest() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("POST", "execute.do");
    MockHttpServletResponse response = new MockHttpServletResponse();
    ScriptingEngine scriptingEngine = new ScriptingEngine() {

        @Override
        public void execute(final String code, final OutputStream output, final OutputStream error) {
            new PrintStream(output, true).print("Groovy rocks your socks!\n");
        }
    };
    ScriptExecutionController scriptExecutionController = new ScriptExecutionController(scriptingEngine);
    String code = "println \"Groovy rocks your socks!\"";
    request.addParameter("script", code);
    scriptExecutionController.handleRequest(request, response);
    String contentType = response.getContentType();
    String content = response.getContentAsString();
    assertThat(contentType, equalTo("application/json"));
    assertThat(content, equalTo("{\"output\":\"Groovy rocks your socks!\\n\"" + ",\"error\":\"\"}"));
}
Example 24
Project: hadoop-20-master  File: TestDFSClientMultipleClose.java View source code
@Test
public void testMultipleFileCloseDFS() throws Exception {
    String testFile = "/testMultipleFileCloseDFS";
    OutputStream stream = dfs.create(testFile, true);
    // This would ensure a close on the stream would fail.
    cluster.getNameNode().stop();
    try {
        stream.close();
    } catch (IOException e) {
        try {
            stream.close();
        } catch (IOException e1) {
            System.out.println("Test passed.");
            return;
        }
        fail("Second close did not throw an exception");
    }
    fail("Close did not throw an exception");
}
Example 25
Project: mini-git-server-master  File: IoUtil.java View source code
public static void copyWithThread(final InputStream src, final OutputStream dst) {
    new Thread("IoUtil-Copy") {

        @Override
        public void run() {
            try {
                final byte[] buf = new byte[256];
                int n;
                while (0 < (n = src.read(buf))) {
                    dst.write(buf, 0, n);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    src.close();
                } catch (IOException e2) {
                }
            }
        }
    }.start();
}
Example 26
Project: pmd-eclipse-plugin-master  File: RuleSetWriterImpl.java View source code
/**
     * Write a ruleset as an XML stream
     * @param writer the output writer
     * @param ruleSet the ruleset to serialize
     */
public void write(OutputStream outputStream, RuleSet ruleSet) throws WriterException {
    try {
        RuleSetWriter ruleSetWriter = new RuleSetWriter(outputStream);
        ruleSetWriter.write(ruleSet);
        outputStream.flush();
    } catch (RuntimeException e) {
        throw new WriterException(e);
    } catch (IOException e) {
        throw new WriterException(e);
    }
}
Example 27
Project: FireflowEngine20-master  File: PostSender.java View source code
@Override
public Response send() throws HttpException {
    try {
        openConnection();
        InputStream ins = request.getInputStream();
        setupRequestHeader();
        if (ins != null && request.getHeader() != null && ins instanceof ByteArrayInputStream && this.request.getHeader().get("Content-Length") == null)
            conn.addRequestProperty("Content-Length", "" + ins.available());
        setupDoInputOutputFlag();
        if (null != ins) {
            OutputStream ops = Streams.buff(conn.getOutputStream());
            Streams.write(ops, ins, 8192);
            Streams.safeClose(ins);
            Streams.safeFlush(ops);
            Streams.safeClose(ops);
        }
        return createResponse(getResponseHeader());
    } catch (Exception e) {
        throw new HttpException(request.getUrl().toString(), e);
    }
}
Example 28
Project: teiid-designer-master  File: XmiStreamWriter.java View source code
/**
     * @see StreamWriter#write(java.io.OutputStream, java.util.Map, java.util.Collection)
     *      Warning: The objects collection input parameter will be added to a new Resource within the execution of this method,
     *      and thus will lose its relationship to any other resource that it is contained in.
     */
@Override
public void write(OutputStream outputstream, Map options, Collection objects) throws IOException {
    if (outputstream == null) {
        CoreArgCheck.isNotNull(outputstream, //$NON-NLS-1$
        ModelerCore.Util.getString("XmiStreamWriter.The_OutputStream_reference_may_not_be_null_1"));
    }
    if (options == null) {
        //$NON-NLS-1$
        CoreArgCheck.isNotNull(options, ModelerCore.Util.getString("XmiStreamWriter.The_Map_reference_may_not_be_null_2"));
    }
    if (objects == null) {
        //$NON-NLS-1$
        CoreArgCheck.isNotNull(objects, ModelerCore.Util.getString("XmiStreamWriter.The_Collection_reference_may_not_be_null_3"));
    }
    Resource temp = new XMIResourceImpl();
    temp.getContents().addAll(objects);
    temp.save(outputstream, options);
}
Example 29
Project: Technomap-master  File: DelimitedTextTableWriter.java View source code
// ------------------------------------------------------------------------
/**
     * @see prefuse.data.io.TableWriter#writeTable(prefuse.data.Table, java.io.OutputStream)
     */
public void writeTable(Table table, OutputStream os) throws DataIOException {
    try {
        // get print stream
        PrintStream out = new PrintStream(new BufferedOutputStream(os));
        // write out header row
        if (m_printHeader) {
            for (int i = 0; i < table.getColumnCount(); ++i) {
                if (i > 0)
                    out.print(m_delim);
                out.print(table.getColumnName(i));
            }
            out.println();
        }
        // write out data
        for (IntIterator rows = table.rows(); rows.hasNext(); ) {
            int row = rows.nextInt();
            for (int i = 0; i < table.getColumnCount(); ++i) {
                if (i > 0)
                    out.print(m_delim);
                out.print(table.getString(row, table.getColumnName(i)));
            }
            out.println();
        }
        // finish up
        out.flush();
    } catch (Exception e) {
        throw new DataIOException(e);
    }
}
Example 30
Project: SideScrollerGDW2012-Max-master  File: ImageIOWriter.java View source code
/**
	 * @see org.newdawn.slick.imageout.ImageWriter#saveImage(org.newdawn.slick.Image, 
	 * java.lang.String, java.io.OutputStream, boolean)
	 */
public void saveImage(Image image, String format, OutputStream output, boolean hasAlpha) throws IOException {
    // conver the image into a byte buffer by reading each pixel in turn
    int len = 4 * image.getWidth() * image.getHeight();
    if (!hasAlpha) {
        len = 3 * image.getWidth() * image.getHeight();
    }
    ByteBuffer out = ByteBuffer.allocate(len);
    Color c;
    for (int y = 0; y < image.getHeight(); y++) {
        for (int x = 0; x < image.getWidth(); x++) {
            c = image.getColor(x, y);
            out.put((byte) (c.r * 255.0f));
            out.put((byte) (c.g * 255.0f));
            out.put((byte) (c.b * 255.0f));
            if (hasAlpha) {
                out.put((byte) (c.a * 255.0f));
            }
        }
    }
    // create a raster of the correct format and fill it with our buffer
    DataBufferByte dataBuffer = new DataBufferByte(out.array(), len);
    PixelInterleavedSampleModel sampleModel;
    ColorModel cm;
    if (hasAlpha) {
        int[] offsets = { 0, 1, 2, 3 };
        sampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, image.getWidth(), image.getHeight(), 4, 4 * image.getWidth(), offsets);
        cm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[] { 8, 8, 8, 8 }, true, false, ComponentColorModel.TRANSLUCENT, DataBuffer.TYPE_BYTE);
    } else {
        int[] offsets = { 0, 1, 2 };
        sampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, image.getWidth(), image.getHeight(), 3, 3 * image.getWidth(), offsets);
        cm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[] { 8, 8, 8, 0 }, false, false, ComponentColorModel.OPAQUE, DataBuffer.TYPE_BYTE);
    }
    WritableRaster raster = Raster.createWritableRaster(sampleModel, dataBuffer, new Point(0, 0));
    // finally create the buffered image based on the data from the texture
    // and spit it through to ImageIO
    BufferedImage img = new BufferedImage(cm, raster, false, null);
    ImageIO.write(img, format, output);
}
Example 31
Project: cdt-tests-runner-master  File: ErrorThread.java View source code
/*
	 * Sit on the error stream output, and append to the GDB console
	 */
public void run() {
    BufferedReader reader = new BufferedReader(new InputStreamReader(session.getChannelErrorStream()));
    try {
        String line;
        while ((line = reader.readLine()) != null) {
            OutputStream console = session.getLogPipe();
            if (console != null) {
                console.write(//$NON-NLS-1$
                (line + "\n").getBytes());
                console.flush();
            }
        }
    } catch (IOException e) {
        try {
            reader.close();
        } catch (IOException e1) {
        }
    }
}
Example 32
Project: castor-master  File: BaseXercesJDK5Serializer.java View source code
/**
     * @see org.exolab.castor.xml.Serializer#setOutputByteStream(java.io.OutputStream)
     *      [email protected]}
     */
public void setOutputByteStream(final OutputStream output) {
    Method method;
    try {
        method = _serializer.getClass().getMethod("setOutputByteStream", new Class[] { OutputStream.class });
        method.invoke(_serializer, new Object[] { output });
    } catch (Exception e) {
        String msg = "Problem invoking XMLSerializer.setOutputByteStream()";
        LOG.error(msg, e);
        throw new RuntimeException(msg + e.getMessage());
    }
}
Example 33
Project: spring-framework-2.5.x-master  File: BurlapExporter.java View source code
/**
	 * Perform an invocation on the exported object.
	 * @param inputStream the request stream
	 * @param outputStream the response stream
	 * @throws Throwable if invocation failed
	 */
public void invoke(InputStream inputStream, OutputStream outputStream) throws Throwable {
    Assert.notNull(this.skeleton, "Burlap exporter has not been initialized");
    ClassLoader originalClassLoader = overrideThreadContextClassLoader();
    try {
        this.skeleton.invoke(new BurlapInput(inputStream), new BurlapOutput(outputStream));
    } finally {
        try {
            inputStream.close();
        } catch (IOException ex) {
        }
        try {
            outputStream.close();
        } catch (IOException ex) {
        }
        resetThreadContextClassLoader(originalClassLoader);
    }
}
Example 34
Project: CodingSpectator-master  File: TextStreamMerger.java View source code
/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.compare.internal.merge.IAutoMerger#automerge(java.io.OutputStream,
	 *      org.eclipse.core.resources.IEncodedStorage,
	 *      org.eclipse.core.resources.IEncodedStorage,
	 *      org.eclipse.core.resources.IEncodedStorage,
	 *      org.eclipse.core.runtime.IProgressMonitor)
	 */
public IStatus merge(OutputStream output, String outputEncoding, InputStream ancestor, String ancestorEncoding, InputStream target, String targetEncoding, InputStream other, String otherEncoding, IProgressMonitor monitor) {
    LineComparator a, t, o;
    try {
        a = new LineComparator(ancestor, ancestorEncoding);
        t = new LineComparator(target, targetEncoding);
        o = new LineComparator(other, otherEncoding);
    } catch (UnsupportedEncodingException e) {
        return new Status(IStatus.ERROR, CompareUI.PLUGIN_ID, 1, MergeMessages.TextAutoMerge_inputEncodingError, e);
    } catch (IOException e) {
        return new Status(IStatus.ERROR, CompareUI.PLUGIN_ID, 1, e.getMessage(), e);
    }
    try {
        //$NON-NLS-1$
        String lineSeparator = System.getProperty("line.separator");
        if (lineSeparator == null)
            //$NON-NLS-1$
            lineSeparator = //$NON-NLS-1$
            "\n";
        RangeDifference[] diffs = RangeDifferencer.findRanges(monitor, a, t, o);
        for (int i = 0; i < diffs.length; i++) {
            RangeDifference rd = diffs[i];
            switch(rd.kind()) {
                // pseudo conflict
                case RangeDifference.ANCESTOR:
                case RangeDifference.NOCHANGE:
                case RangeDifference.RIGHT:
                    for (int j = rd.rightStart(); j < rd.rightEnd(); j++) {
                        String s = o.getLine(j);
                        output.write(s.getBytes(outputEncoding));
                        output.write(lineSeparator.getBytes(outputEncoding));
                    }
                    break;
                case RangeDifference.LEFT:
                    for (int j = rd.leftStart(); j < rd.leftEnd(); j++) {
                        String s = t.getLine(j);
                        output.write(s.getBytes(outputEncoding));
                        output.write(lineSeparator.getBytes(outputEncoding));
                    }
                    break;
                case RangeDifference.CONFLICT:
                    return new Status(IStatus.ERROR, CompareUI.PLUGIN_ID, CONFLICT, MergeMessages.TextAutoMerge_conflict, null);
                default:
                    break;
            }
        }
    } catch (UnsupportedEncodingException e) {
        return new Status(IStatus.ERROR, CompareUI.PLUGIN_ID, 1, MergeMessages.TextAutoMerge_outputEncodingError, e);
    } catch (IOException e) {
        return new Status(IStatus.ERROR, CompareUI.PLUGIN_ID, 1, MergeMessages.TextAutoMerge_outputIOError, e);
    }
    return Status.OK_STATUS;
}
Example 35
Project: platform-api-master  File: ContentStreamWriter.java View source code
/**
     * @see javax.ws.rs.ext.MessageBodyWriter#writeTo(java.lang.Object, java.lang.Class, java.lang.reflect.Type,
     *      java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType, javax.ws.rs.core.MultivaluedMap,
     *      java.io.OutputStream)
     */
@Override
public void writeTo(ContentStream t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    String mimeType = t.getMimeType();
    if (mimeType != null) {
        httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, mimeType);
    }
    httpHeaders.putSingle("Content-Disposition", "attachment; filename=\"" + t.getFileName() + '"');
    Date lastModificationDate = t.getLastModificationDate();
    if (lastModificationDate != null) {
        httpHeaders.putSingle(HttpHeaders.LAST_MODIFIED, t.getLastModificationDate());
    }
    httpHeaders.putSingle(HttpHeaders.CACHE_CONTROL, "public, no-cache, no-store, no-transform");
    try (InputStream content = t.getStream()) {
        byte[] buf = new byte[8192];
        int rd;
        while ((rd = content.read(buf)) != -1) {
            entityStream.write(buf, 0, rd);
        }
        entityStream.flush();
    }
}
Example 36
Project: yarn-comment-master  File: TestDFSClientExcludedNodes.java View source code
@Test
public void testExcludedNodes() throws IOException {
    Configuration conf = new HdfsConfiguration();
    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(3).build();
    FileSystem fs = cluster.getFileSystem();
    Path filePath = new Path("/testExcludedNodes");
    // kill a datanode
    cluster.stopDataNode(AppendTestUtil.nextInt(3));
    OutputStream out = fs.create(filePath, true, 4096);
    out.write(20);
    try {
        out.close();
    } catch (Exception e) {
        fail("DataNode failure should not result in a block abort: \n" + e.getMessage());
    }
}
Example 37
Project: flink-master  File: TestingFailingBlobServer.java View source code
@Override
public void run() {
    // we do properly the first operation (PUT)
    try {
        new BlobServerConnection(getServerSocket().accept(), this).start();
    } catch (Throwable t) {
        t.printStackTrace();
    }
    // do some failing operations
    for (int num = 0; num < numFailures && !isShutdown(); num++) {
        Socket socket = null;
        try {
            socket = getServerSocket().accept();
            InputStream is = socket.getInputStream();
            OutputStream os = socket.getOutputStream();
            // just abort everything
            is.close();
            os.close();
            socket.close();
        } catch (IOException e) {
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (Throwable t) {
                }
            }
        }
    }
    // regular runs
    super.run();
}
Example 38
Project: dataverse-master  File: XgetRecord.java View source code
public void writeToStream(OutputStream outputStream) throws IOException {
    if (this.getRecord() == null) {
        throw new IOException("XgetRecord: null Record");
    }
    Xrecord xrecord = (Xrecord) this.getRecord();
    outputStream.write(RECORD_START_ELEMENT.getBytes());
    outputStream.flush();
    xrecord.writeToStream(outputStream);
    outputStream.write(RECORD_CLOSE_ELEMENT.getBytes());
    outputStream.flush();
}
Example 39
Project: WearPomodoro-master  File: PomodoroUtils.java View source code
private static long copy(final InputStream input, final OutputStream output) throws IOException {
    final byte[] buffer = new byte[1024 * 4];
    long count = 0;
    int n;
    int EOF = -1;
    while (EOF != (n = input.read(buffer))) {
        output.write(buffer, 0, n);
        count += n;
    }
    return count;
}
Example 40
Project: sslcertx-master  File: NamedPipeSocket.java View source code
public void connect(SocketAddress endpoint, int timeout) throws IOException {
    String filename;
    if (host == null || host.equals("localhost")) {
        filename = "\\\\.\\pipe\\" + name;
    } else {
        filename = "\\\\" + host + "\\pipe\\" + name;
    }
    file = new RandomAccessFile(filename, "rw");
    is = new InputStream() {

        @Override
        public int read(byte[] b, int off, int len) throws IOException {
            return file.read(b, off, len);
        }

        @Override
        public int read() throws IOException {
            return file.read();
        }

        @Override
        public int read(byte[] b) throws IOException {
            return file.read(b);
        }
    };
    os = new OutputStream() {

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            file.write(b, off, len);
        }

        @Override
        public void write(int b) throws IOException {
            file.write(b);
        }

        @Override
        public void write(byte[] b) throws IOException {
            file.write(b);
        }
    };
}
Example 41
Project: wso2-synapse-master  File: XMLConfigurationSerializer.java View source code
/**
     * Order of entries is irrelevant, however its nice to have some order.
     * @param synCfg
     * @param outputStream
     * @throws XMLStreamException
     */
public static void serializeConfiguration(SynapseConfiguration synCfg, OutputStream outputStream) throws XMLStreamException {
    if (log.isDebugEnabled()) {
        log.debug("Serializing the XML Configuration to the output stream");
    }
    OMElement definitions = ConfigurationFactoryAndSerializerFinder.serializeConfiguration(synCfg);
    definitions.serialize(outputStream);
}
Example 42
Project: android_platform_libcore-master  File: CipherOutputStreamTest.java View source code
/**
     * javax.crypto.CipherOutputStream#close()
     */
public void test_close() throws Exception {
    // regression test for HARMONY-1139
    try {
        new CipherOutputStream((OutputStream) null, Cipher.getInstance("DES/CBC/PKCS5Padding")).close();
        fail("IllegalStateException expected");
    } catch (IllegalStateException e) {
    }
    CipherOutputStream ch = new CipherOutputStream((OutputStream) null) {
    };
    try {
        new CipherOutputStream(ch, Cipher.getInstance("DES/CBC/PKCS5Padding")).close();
        fail("IllegalStateException expected");
    } catch (IllegalStateException e) {
    }
}
Example 43
Project: tinkerpop-master  File: HadoopPoolShimService.java View source code
public void writeClassAndObject(final Object o, final OutputStream sink) {
    Kryo k = null;
    try {
        k = HadoopPools.getGryoPool().takeKryo();
        final Output output = new Output(sink);
        k.writeClassAndObject(output, o);
        output.flush();
    } finally {
        if (null != k) {
            HadoopPools.getGryoPool().offerKryo(k);
        }
    }
}
Example 44
Project: RoboBuggy-master  File: main.java View source code
public static void main(String args[]) {
    try {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM5");
        CommPort commPort = portIdentifier.open("owner-name", 2000);
        SerialPort serialPort = null;
        int rate = 9600;
        int databits = SerialPort.DATABITS_8;
        int stopbits = SerialPort.STOPBITS_1;
        int parity = SerialPort.PARITY_NONE;
        if (commPort instanceof SerialPort) {
            serialPort = (SerialPort) commPort;
            serialPort.setSerialPortParams(rate, databits, stopbits, parity);
        }
        InputStream in = serialPort.getInputStream();
        OutputStream out = serialPort.getOutputStream();
        byte[] arr = new byte[10];
        while (true) {
            if (in.available() > 10) {
                int n = in.read(arr);
                String temp = new String(arr);
                System.out.println(temp);
                //System.out.println((char)arr[0]);
                System.out.println(Arrays.toString(arr));
            }
        }
    //
    // Use port identifier for acquiring the port
    } catch (Exception e) {
        System.out.print("failed");
    }
}
Example 45
Project: ezdb-master  File: SerializingSerde.java View source code
private static void serialize(Serializable obj, OutputStream outputStream) {
    if (outputStream == null) {
        throw new IllegalArgumentException("The OutputStream must not be null");
    }
    ObjectOutputStream out = null;
    try {
        // stream closed in the finally
        out = new ObjectOutputStream(outputStream);
        out.writeObject(obj);
    } catch (IOException ex) {
        throw new DbException(ex);
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException ex) {
        }
    }
}
Example 46
Project: alien4cloud-master  File: ImageServlet.java View source code
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    final String imageId = req.getParameter("id");
    final String quality = req.getParameter("quality");
    final ImageQuality imageQuality;
    if (quality == null) {
        imageQuality = ImageQuality.QUALITY_BEST;
    } else {
        imageQuality = ImageQuality.valueOf(quality);
    }
    final ImageData imageData = this.imageDAO.readImage(imageId, imageQuality);
    if (imageData != null) {
        // Set content type
        resp.setContentType(imageData.getMime());
        // Set content size
        resp.setContentLength(imageData.getData().length);
        // Open the file and output streams
        final OutputStream out = resp.getOutputStream();
        try {
            out.write(imageData.getData());
        } finally {
            out.close();
        }
    } else {
        resp.setStatus(HttpStatus.NOT_FOUND.value());
    }
}
Example 47
Project: jena-master  File: XMLOutput.java View source code
@Override
public void format(OutputStream out, ResultSet resultSet) {
    XMLOutputResultSet xOut = new XMLOutputResultSet(out);
    xOut.setStylesheetURL(stylesheetURL);
    xOut.setXmlInst(includeXMLinst);
    ResultSetApply a = new ResultSetApply(resultSet, xOut);
    a.apply();
}
Example 48
Project: org.eclipse.ecr-master  File: ResourceServlet.java View source code
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String pathInfo = req.getPathInfo();
    if (pathInfo == null || pathInfo.equals("/") || pathInfo.length() == 0) {
        pathInfo = index;
    } else if (pathInfo.endsWith("/")) {
        pathInfo += index;
    }
    InputStream in = getServletContext().getResourceAsStream(pathInfo);
    if (in != null) {
        String ctype = getServletContext().getMimeType(pathInfo);
        if (ctype != null) {
            resp.addHeader("Content-Type", ctype);
        }
        try {
            OutputStream out = resp.getOutputStream();
            byte[] bytes = new byte[1024 * 64];
            int r = in.read(bytes);
            while (r > -1) {
                if (r > 0) {
                    out.write(bytes, 0, r);
                }
                r = in.read(bytes);
            }
            out.flush();
        } finally {
            in.close();
        }
    }
}
Example 49
Project: geotools-old-master  File: ImageIOExtTest.java View source code
@Test
public void testThreshold() throws Exception {
    OutputStream os = new ByteArrayOutputStream();
    ImageIOExt.setFilesystemThreshold(100 * 100 * 3l);
    RenderedImage imageSmall = getTestRenderedImage(50, 50, 3);
    final ImageOutputStream iosSmall = ImageIOExt.createImageOutputStream(imageSmall, os);
    try {
        assertEquals(MemoryCacheImageOutputStream.class, iosSmall.getClass());
    } finally {
        iosSmall.close();
    }
    RenderedImage imageLarge = getTestRenderedImage(101, 101, 3);
    final ImageOutputStream iosLarge = ImageIOExt.createImageOutputStream(imageLarge, os);
    try {
        assertEquals(FileCacheImageOutputStream.class, iosLarge.getClass());
    } finally {
        iosLarge.close();
    }
}
Example 50
Project: Fontster-master  File: FileUtils.java View source code
public static File getAssetsFile(String fileName, Context context) {
    if (context == null)
        return null;
    File file = new File(context.getExternalCacheDir() + File.separator + fileName);
    if (!file.exists()) {
        try {
            InputStream in = context.getAssets().open(fileName);
            OutputStream out = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int read;
            while ((read = in.read(buffer)) != -1) out.write(buffer, 0, read);
            in.close();
            out.close();
        } catch (IOException e) {
            file = null;
        }
    }
    return file;
}
Example 51
Project: dcache-master  File: ContextPictureEngine.java View source code
@Override
public void queryUrl(HttpRequest request) throws HttpException {
    String[] tokens = request.getRequestTokens();
    int offset = request.getRequestTokenOffset();
    _log.info("Offset : " + offset);
    for (int i = 0; i < tokens.length; i++) {
        _log.info(i + " -> " + tokens[i]);
    }
    if (tokens.length < 2) {
        throw new HttpException(404, "Illegal Request");
    }
    String contextName = tokens[1];
    Object obj = context.get(contextName);
    if (!(obj instanceof byte[])) {
        throw new HttpException(404, "Not a picture");
    }
    byte[] picture = (byte[]) obj;
    request.setContentType("image/png");
    request.printHttpHeader(picture.length);
    OutputStream stream = request.getOutputStream();
    try {
        stream.write(picture, 0, picture.length);
        stream.flush();
    } catch (IOException ee) {
        throw new HttpException(203, ee.getMessage());
    }
}