javatips.net counter

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: flink-master  File: HistogramStatisticsWrapper.java View source code
@Override
public void dump(OutputStream output) {
    try (PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(output, UTF_8))) {
        for (Long value : histogramStatistics.getValues()) {
            printWriter.printf("%d%n", value);
        }
    }
}
Example 2
Project: cdo-master  File: GZIPStreamWrapper.java View source code
public GZIPOutputStream wrapOutputStream(OutputStream out) throws IOException {
    if (out instanceof GZIPOutputStream) {
        return (GZIPOutputStream) out;
    }
    return new GZIPOutputStream(out, bufferSize) {

        {
            def.setLevel(compressionLevel);
        }
    };
}
Example 3
Project: pentaho-kettle-master  File: GZIPCompressionOutputStream.java View source code
protected static GZIPOutputStream getDelegate(OutputStream out) throws IOException {
    GZIPOutputStream delegate = null;
    if (out instanceof ZipOutputStream) {
        delegate = (GZIPOutputStream) out;
    } else {
        delegate = new GZIPOutputStream(out);
    }
    return delegate;
}
Example 4
Project: kanqiu_letv-master  File: IoUtils.java View source code
public static void copyStream(InputStream is, OutputStream os) throws IOException {
    byte[] bytes = new byte[BUFFER_SIZE];
    while (true) {
        int count = is.read(bytes, 0, BUFFER_SIZE);
        if (count == -1) {
            break;
        }
        os.write(bytes, 0, count);
    }
}
Example 5
Project: jena-master  File: AbstractQuadsInputFormatTests.java View source code
@Override
protected void generateTuples(OutputStream output, int num) throws IOException {
    for (int i = 0; i < num; i++) {
        output.write(("<http://subjects/" + i + "> <http://predicate> \"" + i + "\" <http://graphs/" + i + "> .\n").getBytes(utf8));
    }
    output.flush();
    output.close();
}
Example 6
Project: sysart-itext-master  File: TestResourceUtils.java View source code
private static void writeInputToOutput(InputStream is, OutputStream os) throws IOException {
    final byte[] buffer = new byte[8192];
    while (true) {
        final int bytesRead = is.read(buffer);
        if (bytesRead == -1) {
            break;
        }
        os.write(buffer, 0, bytesRead);
    }
}
Example 7
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 8
Project: ilarkesto-master  File: XStreamSerializer.java View source code
@Override
public void serialize(Object bean, OutputStream out) {
    try {
        Writer writer = new OutputStreamWriter(out, encoding);
        writer.write("<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>");
        xstream.toXML(bean, writer);
        writer.flush();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
Example 9
Project: geoserver-enterprise-master  File: StoredFileResponse.java View source code
public void write(Object value, OutputStream output, Operation operation) throws IOException {
    File file = (File) value;
    FileInputStream fos = null;
    try {
        cleaner.lock(file);
        fos = new FileInputStream(file);
        IOUtils.copy(fos, output);
    } finally {
        cleaner.unlock(file);
        IOUtils.closeQuietly(fos);
    }
}
Example 10
Project: jlibs-master  File: DOMPayload.java View source code
@Override
public void writeTo(OutputStream out) throws IOException {
    try {
        Transformer transformer = TransformerUtil.newTransformer(null, omitXMLDeclaration, indentAmount, IOUtil.UTF_8.name());
        transformer.transform(new DOMSource(node), new StreamResult(out));
    } catch (TransformerException ex) {
        throw new IOException(ex);
    }
}
Example 11
Project: cloudtm-data-platform-master  File: ClassloaderMessageListener.java View source code
public void getState(final OutputStream output) throws Exception {
    final Thread currentThread = Thread.currentThread();
    final ClassLoader previous = currentThread.getContextClassLoader();
    currentThread.setContextClassLoader(cl);
    try {
        delegate.getState(output);
    } finally {
        currentThread.setContextClassLoader(previous);
    }
}
Example 12
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 13
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 14
Project: PARWorks-Android-MARS-master  File: Utilities.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 15
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 16
Project: android_packages_apps-master  File: SmilXmlSerializer.java View source code
public static void serialize(SMILDocument smilDoc, OutputStream out) {
    try {
        Writer writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"), 2048);
        writeElement(writer, smilDoc.getDocumentElement());
        writer.flush();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 17
Project: breakout-master  File: BimapperStreamBimapper.java View source code
@Override
public void write(T t, OutputStream out) throws Exception {
    OutputStreamWriter writer = null;
    try {
        writer = new OutputStreamWriter(out);
        writer.write(format.map(t));
        writer.flush();
    } finally {
        if (closeStreams && writer != null) {
            try {
                writer.close();
            } catch (Exception ex) {
            }
        }
    }
}
Example 18
Project: rsimulator-master  File: ResponseWriter.java View source code
public void write(RequestReader.Request request, SimulatorResponse simulatorResponse, OutputStream out) throws IOException {
    String responseBody = simulatorResponse.getResponse();
    log.debug("responseBody: #{}#", responseBody);
    String response = prependHeader(request.getHeader(), responseBody);
    log.info("response: #{}#", response);
    out.write(response.getBytes(encoding));
    out.flush();
}
Example 19
Project: bigpetstore-master  File: OpenEntity.java View source code
@Override
public void writeTo(OpenEntity e, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream out) throws IOException {
    try {
        IOUtils.copyBytes(e.in, out, e.length, 4096, false);
    } finally {
        IOUtils.cleanup(DatanodeWebHdfsMethods.LOG, e.in);
        IOUtils.cleanup(DatanodeWebHdfsMethods.LOG, e.dfsclient);
    }
}
Example 20
Project: android-15-master  File: ViewStateSerializer.java View source code
static boolean serializeViewState(OutputStream stream, WebView web) throws IOException {
    int baseLayer = web.getBaseLayer();
    if (baseLayer == 0) {
        return false;
    }
    DataOutputStream dos = new DataOutputStream(stream);
    dos.writeInt(VERSION);
    dos.writeInt(web.getContentWidth());
    dos.writeInt(web.getContentHeight());
    return nativeSerializeViewState(baseLayer, dos, new byte[WORKING_STREAM_STORAGE]);
}
Example 21
Project: ecologylabFundamental-master  File: StringSerializer.java View source code
@Override
public void serialize(Object object, OutputStream outputStream, TranslationContext translationContext) throws SIMPLTranslationException {
    //		serialize(object, (Appendable) new PrintStream(outputStream), translationContext);
    try {
        serialize(object, (Appendable) new PrintStream(outputStream, true, "utf-8"), translationContext);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}
Example 22
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 23
Project: apache-james-mime4j-groundhog-master  File: StringTextBody.java View source code
@Override
public void writeTo(OutputStream out) throws IOException {
    if (out == null)
        throw new IllegalArgumentException();
    Reader reader = new StringReader(text);
    Writer writer = new OutputStreamWriter(out, charset);
    char buffer[] = new char[1024];
    while (true) {
        int nChars = reader.read(buffer);
        if (nChars == -1)
            break;
        writer.write(buffer, 0, nChars);
    }
    reader.close();
    writer.flush();
}
Example 24
Project: mkgmap-master  File: FileBlock.java View source code
/**
	 * Write to an output stream.
	 *
	 * This will be to the actual TDB file.
	 */
public void writeTo(OutputStream os, int codePage) throws IOException {
    StructuredOutputStream output = getStructuredOutput(codePage);
    writeBody(output);
    byte[] b = this.output.toByteArray();
    // Fill in the actual full block length
    int blockLength = b.length - 3;
    b[1] = (byte) (blockLength & 0xff);
    b[2] = (byte) ((blockLength >> 8) & 0xff);
    os.write(b);
}
Example 25
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 26
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 27
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 28
Project: usercenter-master  File: ASN1Writer.java View source code
public static void writeElement(final ASN1Element element, final OutputStream outputStream) throws IOException {
    debugASN1Write(element);
    ByteStringBuffer buffer = buffers.get();
    if (buffer == null) {
        buffer = new ByteStringBuffer();
        buffers.set(buffer);
    }
    element.encodeTo(buffer);
    try {
        buffer.write(outputStream);
    } finally {
        if (buffer.capacity() > MAX_BUFFER_LENGTH) {
            buffer.setCapacity(MAX_BUFFER_LENGTH);
        }
        buffer.clear();
    }
}
Example 29
Project: ha-bridge-master  File: DevModeResponse.java View source code
private String dataReader(String filePath) {
    String content = null;
    try {
        InputStream input = getClass().getResourceAsStream(filePath);
        OutputStream out = new ByteArrayOutputStream();
        int read;
        byte[] bytes = new byte[1024];
        while ((read = input.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        content = out.toString();
    } catch (IOException e) {
        log.error("Error reading the file: " + filePath + " message: " + e.getMessage(), e);
    }
    return content;
}
Example 30
Project: cms-ce-master  File: BlobKeyCreator.java View source code
public static BlobKey createKey(final InputStream in, final OutputStream out) throws BlobStoreException {
    try {
        final MessageDigest digest = createMessageDigest();
        final DigestOutputStream digestOut = new DigestOutputStream(out, digest);
        try {
            ByteStreams.copy(in, digestOut);
        } finally {
            digestOut.close();
            in.close();
        }
        return new BlobKey(digest.digest());
    } catch (IOException e) {
        throw new BlobStoreException("Failed to create blob key", e);
    }
}
Example 31
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 32
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 33
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 34
Project: spring-framework-2.5.x-master  File: HessianExporter.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.skeletonInvoker, "Hessian exporter has not been initialized");
    ClassLoader originalClassLoader = overrideThreadContextClassLoader();
    try {
        this.skeletonInvoker.invoke(inputStream, outputStream);
    } finally {
        resetThreadContextClassLoader(originalClassLoader);
    }
}
Example 35
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 36
Project: open-mika-master  File: Multipart.java View source code
/**
     * 
     * @see org.apache.james.mime4j.message.Body#writeTo(java.io.OutputStream)
     */
public void writeTo(OutputStream out) throws IOException {
    String boundary = getBoundary();
    List bodyParts = getBodyParts();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, CharsetUtil.getCharset(getCharset())), 8192);
    writer.write(getPreamble() + "\r\n");
    for (int i = 0; i < bodyParts.size(); i++) {
        writer.write(boundary + "\r\n");
        ((BodyPart) bodyParts.get(i)).writeTo(out);
    }
    writer.write(getEpilogue() + "\r\n");
    writer.write(boundary + "--" + "\r\n");
}
Example 37
Project: openwayback-master  File: JSPExecRule.java View source code
public void emit(ReplayParseContext context, Node node) throws ServletException, IOException {
    JSPExecutor jspExec = context.getJspExec();
    if (jspExec != null) {
        OutputStream os = context.getOutputStream();
        if (os != null) {
            String jspResult = jspExec.jspToString(jspPath);
            byte[] bytes = null;
            try {
                bytes = jspResult.getBytes(context.getOutputCharset());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                bytes = jspResult.getBytes();
            }
            os.write(bytes);
        }
    }
}
Example 38
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 39
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 40
Project: abmash-master  File: IOTools.java View source code
public static File convertStreamToFile(InputStream inputStream, String extension) {
    try {
        File tmpFile = File.createTempFile("file", "." + extension);
        tmpFile.deleteOnExit();
        // write the inputStream to a FileOutputStream
        OutputStream out = new FileOutputStream(tmpFile);
        int read = 0;
        byte[] bytes = new byte[1024];
        while ((read = inputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        inputStream.close();
        out.flush();
        out.close();
        return tmpFile;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Example 41
Project: google-web-toolkit-svnmirror-master  File: StaticResources.java View source code
public static void emit(OutputDirectory outDir) throws IOException {
    String prefix = StaticResources.class.getPackage().getName().replace('.', '/') + "/resources/";
    ClassLoader loader = StaticResources.class.getClassLoader();
    for (String resourceName : resourceNames) {
        InputStream in = loader.getResourceAsStream(prefix + resourceName);
        if (in == null) {
            throw new Error("Could not find resource via my class loader: " + prefix + resourceName);
        }
        OutputStream out = outDir.getOutputStream(resourceName);
        Utility.streamOut(in, out, 10240);
        in.close();
        out.close();
    }
}
Example 42
Project: milton2-master  File: MultiStatusEntity.java View source code
@Override
public void write(Response response, OutputStream outputStream) throws Exception {
    XmlWriter writer = new XmlWriter(response.getOutputStream());
    writer.writeXMLHeader();
    // only single namespace for this method
    writer.open("multistatus xmlns:D" + "=\"" + WebDavProtocol.NS_DAV + ":\"");
    writer.newLine();
    for (HrefStatus status : getStatii()) {
        XmlWriter.Element elResponse = writer.begin("response").open();
        writer.writeProperty("", "href", status.href);
        writer.writeProperty("", "status", status.status.code + "");
        elResponse.close();
    }
    writer.close("multistatus");
    writer.flush();
}
Example 43
Project: polly-master  File: HttpResourceAnswer.java View source code
@Override
public void getAnswer(OutputStream out, HttpServer server) throws IOException {
    InputStream in = null;
    try {
        final String path = this.resourcePath.startsWith("/") ? this.resourcePath.substring(1) : this.resourcePath;
        in = this.cl.getResourceAsStream(path);
        if (in == null) {
            return;
        }
        final byte[] buffer = new byte[BUFFER_SIZE];
        int read = in.read(buffer, 0, buffer.length);
        while (read != -1) {
            out.write(buffer, 0, read);
            read = in.read(buffer, 0, buffer.length);
        }
    } finally {
        if (in != null) {
            in.close();
        }
    }
}
Example 44
Project: bitcoinj-master  File: TransactionOutputChanges.java View source code
public void serializeToStream(OutputStream bos) throws IOException {
    int numOutsCreated = txOutsCreated.size();
    bos.write(0xFF & numOutsCreated);
    bos.write(0xFF & (numOutsCreated >> 8));
    bos.write(0xFF & (numOutsCreated >> 16));
    bos.write(0xFF & (numOutsCreated >> 24));
    for (UTXO output : txOutsCreated) {
        output.serializeToStream(bos);
    }
    int numOutsSpent = txOutsSpent.size();
    bos.write(0xFF & numOutsSpent);
    bos.write(0xFF & (numOutsSpent >> 8));
    bos.write(0xFF & (numOutsSpent >> 16));
    bos.write(0xFF & (numOutsSpent >> 24));
    for (UTXO output : txOutsSpent) {
        output.serializeToStream(bos);
    }
}
Example 45
Project: eclipselink.runtime-master  File: PrintStackTraceTest.java View source code
/**
     * This method was created in VisualAge.
     */
public void test() {
    // do not use logMessages(), which has been already set up for the session
    Integer integer = new Integer(1);
    try {
        UnitOfWork uow = getSession().acquireUnitOfWork();
        uow.registerObject(integer);
        uow.commit();
    } catch (org.eclipse.persistence.exceptions.EclipseLinkException e) {
        java.io.OutputStream out = new java.io.ByteArrayOutputStream(100);
        e.printStackTrace(new java.io.PrintStream(out));
        if (out.toString().length() < 200) {
            throw new TestErrorException("Exception toString was to complete.");
        }
    }
}
Example 46
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 47
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 48
Project: lucene-solr-master  File: TestVirusCheckingFS.java View source code
/** Test Files.delete fails if a file has an open inputstream against it */
public void testDeleteSometimesFails() throws IOException {
    Path dir = wrap(createTempDir());
    int counter = 0;
    while (true) {
        Path path = dir.resolve("file" + counter);
        counter++;
        OutputStream file = Files.newOutputStream(path);
        file.write(5);
        file.close();
        // File is now closed, we attempt delete:
        try {
            Files.delete(path);
        } catch (AccessDeniedException ade) {
            assertTrue(ade.getMessage().contains("VirusCheckingFS is randomly refusing to delete file "));
            break;
        }
        assertFalse(Files.exists(path));
    }
}
Example 49
Project: fdroidclient-master  File: TestUtils.java View source code
public static File copyResourceToTempFile(String resourceName) {
    File tempFile = null;
    InputStream input = null;
    OutputStream output = null;
    try {
        tempFile = File.createTempFile(resourceName + "-", ".testasset");
        input = TestUtils.class.getClassLoader().getResourceAsStream(resourceName);
        output = new FileOutputStream(tempFile);
        Utils.copy(input, output);
    } catch (IOException e) {
        e.printStackTrace();
        if (tempFile != null && tempFile.exists()) {
            assertTrue(tempFile.delete());
        }
        fail();
        return null;
    } finally {
        Utils.closeQuietly(output);
        Utils.closeQuietly(input);
    }
    return tempFile;
}
Example 50
Project: js-android-app-master  File: PermanentDatabase.java View source code
public ResourceDatabase prepare() {
    File originalFile = resourceDatabase.getFile();
    String copyResourceName = originalFile.getName() + "-copy";
    File copyFile = new File(originalFile.getParentFile(), copyResourceName);
    InputStream in = resourceDatabase.getInputStream();
    try {
        OutputStream out = new FileOutputStream(copyFile);
        IOUtils.copy(in, out);
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
        ResourceDatabase resourceDatabase = ResourceDatabase.get(copyResourceName);
        return resourceDatabase;
    } catch (FileNotFoundException e) {
        throw new RuntimeException();
    } catch (IOException e) {
        throw new RuntimeException();
    }
}
Example 51
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 52
Project: GeoGig-master  File: DepthResource.java View source code
@Override
public void write(OutputStream out) throws IOException {
    PrintWriter w = new PrintWriter(out);
    Form options = request.getResourceRef().getQueryAsForm();
    Optional<String> commit = Optional.fromNullable(options.getFirstValue("commitId", null));
    Optional<GeoGIG> geogig = getGeogig(request);
    Preconditions.checkState(geogig.isPresent());
    GeoGIG ggit = geogig.get();
    Optional<Integer> depth = Optional.absent();
    if (commit.isPresent()) {
        depth = Optional.of(ggit.getRepository().graphDatabase().getDepth(ObjectId.valueOf(commit.get())));
    } else {
        depth = ggit.getRepository().getDepth();
    }
    if (depth.isPresent()) {
        w.write(depth.get().toString());
    }
    w.flush();
}
Example 53
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 54
Project: HDP-2.2-Patched-master  File: TestClose.java View source code
@Test
public void testWriteAfterClose() throws IOException {
    Configuration conf = new Configuration();
    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build();
    try {
        final byte[] data = "foo".getBytes();
        FileSystem fs = FileSystem.get(conf);
        OutputStream out = fs.create(new Path("/test"));
        out.write(data);
        out.close();
        try {
            // Should fail.
            out.write(data);
            fail("Should not have been able to write more data after file is closed.");
        } catch (ClosedChannelException cce) {
        }
        // Should succeed. Double closes are OK.
        out.close();
    } finally {
        if (cluster != null) {
            cluster.shutdown();
        }
    }
}
Example 55
Project: palava-ipc-xml-rpc-master  File: JaxbEncoder.java View source code
@Override
protected Object encode(ChannelHandlerContext context, Channel channel, Object message) throws Exception {
    if (message instanceof MethodResponse) {
        final ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
        final OutputStream stream = new ChannelBufferOutputStream(buffer);
        final Marshaller marshaller = provider.get();
        marshaller.marshal(message, stream);
        if (LOG.isTraceEnabled()) {
            final StringWriter writer = new StringWriter();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(message, writer);
            LOG.trace("Xml-Rpc response:\n{}", writer);
        }
        return buffer;
    } else {
        return message;
    }
}
Example 56
Project: devcoin-android-master  File: ScriptChunk.java View source code
public void write(OutputStream stream) throws IOException {
    if (isOpCode) {
        checkState(data.length == 1);
        stream.write(data);
    } else {
        checkState(data.length <= Script.MAX_SCRIPT_ELEMENT_SIZE);
        if (data.length < OP_PUSHDATA1) {
            stream.write(data.length);
        } else if (data.length <= 0xFF) {
            stream.write(OP_PUSHDATA1);
            stream.write(data.length);
        } else if (data.length <= 0xFFFF) {
            stream.write(OP_PUSHDATA2);
            stream.write(0xFF & data.length);
            stream.write(0xFF & (data.length >> 8));
        } else {
            stream.write(OP_PUSHDATA4);
            Utils.uint32ToByteStreamLE(data.length, stream);
        }
        stream.write(data);
    }
}
Example 57
Project: picard-tools-master  File: FileFaker.java View source code
public void fakeFile(final File cycleFile, Integer size) throws IOException {
    if (size == null) {
        size = 1;
    }
    this.size = size;
    final OutputStream outputStream;
    if (BclReader.isGzipped(cycleFile))
        outputStream = new GZIPOutputStream(new FileOutputStream(cycleFile));
    else if (BclReader.isBlockGzipped(cycleFile))
        outputStream = new BlockCompressedOutputStream(cycleFile);
    else
        outputStream = new FileOutputStream(cycleFile);
    final WritableByteChannel channel = Channels.newChannel(outputStream);
    final ByteBuffer buffer = ByteBuffer.allocate(this.bufferSize());
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    fakeFile(buffer);
    buffer.flip();
    channel.write(buffer);
    channel.close();
    outputStream.close();
}
Example 58
Project: gcontact-excel-sync-master  File: MediaMultipartGenerator.java View source code
/**
   * Generates output for requests that target media resources.
   */
public void generate(OutputStream contentStream, OutputProperties request, MediaMultipart source) throws IOException {
    OutputProperties prevProperties = null;
    try {
        prevProperties = GDataContentHandler.setThreadOutputProperties(request);
        source.writeTo(contentStream);
    } catch (MessagingException me) {
        Throwable t = me.getCause();
        if (t instanceof IOException) {
            throw (IOException) t;
        }
        IOException ioe = new IOException("Invalid multipart content");
        ioe.initCause(new InvalidEntryException("Invalid media entry", me));
        throw ioe;
    } finally {
        GDataContentHandler.setThreadOutputProperties(prevProperties);
    }
}
Example 59
Project: aokp-gerrit-master  File: HttpContactStoreConnection.java View source code
@Override
public void store(final byte[] body) throws IOException {
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    conn.setDoOutput(true);
    conn.setFixedLengthStreamingMode(body.length);
    try (OutputStream out = conn.getOutputStream()) {
        out.write(body);
    }
    if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new IOException("Connection failed: " + conn.getResponseCode());
    }
    final byte[] dst = new byte[2];
    final InputStream in = conn.getInputStream();
    try {
        IO.readFully(in, dst, 0, 2);
    } finally {
        in.close();
    }
    if (dst[0] != 'O' || dst[1] != 'K') {
        throw new IOException("Store failed: " + dst[0] + dst[1]);
    }
}
Example 60
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 61
Project: hadoop-on-lustre2-master  File: TestRetriableFileCopyCommand.java View source code
@SuppressWarnings("rawtypes")
@Test
public void testFailOnCloseError() throws Exception {
    Mapper.Context context = mock(Mapper.Context.class);
    doReturn(new Configuration()).when(context).getConfiguration();
    Exception expectedEx = new IOException("boom");
    OutputStream out = mock(OutputStream.class);
    doThrow(expectedEx).when(out).close();
    File f = File.createTempFile(this.getClass().getSimpleName(), null);
    f.deleteOnExit();
    FileStatus stat = new FileStatus(1L, false, 1, 1024, 0, new Path(f.toURI()));
    Exception actualEx = null;
    try {
        new RetriableFileCopyCommand("testFailOnCloseError").copyBytes(stat, out, 512, context);
    } catch (Exception e) {
        actualEx = e;
    }
    assertNotNull("close didn't fail", actualEx);
    assertEquals(expectedEx, actualEx);
}
Example 62
Project: extension-aws-master  File: UploadDiskFileItem.java View source code
public OutputStream getOutputStream() throws IOException {
    // item.putProperty("offset", inReq.getRequestParameter("offset"));
    // log.info("Uploading from offset: " + item.get("offset"));
    OutputStream fos;
    File file = getTempFile();
    if (fieldSeek > 0 && file.length() == fieldSeek) {
        fos = new FileOutputStream(file, true);
    } else {
        fos = new FileOutputStream(getTempFile());
    }
    return new BufferedOutputStream(fos) {

        public void write(byte[] bytes, int one, int two) throws IOException {
            //Put breakpoint here to slow down progress SLOWDOWN
            //						try
            //						{
            //							Thread.sleep(100);
            //						}
            //						catch( Exception ex)
            //						{
            //							
            //						}
            super.write(bytes, one, two);
        }
    };
}
Example 63
Project: rascal-master  File: SnakesAndLadders.java View source code
private void copyFile(URIResolverRegistry reg, ISourceLocation sourceRoot, ISourceLocation sourcePath, File targetRoot) throws IOException {
    File targetPath = new File(targetRoot, sourcePath.getPath().replace(sourceRoot.getPath(), ""));
    if (targetPath.getAbsolutePath().endsWith(".jv")) {
        String targetPathName = targetPath.getAbsolutePath();
        targetPath = new File(targetPathName.substring(0, targetPathName.length() - 3) + ".java");
    }
    targetPath.getParentFile().mkdirs();
    try (InputStream from = reg.getInputStream(sourcePath)) {
        try (OutputStream to = new FileOutputStream(targetPath)) {
            byte[] buffer = new byte[8 * 1024];
            int read;
            while ((read = from.read(buffer)) > 0) {
                to.write(buffer, 0, read);
            }
        } finally {
            targetPath.deleteOnExit();
        }
    }
}
Example 64
Project: org.eclipse.ecr-master  File: JsonAutomationInfoWriter.java View source code
public void writeTo(AutomationInfo arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4, MultivaluedMap<String, Object> arg5, OutputStream arg6) throws IOException, WebApplicationException {
    JSONObject json = new JSONObject();
    JSONObject paths = new JSONObject();
    paths.element("login", "login");
    json.element("paths", paths);
    // operations
    JSONArray ops = new JSONArray();
    for (OperationDocumentation doc : arg0.getOperations()) {
        JSONObject op = JSONExporter.toJSON(doc);
        ops.add(op);
    }
    json.element("operations", ops);
    // operation chains
    JSONArray chains = new JSONArray();
    for (OperationDocumentation doc : arg0.getChains()) {
        JSONObject op = JSONExporter.toJSON(doc);
        op.element("url", "Chain." + doc.id);
        chains.add(op);
    }
    json.element("chains", chains);
    arg6.write(json.toString(2).getBytes("UTF-8"));
}
Example 65
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());
    }
}
Example 66
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 67
Project: geotoolkit-master  File: AbstractDescribeFeatureType.java View source code
/**
     * [email protected]}
     */
@Override
public InputStream getResponseStream() throws IOException {
    if (featureId == null) {
        throw new IllegalArgumentException("The parameter \"featureId\" is not defined");
    }
    final URL url = new URL(serverURL);
    URLConnection conec = url.openConnection();
    conec = security.secure(conec);
    conec.setDoOutput(true);
    conec.setRequestProperty("Content-Type", "text/xml");
    OutputStream stream = conec.getOutputStream();
    stream = security.encrypt(stream);
    try {
        final Marshaller marsh = POOL.acquireMarshaller();
        final DescribeFeatureType describeFeatureTypeXml = new DescribeFeatureType(version, featureId);
        marsh.marshal(describeFeatureTypeXml, stream);
        POOL.recycle(marsh);
    } catch (JAXBException ex) {
        throw new IOException(ex);
    }
    stream.close();
    return security.decrypt(conec.getInputStream());
}
Example 68
Project: yarn-comment-master  File: TestWriteConfigurationToDFS.java View source code
@Test(timeout = 60000)
public void testWriteConf() throws Exception {
    Configuration conf = new HdfsConfiguration();
    conf.setInt(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, 4096);
    System.out.println("Setting conf in: " + System.identityHashCode(conf));
    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
    FileSystem fs = null;
    OutputStream os = null;
    try {
        fs = cluster.getFileSystem();
        Path filePath = new Path("/testWriteConf.xml");
        os = fs.create(filePath);
        StringBuilder longString = new StringBuilder();
        for (int i = 0; i < 100000; i++) {
            longString.append("hello");
        }
        // 500KB
        conf.set("foobar", longString.toString());
        conf.writeXml(os);
        os.close();
        os = null;
        fs.close();
        fs = null;
    } finally {
        IOUtils.cleanup(null, os, fs);
        cluster.shutdown();
    }
}
Example 69
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 70
Project: eclipse-integration-commons-master  File: SimpleDownloadService.java View source code
[email protected]
public void fetch(URL url, OutputStream writeTo) throws IOException {
    URLConnection conn = null;
    InputStream input = null;
    try {
        conn = connectionFactory.createConnection(url);
        conn.connect();
        if (DEBUG) {
            System.out.println(">>> " + url);
            Map<String, List<String>> headers = conn.getHeaderFields();
            for (Entry<String, List<String>> header : headers.entrySet()) {
                System.out.println(header.getKey() + ":");
                for (String value : header.getValue()) {
                    System.out.println("   " + value);
                }
            }
            System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        }
        input = conn.getInputStream();
        IOUtil.pipe(input, writeTo);
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (Throwable e) {
            }
        }
    }
}
Example 71
Project: openjdk-master  File: Processor.java View source code
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (!roundEnv.processingOver()) {
        for (Element element : roundEnv.getRootElements()) {
            String elementName = element.getSimpleName().toString();
            if (elementName.startsWith("AutoAnnotation_")) {
                continue;
            }
            String name = "AutoAnnotation_" + elementName;
            JavaFileObject jfo;
            try {
                jfo = processingEnv.getFiler().createSourceFile(name, element);
            } catch (IOException e) {
                throw new IOError(e);
            }
            try (OutputStream os = jfo.openOutputStream()) {
                String output = String.format("public @interface %s {}", name);
                os.write(output.getBytes(StandardCharsets.UTF_8));
            } catch (IOException e) {
                throw new IOError(e);
            }
        }
    }
    return false;
}
Example 72
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 73
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 74
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 75
Project: magnificent-mileage-master  File: JsonpCallbackFilter.java View source code
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    @SuppressWarnings("unchecked") Map<String, String[]> parms = httpRequest.getParameterMap();
    if (parms.containsKey("callback")) {
        if (log.isDebugEnabled())
            log.debug("Wrapping response with JSONP callback '" + parms.get("callback")[0] + "'");
        OutputStream out = httpResponse.getOutputStream();
        GenericResponseWrapper wrapper = new GenericResponseWrapper(httpResponse);
        chain.doFilter(request, wrapper);
        out.write(new String(parms.get("callback")[0] + "(").getBytes());
        out.write(wrapper.getData());
        out.write(new String(");").getBytes());
        wrapper.setContentType("text/javascript;charset=UTF-8");
        out.close();
    } else {
        chain.doFilter(request, response);
    }
}
Example 76
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 77
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 78
Project: openmap-master  File: WebBrowser.java View source code
/**
     * Write temporary file to temporary directory, and generate URL.
     * 
     * @param text text String
     * @return String file URL
     */
protected String writeFileAndGenerateURL(String text) {
    File tmpFile = null;
    try {
        tmpFile = File.createTempFile(Environment.OpenMapPrefix, ".html", new File(Environment.get(Environment.TmpDir)));
        // get rid of it when the user
        tmpFile.deleteOnExit();
        // quits.
        FileOutputStream fs = new FileOutputStream(tmpFile);
        PrintWriter out = new PrintWriter((OutputStream) fs);
        out.println(text);
        // close the streams
        fs.close();
        String urlString = tmpFile.toURI().toURL().toString();
        Debug.output("WebBrowser: created " + urlString);
        return urlString;
    } catch (SecurityException se) {
        Debug.error("WebBrowser.writeAndGenerateURL: " + se);
    } catch (IOException ioe) {
        Debug.error("WebBrowser.writeAndGenerateURL: " + ioe);
    }
    postErrorMessage("Cannot write to temp file:" + (tmpFile != null ? tmpFile.getAbsolutePath() : "unknown"));
    return null;
}
Example 79
Project: syncthing-android-master  File: PostTask.java View source code
/**
     * For [email protected] #URI_CONFIG}, params[0] must contain the config.
     *
     * For [email protected] #URI_SCAN}, params[0] must contain the folder, and params[1] the subfolder.
     */
@Override
protected Boolean doInBackground(String... params) {
    try {
        HttpsURLConnection connection = (mPath.equals(URI_SCAN)) ? openConnection("folder", params[0], "sub", params[1]) : openConnection();
        connection.setRequestMethod("POST");
        Log.v(TAG, "Calling Rest API at " + connection.getURL());
        if (mPath.equals(URI_CONFIG)) {
            OutputStream os = connection.getOutputStream();
            os.write(params[0].getBytes("UTF-8"));
        }
        connection.connect();
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String line;
        String result = "";
        while ((line = br.readLine()) != null) {
            result += line;
        }
        br.close();
        Log.v(TAG, "API call result: " + result);
        return true;
    } catch (IOException e) {
        Log.w(TAG, "Failed to call rest api", e);
        return false;
    }
}
Example 80
Project: oobd-master  File: CMSEncryptedDataGenerator.java View source code
private CMSEncryptedData doGenerate(CMSTypedData content, OutputEncryptor contentEncryptor) throws CMSException {
    AlgorithmIdentifier encAlgId;
    ASN1OctetString encContent;
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    try {
        OutputStream cOut = contentEncryptor.getOutputStream(bOut);
        content.write(cOut);
        cOut.close();
    } catch (IOException e) {
        throw new CMSException("");
    }
    byte[] encryptedContent = bOut.toByteArray();
    encAlgId = contentEncryptor.getAlgorithmIdentifier();
    encContent = new BEROctetString(encryptedContent);
    EncryptedContentInfo eci = new EncryptedContentInfo(content.getContentType(), encAlgId, encContent);
    ASN1Set unprotectedAttrSet = null;
    if (unprotectedAttributeGenerator != null) {
        AttributeTable attrTable = unprotectedAttributeGenerator.getAttributes(new HashMap());
        unprotectedAttrSet = new BERSet(attrTable.toASN1EncodableVector());
    }
    ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.encryptedData, new EncryptedData(eci, unprotectedAttrSet));
    return new CMSEncryptedData(contentInfo);
}
Example 81
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 82
Project: openjdk8-jdk-master  File: B6431193.java View source code
/**
         * @param args
         */
public static void main(String[] args) {
    class MyHandler implements HttpHandler {

        public void handle(HttpExchange t) throws IOException {
            InputStream is = t.getRequestBody();
            read(is);
            // .. read the request body
            String response = "This is the response";
            t.sendResponseHeaders(200, response.length());
            OutputStream os = t.getResponseBody();
            os.write(response.getBytes());
            os.close();
            error = Thread.currentThread().isDaemon();
        }
    }
    HttpServer server;
    try {
        server = HttpServer.create(new InetSocketAddress(0), 10);
        server.createContext("/apps", new MyHandler());
        server.setExecutor(null);
        // creates a default executor
        server.start();
        int port = server.getAddress().getPort();
        String s = "http://localhost:" + port + "/apps/foo";
        URL url = new URL(s);
        InputStream is = url.openStream();
        read(is);
        server.stop(1);
        if (error) {
            throw new RuntimeException("error in test");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 83
Project: wso2-synapse-master  File: FIXMessageFromatterTest.java View source code
public void testWriteTo() {
    String input = "8=FIX.4.09=10535=D34=249=BANZAI52=20080711-06:42:2656=SYNAPSE" + "11=121575854627821=138=9000000040=154=155=DEL59=010=121";
    MessageContext msgCtx = new MessageContext();
    FIXMessageBuilder builder = new FIXMessageBuilder();
    OMElement element = null;
    try {
        element = builder.processDocument(new ByteArrayInputStream(input.getBytes()), "fix/j", msgCtx);
        Assert.assertNotNull(element);
    // System.out.println(element);
    } catch (AxisFault e) {
        e.printStackTrace();
    }
    FIXMessageFromatter fixMessageFromatter = new FIXMessageFromatter();
    // msgCtx = new MessageContext();
    // msgCtx.seten
    OutputStream output = new ByteArrayOutputStream();
    SOAPFactory factory = OMAbstractFactory.getSOAP12Factory();
    SOAPEnvelope env = factory.getDefaultEnvelope();
    env.getBody().addChild(element);
    try {
        msgCtx.setEnvelope(env);
    } catch (AxisFault e1) {
        e1.printStackTrace();
    }
    OMOutputFormat myOutputFormat = new OMOutputFormat();
    try {
        fixMessageFromatter.writeTo(msgCtx, myOutputFormat, output, false);
        assertTrue(output.toString().length() > 0);
    } catch (AxisFault e) {
        e.printStackTrace();
    }
}
Example 84
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 85
Project: framework-master  File: TestFileUploadSize.java View source code
@Override
protected void setup() {
    getLayout().setMargin(new MarginInfo(true, false, false, false));
    getLayout().setSpacing(true);
    Upload u = new Upload("Upload", new Upload.Receiver() {

        @Override
        public OutputStream receiveUpload(String filename, String mimeType) {
            return baos;
        }
    });
    u.setId("UPL");
    u.addStartedListener(new Upload.StartedListener() {

        @Override
        public void uploadStarted(StartedEvent event) {
            expectedSize.setValue(String.valueOf(event.getContentLength()));
        }
    });
    u.addFinishedListener(new Upload.FinishedListener() {

        @Override
        public void uploadFinished(FinishedEvent event) {
            label.setValue("Upload finished. Name: " + event.getFilename());
            receivedSize.setValue(String.valueOf(baos.size()));
            baos.reset();
        }
    });
    expectedSize.setId("expected");
    receivedSize.setId("received");
    GridLayout grid = new GridLayout(2, 2);
    grid.addComponent(new Label("Expected size:"), 0, 0);
    grid.addComponent(new Label("Received size:"), 0, 1);
    grid.addComponent(expectedSize, 1, 0);
    grid.addComponent(receivedSize, 1, 1);
    addComponent(label);
    addComponent(grid);
    addComponent(u);
}
Example 86
Project: jumi-master  File: JumiLauncherBuilder.java View source code
public JumiLauncher build() {
    ExecutorService actorsThreadPool = createActorsThreadPool();
    ProcessStarter processStarter = createProcessStarter();
    NetworkServer networkServer = createNetworkServer();
    OutputStream daemonOutputListener = createDaemonOutputListener();
    Actors actors = new MultiThreadedActors(actorsThreadPool, new ComposedEventizerProvider(new DaemonSummonerEventizer(), new SuiteLauncherEventizer(), new DaemonListenerEventizer()), new PrintStreamFailureLogger(System.out), new NullMessageListener());
    ActorThread actorThread = startActorThread(actors);
    ActorRef<DaemonSummoner> daemonSummoner = actorThread.bindActor(DaemonSummoner.class, new ProcessStartingDaemonSummoner(new DirBasedSteward(new EmbeddedDaemonJar()), processStarter, networkServer, daemonOutputListener));
    ActorRef<SuiteLauncher> suiteLauncher = actorThread.bindActor(SuiteLauncher.class, new RemoteSuiteLauncher(actorThread, daemonSummoner));
    return new JumiLauncher(suiteLauncher, () -> {
        networkServer.close();
        actorThread.stop();
        actorsThreadPool.shutdown();
        try {
            actorsThreadPool.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    });
}
Example 87
Project: FireflowEngine20-master  File: RawView2.java View source code
public void render(HttpServletRequest req, HttpServletResponse resp, Object obj) throws Throwable {
    if (resp.getContentType() == null)
        resp.setContentType(contentType);
    resp.addHeader("Connection", "close");
    String rangeStr = req.getHeader("Range");
    if (rangeStr == null) {
        resp.setContentLength(maxLen);
        Streams.writeAndClose(resp.getOutputStream(), in);
        return;
    }
    List<RangeRange> rs = new ArrayList<RawView.RangeRange>();
    if (!parseRange(rangeStr, rs, maxLen)) {
        resp.setStatus(416);
        return;
    }
    // 暂时只实现了单range
    if (rs.size() != 1) {
        // TODO 完成多range的下载
        log.info("multipart/byteranges is NOT support yet");
        resp.setStatus(416);
        return;
    }
    long totolSize = 0;
    for (RangeRange rangeRange : rs) {
        totolSize += (rangeRange.end - rangeRange.start);
    }
    resp.setStatus(206);
    resp.setHeader("Content-Length", "" + totolSize);
    resp.setHeader("Accept-Ranges", "bytes");
    // 暂时只有单range,so,简单起见吧
    RangeRange rangeRange = rs.get(0);
    resp.setHeader("Content-Range", String.format("bytes %d-%d/%d", rangeRange.start, rangeRange.end - 1, maxLen));
    OutputStream out = resp.getOutputStream();
    writeDownloadRange(in, out, rangeRange);
    out.close();
    System.out.println("END");
}
Example 88
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 89
Project: Technomap-master  File: ExportDisplayAction.java View source code
/**
     * Shows the image export dialog and processes the results.
     * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
     */
public void actionPerformed(ActionEvent evt) {
    // lazy initialization
    if (chooser == null)
        init();
    // open image save dialog
    File f = null;
    scaler.setImage(display.getOffscreenBuffer());
    int returnVal = chooser.showSaveDialog(display);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        f = chooser.getSelectedFile();
    } else {
        return;
    }
    String format = ((SimpleFileFilter) chooser.getFileFilter()).getExtension();
    String ext = IOLib.getExtension(f);
    if (!format.equals(ext)) {
        f = new File(f.toString() + "." + format);
    }
    double scale = scaler.getScale();
    // save image
    boolean success = false;
    try {
        OutputStream out = new BufferedOutputStream(new FileOutputStream(f));
        System.out.print("Saving image " + f.getName() + ", " + format + " format...");
        success = display.saveImage(out, format, scale);
        out.flush();
        out.close();
        System.out.println("\tDONE");
    } catch (Exception e) {
        success = false;
    }
    // show result dialog on failure
    if (!success) {
        JOptionPane.showMessageDialog(display, "Error Saving Image!", "Image Save Error", JOptionPane.ERROR_MESSAGE);
    }
}
Example 90
Project: deb-kitkat-storage-access-framework-master  File: ParcelFileDescriptorTest.java View source code
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void testThatPipeShouldWorkProperly() throws Exception {
    final String givenData = "Hello, ParcelFileDescriptor.";
    final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
    final ParcelFileDescriptor source = pipe[0];
    final ParcelFileDescriptor sink = pipe[1];
    final InputStream in = new FileInputStream(source.getFileDescriptor());
    final OutputStream out = new ByteArrayOutputStream();
    new AsyncTask<ParcelFileDescriptor, Void, Void>() {

        @Override
        protected Void doInBackground(ParcelFileDescriptor... params) {
            //Simulates long periodic network operation
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException ignore) {
            }
            ParcelFileDescriptor pfd = params[0];
            FileDescriptor fd = pfd.getFileDescriptor();
            FileOutputStream out = new FileOutputStream(fd);
            byte[] data = givenData.getBytes();
            try {
                out.write(data, 0, data.length);
                out.close();
                pfd.close();
            } catch (IOException ignore) {
            }
            return null;
        }
    }.execute(sink);
    final byte[] buffer = new byte[8192];
    for (int count; (count = in.read(buffer)) > -1; ) {
        out.write(buffer, 0, count);
    }
    assertThat(out.toString()).isEqualTo(givenData);
}
Example 91
Project: dataverse-master  File: DublinCoreExportUtilTest.java View source code
/**
     * Test of datasetJson2dublincore method, of class DublinCoreExportUtil.
     */
@Test
public void testDatasetJson2dublincore() throws Exception {
    File datasetVersionJson = new File("src/test/java/edu/harvard/iq/dataverse/export/ddi/dataset-finch1.json");
    String datasetVersionAsJson = new String(Files.readAllBytes(Paths.get(datasetVersionJson.getAbsolutePath())));
    JsonReader jsonReader = Json.createReader(new StringReader(datasetVersionAsJson));
    JsonObject obj = jsonReader.readObject();
    File dubCoreFile = new File("src/test/java/edu/harvard/iq/dataverse/export/ddi/dataset-finchDC.xml");
    String datasetAsDdi = XmlPrinter.prettyPrintXml(new String(Files.readAllBytes(Paths.get(dubCoreFile.getAbsolutePath()))));
    logger.info(datasetAsDdi);
    OutputStream output = new ByteArrayOutputStream();
    DublinCoreExportUtil.datasetJson2dublincore(obj, output, DublinCoreExportUtil.DC_FLAVOR_DCTERMS);
    String result = XmlPrinter.prettyPrintXml(output.toString());
    logger.info(result);
    assertEquals(datasetAsDdi, result);
/*
        System.out.println("datasetJson2dublincore");
        JsonObject datasetDtoAsJson = null;
        OutputStream expResult = null;
        OutputStream result = DublinCoreExportUtil.datasetJson2dublincore(datasetDtoAsJson);
        assertEquals(expResult, result);
        // TODO review the generated test code and remove the default call to fail.
        fail("The test case is a prototype.");
*/
}
Example 92
Project: shrinkwrap-master  File: AbstractStreamExporterImpl.java View source code
// -------------------------------------------------------------------------------------||
// Functional Methods -----------------------------------------------------------------||
// -------------------------------------------------------------------------------------||
/**
     * Obtains an [email protected] OutputStream} to the provided [email protected] File}.
     *
     * @param target
     * @param overwrite
     *            Whether we may overwrite an existing file
     * @return
     * @throws FileExistsException
     *             If the specified file exists and the overwrite flag is false
     * @throws IllegalArgumentException
     *             If the file target is not specified
     */
protected final OutputStream getOutputStreamToFile(final File target, final boolean overwrite) throws FileExistsException {
    // Precondition checks
    if (target == null) {
        throw new IllegalArgumentException("Target file must be specified");
    }
    if (target.isDirectory()) {
        throw new IllegalArgumentException("Cannot export a stream file to existing directory: " + target.getAbsolutePath());
    }
    // If target exists and we're not allowed to overwrite it
    if (target.exists() && !overwrite) {
        throw new FileExistsException("Target exists and we haven't been flagged to overwrite it: " + target.getAbsolutePath());
    }
    // Get Stream
    final OutputStream out;
    try {
        out = new FileOutputStream(target);
    } catch (final FileNotFoundException e) {
        throw new ArchiveExportException("File could not be created: " + target);
    }
    // Return
    return out;
}
Example 93
Project: jentrata-msh-master  File: ByteStreamDataContentHandler.java View source code
/**
     * Converts the object to a byte stream of the specified MIME type and 
     * write it to the output stream. 
     * 
     * @param obj the object to be converted.
     * @param mimeType the requested MIME type of the resulting byte stream.
     * @param os the output stream into which to write the converted byte stream. 
     * @throws IOException if unable to convert the given object.
     * @see javax.activation.DataContentHandler#writeTo(java.lang.Object, java.lang.String, java.io.OutputStream)
     */
public void writeTo(Object obj, String mimeType, OutputStream os) throws IOException {
    byte[] bytes = null;
    if (obj instanceof InputStream) {
        IOHandler.pipe((InputStream) obj, os);
        return;
    } else if (obj instanceof DataSource) {
        IOHandler.pipe(((DataSource) obj).getInputStream(), os);
        return;
    } else if (obj instanceof byte[]) {
        bytes = (byte[]) obj;
    } else if (obj instanceof String) {
        bytes = ((String) obj).getBytes();
    } else {
        try {
            String methodName = "writeTo";
            Class[] outsParam = new Class[] { OutputStream.class };
            Instance instance = new Instance(obj);
            if (instance.isMethodExist(methodName, outsParam)) {
                instance.invoke(methodName, outsParam, new Object[] { os });
            }
            return;
        } catch (Exception e) {
            bytes = null;
        }
    }
    if (bytes == null) {
        throw new IOException("Unable to convert object of type " + (obj == null ? "null" : obj.getClass().getName()));
    } else {
        os.write(bytes);
    }
}
Example 94
Project: android_platform_libcore-master  File: GenericSignatureFormatErrorTest.java View source code
@AndroidOnly("Uses Android specific class dalvik.system.DexFile " + "for loading classes.")
@SideEffect("strange issue (exception: 'could not open dex file', " + "dalvikvm: 'waitpid failed' log msg  - only occurs when @SideEffect is removed " + "and this test is run via running tests.luni.AllTestsLang TestSuite")
public void test_signatureFormatError() throws Exception {
    /*
         * dex1.bytes is a jar file with a classes.dex in it.
         * the classes.dex was javac'ed, dx'ed and patched
         * with the following java file:
         *
         * package demo;
         *  public class HelloWorld<U> {
         *      public HelloWorld(U t) {}
         *  }
         *
         * patch:
         * the string constant (class generics signature string)
         *  "<U:" was changed to "<<:"
         *
         */
    File tf = File.createTempFile("classes", ".dex");
    // System.out.println("GenericSignatureFormatErrorTest:" +
    //         tf.getAbsolutePath() + ", canRead: " + tf.canRead() +
    //         ", canWrite: "+tf.canWrite());
    InputStream is = this.getClass().getResourceAsStream("dex1.bytes");
    assertNotNull(is);
    OutputStream fos = new FileOutputStream(tf);
    copy(is, fos);
    fos.flush();
    fos.close();
    //System.out.println("file length:"+tf.length());
    try {
        // Was:
        // DexFile df = new DexFile(tf);
        // Class clazz = df.loadClass("demo/HelloWorld", this.getClass().getClassLoader());
        ClassLoader cl = Support_ClassLoader.getInstance(tf.toURL(), getClass().getClassLoader());
        Class clazz = cl.loadClass("demo/HelloWorld");
        TypeVariable[] tvs = clazz.getTypeParameters();
        fail("expecting a GenericSignatureFormatError");
    // for (TypeVariable tv : tvs) {
    //     System.out.println("tv:"+tv.toString());
    // }
    } catch (GenericSignatureFormatError gsfe) {
    }
}
Example 95
Project: javainstaller-master  File: Download.java View source code
public void run() {
    InputStream input = null;
    OutputStream output = null;
    URLConnection connection = null;
    HttpURLConnection httpconnection = null;
    try {
        connection = url.openConnection();
        connection.connect();
        if (connection instanceof HttpURLConnection) {
            httpconnection = (HttpURLConnection) connection;
            // instead of the file
            if (httpconnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                final String error = "Server returned HTTP " + httpconnection.getResponseCode() + " " + httpconnection.getResponseMessage();
                handler.post(new Error(new Exception(error), ctx));
                System.out.println("Server returned HTTP " + httpconnection.getResponseCode() + " " + httpconnection.getResponseMessage());
            }
        }
        // this will be useful to display download percentage
        // might be -1: server did not report the length
        int fileLength = connection.getContentLength();
        // download the file
        input = connection.getInputStream();
        output = new FileOutputStream(path);
        final byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data, 0, 1024)) != -1) {
            total += count;
            final int percent = (int) (total * 100 / fileLength);
            final String status = total / 1024 + "/" + fileLength / 1024 + "kb  " + percent + "/100%";
            handler.post(new Runnable() {

                @Override
                public void run() {
                    progress.setProgress(percent);
                    tv.setText(status);
                }
            });
            output.write(data, 0, count);
        }
        input.close();
        output.close();
    //progress.dismiss();
    } catch (Exception e) {
        e.printStackTrace();
        handler.post(new Error(e, ctx));
    }
}
Example 96
Project: SecurePhoto-master  File: TimestampClient.java View source code
//    private static final String serverAddress = "http://timestamping.edelweb.fr/service/tsp";
static void requestTSP() throws IOException, NoSuchAlgorithmException, TSPException {
    TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();
    SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
    BigInteger nonce = BigInteger.valueOf(secureRandom.nextLong());
    TimeStampRequest request = reqGen.generate(TSPAlgorithms.SHA1, new byte[20], nonce);
    byte[] requestBytes = request.getEncoded();
    URL netAddress = new URL(serverAddress);
    HttpURLConnection connection = (HttpURLConnection) netAddress.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("ContentType", "application/timestamp-query");
    connection.setRequestProperty("ContentLength", String.valueOf(requestBytes.length));
    connection.setDoOutput(true);
    connection.connect();
    OutputStream stream = connection.getOutputStream();
    stream.write(requestBytes, 0, requestBytes.length);
    stream.close();
    InputStream responseStream = new BufferedInputStream(connection.getInputStream());
    TimeStampResponse timeStampResponse = new TimeStampResponse(responseStream);
    responseStream.close();
    byte[] response = timeStampResponse.getEncoded();
    TimeStampRequest recoveredRequest = new TimeStampRequest(requestBytes);
    TimeStampResponse recoveredResponse = new TimeStampResponse(response);
    recoveredResponse.validate(recoveredRequest);
    TimeStampToken tsToken = recoveredResponse.getTimeStampToken();
    TimeStampTokenInfo tsInfo = tsToken.getTimeStampInfo();
    SignerId signer_id = tsToken.getSID();
    BigInteger cert_serial_number = signer_id.getSerialNumber();
    System.out.println("Generation time " + tsInfo.getGenTime());
    System.out.println("Signer ID serial " + signer_id.getSerialNumber());
    System.out.println("Signer ID issuer " + signer_id.getIssuerAsString());
}
Example 97
Project: MyFramework-master  File: AgentPaymentBatchFileGenerator.java View source code
public static void main(String[] args) {
    String templateFile = "ccb-c.ftl";
    String fileName = "E:/template/RPT_ORG_SUMMARY" + DateUtil.formatCurrDateTime(DateUtil.DF_YMDHMS) + ".txt";
    Map model = new HashMap();
    String date = DateUtil.formatCurrDateTime(DateUtil.DF_YYYY_MM_DD);
    model.put("tlAccountNo", "100010001000");
    model.put("today", DateUtil.date2string(new Date()));
    List resultList = new ArrayList();
    AgentPaymentDetail paymentBatchDetail = new AgentPaymentDetail();
    paymentBatchDetail.setMerchantId("1000200912180001");
    paymentBatchDetail.setAccountName("name");
    paymentBatchDetail.setAccountNo("no");
    paymentBatchDetail.setAmount(10000L);
    paymentBatchDetail.setFee(888l);
    resultList.add(paymentBatchDetail);
    AgentPaymentDetail paymentBatchDetail1 = new AgentPaymentDetail();
    paymentBatchDetail.setMerchantId("1000200912180002");
    paymentBatchDetail1.setAccountName("name2");
    paymentBatchDetail1.setAccountNo("no2");
    paymentBatchDetail1.setAmount(8898l);
    paymentBatchDetail1.setFee(888l);
    resultList.add(paymentBatchDetail1);
    model.put("resultList", resultList);
    Writer writer = null;
    FileWriter fw = null;
    try {
        writer = new CharArrayWriter();
        Template template = getTemplate(templateFile);
        template.process(model, writer);
        writer.flush();
        File file = new File(fileName);
        file.delete();
        OutputStream os = new FileOutputStream(file);
        FileUtil.save(os, writer.toString().getBytes("utf-8"));
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (null != writer) {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != fw) {
            try {
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Example 98
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 99
Project: smack-xmpp-master  File: FileTransferTest.java View source code
public void testFileTransfer() throws Exception {
    final byte[] testTransfer = "This is a test transfer".getBytes();
    final SynchronousQueue<byte[]> queue = new SynchronousQueue<byte[]>();
    FileTransferManager manager1 = new FileTransferManager(getConnection(0));
    manager1.addFileTransferListener(new FileTransferListener() {

        public void fileTransferRequest(final FileTransferRequest request) {
            new Thread(new Runnable() {

                public void run() {
                    IncomingFileTransfer transfer = request.accept();
                    InputStream stream;
                    try {
                        stream = transfer.recieveFile();
                    } catch (XMPPException e) {
                        exception = e;
                        return;
                    }
                    byte[] testRecieve = new byte[testTransfer.length];
                    int receiveCount = 0;
                    try {
                        while (receiveCount != -1) {
                            receiveCount = stream.read(testRecieve);
                        }
                    } catch (IOException e) {
                        exception = e;
                    } finally {
                        try {
                            stream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        queue.put(testRecieve);
                    } catch (InterruptedException e) {
                        exception = e;
                    }
                }
            }).start();
        }
    });
    // Send the file from user1 to user0
    FileTransferManager manager2 = new FileTransferManager(getConnection(1));
    OutgoingFileTransfer outgoing = manager2.createOutgoingFileTransfer(getFullJID(0));
    OutputStream stream = outgoing.sendFile("test.txt", testTransfer.length, "The great work of robin hood");
    stream.write(testTransfer);
    stream.flush();
    stream.close();
    if (exception != null) {
        exception.printStackTrace();
        fail();
    }
    byte[] array = queue.take();
    assertEquals("Recieved file not equal to sent file.", testTransfer, array);
}
Example 100
Project: kabeja-master  File: DXFGenerator.java View source code
/*
	 * (non-Javadoc)
	 * 
	 * @see org.kabeja.io.Generator#generate(org.kabeja.dxf.DXFDocument,
	 * java.io.OutputStream)
	 */
public void generate(DraftDocument doc, Map<String, Object> context, OutputStream out) throws GenerationException {
    String profileName = null;
    if (context.containsKey(DXFGenerationContext.ATTRIBUTE_PROFILE)) {
        profileName = context.get(DXFGenerationContext.ATTRIBUTE_PROFILE).toString();
    } else if (this.generationContext.hasAttribute(DXFGenerationContext.ATTRIBUTE_DEFAULT_PROFILE)) {
        profileName = this.generationContext.getAttribute(DXFGenerationContext.ATTRIBUTE_DEFAULT_PROFILE).toString();
    }
    if (this.generationContext.getDXFGeneratorManager().hasDXFProfile(profileName)) {
        DXFProfile profile = this.generationContext.getDXFGeneratorManager().getDXFProfile(profileName);
        BufferedOutputStream buffered = new BufferedOutputStream(out);
        if (!this.generationContext.hasAttribute(DXFGenerationConstants.DEFAULT_TEXT_HEIGHT)) {
            this.generationContext.addAttribute(DXFGenerationConstants.DEFAULT_TEXT_HEIGHT, "1.0");
        }
        DXFOutput output = null;
        if (this.generationContext.hasAttribute(DXFGenerationConstants.DXF_ENCODING)) {
            output = new DXFOutput(buffered, this.generationContext.getAttribute(DXFGenerationConstants.DXF_ENCODING).toString());
        } else {
            output = new DXFOutput(buffered, DXFGenerationConstants.DEFAULT_ENCODING);
        }
        this.outputSection(Constants.SECTION_HEADER, profile, output, doc);
        this.outputSection(Constants.SECTION_CLASSES, profile, output, doc);
        this.outputSection(Constants.SECTION_TABLES, profile, output, doc);
        this.outputSection(Constants.SECTION_BLOCKS, profile, output, doc);
        this.outputSection(Constants.SECTION_ENTITIES, profile, output, doc);
        this.outputSection(Constants.SECTION_OBJECTS, profile, output, doc);
        this.outputSection(Constants.SECTION_THUMBNAILIMAGE, profile, output, doc);
        output.output(0, "EOF");
        try {
            buffered.flush();
            buffered.close();
        } catch (IOException e) {
            throw new GenerationException("Could not close stream.", e);
        }
    } else {
        throw new GenerationException("No DXF-Profile defined or not found, you have to configure a DXF-Profile.");
    }
}
Example 101
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;
}