Example usage for java.io DataOutputStream close

List of usage examples for java.io DataOutputStream close

Introduction

In this page you can find the example usage for java.io DataOutputStream close.

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with the stream.

Usage

From source file:com.panet.imeta.trans.steps.blockingstep.BlockingStep.java

private boolean addBuffer(RowMetaInterface rowMeta, Object[] r) {
    if (r != null) {
        data.buffer.add(r); // Save row
    }/*  w  w  w. jav a2  s. c  o m*/

    // Time to write to disk: buffer in core is full!
    if (data.buffer.size() == meta.getCacheSize() // Buffer is full: dump to disk 
            || (data.files.size() > 0 && r == null && data.buffer.size() > 0) // No more records: join from disk 
    ) {
        // Then write them to disk...
        DataOutputStream dos;
        GZIPOutputStream gzos;
        int p;

        try {
            FileObject fileObject = KettleVFS.createTempFile(meta.getPrefix(), ".tmp",
                    environmentSubstitute(meta.getDirectory()));

            data.files.add(fileObject); // Remember the files!
            OutputStream outputStream = KettleVFS.getOutputStream(fileObject, false);
            if (meta.getCompress()) {
                gzos = new GZIPOutputStream(new BufferedOutputStream(outputStream));
                dos = new DataOutputStream(gzos);
            } else {
                dos = new DataOutputStream(outputStream);
                gzos = null;
            }

            // How many records do we have?
            dos.writeInt(data.buffer.size());

            for (p = 0; p < data.buffer.size(); p++) {
                // Just write the data, nothing else
                rowMeta.writeData(dos, (Object[]) data.buffer.get(p));
            }
            // Close temp-file
            dos.close(); // close data stream
            if (gzos != null) {
                gzos.close(); // close gzip stream
            }
            outputStream.close(); // close file stream
        } catch (Exception e) {
            logError("Error processing tmp-file: " + e.toString());
            return false;
        }

        data.buffer.clear();
    }

    return true;
}

From source file:net.mohatu.bloocoin.miner.SubmitList.java

private void submit() {
    for (int i = 0; i < solved.size(); i++) {
        try {/*from   w  w w  .  j a  v a2  s  .  c  o  m*/
            Socket sock = new Socket(this.url, this.port);
            String result = new String();
            DataInputStream is = new DataInputStream(sock.getInputStream());
            DataOutputStream os = null;
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            solution = solved.get(i);
            hash = DigestUtils.sha512Hex(solution);

            String command = "{\"cmd\":\"check" + "\",\"winning_string\":\"" + solution
                    + "\",\"winning_hash\":\"" + hash + "\",\"addr\":\"" + Main.getAddr() + "\"}";
            os = new DataOutputStream(sock.getOutputStream());
            os.write(command.getBytes());

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                result += inputLine;
            }

            if (result.contains("\"success\": true")) {
                System.out.println("Result: Submitted");
                Main.updateStatusText(solution + " submitted", Color.blue);
                Thread gc = new Thread(new Coins());
                gc.start();
            } else if (result.contains("\"success\": false")) {
                System.out.println("Result: Failed");
                Main.updateStatusText("Submission of " + solution + " failed, already exists!", Color.red);
            }
            is.close();
            os.close();
            os.flush();
            sock.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            Main.updateStatusText("Submission of " + solution + " failed, connection failed!", Color.red);
        } catch (IOException e) {
            e.printStackTrace();
            Main.updateStatusText("Submission of " + solution + " failed, connection failed!", Color.red);
        }
    }
    Thread gc = new Thread(new Coins());
    gc.start();
}

From source file:br.com.anteros.android.synchronism.communication.HttpConnectionClient.java

public MobileResponse sendReceiveData(MobileRequest mobileRequest) {
    sessionId = HttpConnectionSession.getInstance().getSessionId();

    add(mobileRequest.getFormattedHeader(), mobileRequest.getFormatedActions());
    MobileResponse mobileResponse = new MobileResponse();
    try {/*from  w  ww  .java2s .c o m*/
        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onWaitServer();
        }

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onStatusConnectionServer("Conectando Servidor...");
        }

        /*
         * Define url e estabelece conexo
         */

        HttpPost httpPost = new HttpPost(url);

        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is
        // established.
        // The default value is zero, that means the timeout is not used.
        HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT_CONNECTION);
        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUT_SOCKET);

        if (httpClient == null)
            httpClient = new DefaultHttpClient(httpParameters);

        //

        /*
         * Setar o cookie da sesso
         */
        if ((sessionId != null) && (!"".equals(sessionId))) {
            httpPost.setHeader("Cookie", "JSESSIONID=" + sessionId);
        }
        httpPost.setHeader("User-Agent", "Android");
        httpPost.setHeader("Accept-Encoding", "gzip");

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onStatusConnectionServer("Enviando requisio...");
        }

        //
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream(baos);
        //

        /*
         * Escrever no output
         */
        out.writeInt(numOption);
        String aux[];
        for (int i = 0; i < opPOST.size(); i++) {
            aux = (String[]) opPOST.get(i);

            out.writeUTF(aux[0]);

            byte[] b = aux[1].getBytes();
            out.writeInt(b.length);
            out.write(b);

            aux = null;
        }
        out.flush();

        ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray());
        entity.setContentEncoding("UTF-8");
        httpPost.setEntity(entity);
        httpPost.addHeader("Connection", "Keep-Alive");
        httpPost.addHeader("Keep-Alive", "timeout=120000");

        out.close();
        //

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onStatusConnectionServer("Recebendo dados...");
        }

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onDebugMessage("Recebendo dados conexo");
        }

        /*
         * Aguardar resposta
         */
        HttpResponse httpResponse = httpClient.execute(httpPost);
        List result = null;
        StatusLine statusLine = httpResponse.getStatusLine();
        int code = statusLine.getStatusCode();
        if (code != 200) {
            String msg = "Erro RECEBENDO resposta do Servidor " + url + " - Cdigo do Erro HTTP " + code + "-"
                    + statusLine.getReasonPhrase();
            mobileResponse.setStatus(msg);
        } else {
            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onStatusConnectionServer("Resposta OK !");
            }

            /*
             * Ler cookie
             */
            String tmpSessionId = null;

            for (Cookie c : httpClient.getCookieStore().getCookies()) {
                if ("JSESSIONID".equals(c.getName())) {
                    tmpSessionId = c.getValue();
                }
            }

            if (tmpSessionId != null) {
                sessionId = tmpSessionId;
                HttpConnectionSession.getInstance().setSessionId(sessionId);
            }
            //

            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onStatusConnectionServer("Lendo dados...");
            }

            /*
             * Le os dados
             */
            HttpEntity entityResponse = httpResponse.getEntity();
            InputStream in = AndroidHttpClient.getUngzippedContent(entityResponse);

            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));

            String content = null;

            content = reader.readLine();
            String line = null;
            while ((line = reader.readLine()) != null) {
                content += line;
            }
            line = "";

            reader.close();
            reader = null;
            in.close();
            in = null;
            entityResponse.consumeContent();
            entityResponse = null;
            //

            StringTokenizer messagePart = new StringTokenizer(content, "#");
            content = null;

            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onDebugMessage("RECEBEU dados conexo");
            }

            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onStatusConnectionServer("Processando resposta... ");
            }

            if (this.getSendData() != null) {
                for (MobileSendDataListener listener : this.getSendData().getListeners())
                    listener.onDebugMessage("Converteu string dados conexo");
            }

            while (messagePart.hasMoreTokens()) {
                String resultData = messagePart.nextToken();
                resultData = resultData.substring(resultData.indexOf("*") + 1, resultData.length());
                if (result == null)
                    result = formatData(resultData);
                else
                    result.addAll(formatData(resultData));
            }
            messagePart = null;
        }

        if (result != null) {
            mobileResponse.setFormattedParameters(result);
            result.clear();
            result = null;
        }

        if (this.getSendData() != null) {
            for (MobileSendDataListener listener : this.getSendData().getListeners())
                listener.onEndServer();
        }

    } catch (SocketTimeoutException exTimeout) {
        exTimeout.printStackTrace();
        wrapException(mobileResponse, "No foi possvel CONECTAR ao Servidor " + url
                + ". Verifique sua conexo e se o servidor est em funcionamento.");
    } catch (Exception e) {
        e.printStackTrace();
        if ((e.getMessage() + "").contains("unreachable"))
            wrapException(mobileResponse,
                    "Voc est sem acesso a internet. Verifique sua conexo. No foi possvel conectar ao servidor  "
                            + url);
        else
            wrapException(mobileResponse,
                    "No foi possivel CONECTAR ao Servidor " + url + " " + e.getMessage());
    }
    return mobileResponse;
}

From source file:com.ibm.bi.dml.test.utils.TestUtils.java

public static void writeTestScalar(String file, double value) {
    try {/*w w w. j a  v a 2 s  .co m*/
        DataOutputStream out = new DataOutputStream(new FileOutputStream(file));
        PrintWriter pw = new PrintWriter(out);
        pw.println(value);
        pw.close();
        out.close();
    } catch (IOException e) {
        fail("unable to write test scalar (" + file + "): " + e.getMessage());
    }
}

From source file:com.qumasoft.qvcslib.CompareFilesWithApacheDiff.java

protected void writeEditScript(Revision apacheRevision, CompareLineInfo[] fileA, CompareLineInfo[] fileB)
        throws QVCSOperationException {
    DataOutputStream outStream = null;
    try {//from w w  w .j  av  a  2 s. c om
        outStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));

        // Write the header
        CompareFilesEditHeader editHeader = new CompareFilesEditHeader();
        editHeader.setBaseFileSize(new Common32Long((int) inFileA.length()));
        editHeader.setTimeOfTarget(new CommonTime());
        editHeader.write(outStream);

        int count = apacheRevision.size();
        for (int index = 0; index < count; index++) {
            Delta delta = apacheRevision.getDelta(index);
            formatEditScript(delta, outStream, fileA);
        }
    } catch (IOException e) {
        throw new QVCSOperationException("IO Exception in writeEditScript() " + e.getLocalizedMessage());
    } finally {
        if (outStream != null) {
            try {
                outStream.close();
            } catch (IOException ex) {
                Logger.getLogger(CompareFilesWithApacheDiff.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:net.sf.gazpachoquest.rest.auth.TokenStore.java

/**
 * Stores the current set of tokens to the token file
 *//*w w w .  jav a2  s . com*/
private void saveTokens() {
    FileOutputStream fout = null;
    DataOutputStream keyOutputStream = null;
    try {
        File parent = tokenFile.getAbsoluteFile().getParentFile();
        log.info("Token File {} parent {} ", tokenFile, parent);
        if (!parent.exists()) {
            parent.mkdirs();
        }
        fout = new FileOutputStream(tmpTokenFile);
        keyOutputStream = new DataOutputStream(fout);
        keyOutputStream.writeInt(currentToken);
        keyOutputStream.writeLong(nextUpdate);
        for (int i = 0; i < currentTokens.length; i++) {
            if (currentTokens[i] == null) {
                keyOutputStream.writeInt(0);
            } else {
                keyOutputStream.writeInt(1);
                byte[] b = currentTokens[i].getEncoded();
                keyOutputStream.writeInt(b.length);
                keyOutputStream.write(b);
            }
        }
        keyOutputStream.close();
        tmpTokenFile.renameTo(tokenFile);
    } catch (IOException e) {
        log.error("Failed to save cookie keys " + e.getMessage());
    } finally {
        try {
            keyOutputStream.close();
        } catch (Exception e) {
        }
        try {
            fout.close();
        } catch (Exception e) {
        }

    }
}

From source file:com.project.qrypto.keymanagement.KeyManager.java

/**
 * Saves the Keystore. Uses either internal or external memory depending on settings.
 * @param context the context to use//w ww. j  a va  2 s. c o  m
 * 
 * @throws IOException if the outstream is somehow bad or interrupted
 * @throws InvalidCipherTextException if the key is bad or the data is bad
 */
public void commit(Context context) throws IOException, InvalidCipherTextException {
    //Commit Preferences
    Editor edit = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE).edit();
    edit.putBoolean(USE_INTERNAL_STORAGE, internalStorage);
    edit.putBoolean(PASSWORD_PROTECTED, passwordProtected);
    edit.putBoolean(SETUP_COMPLETE, true);
    edit.commit();

    //Commit Key Data
    DataOutputStream writer = null;
    ByteArrayOutputStream output = null;

    //Create the proper streams
    if (passwordProtected) {
        output = new ByteArrayOutputStream();
        writer = new DataOutputStream(output);
    } else {
        writer = new DataOutputStream(getAssociatedOutFileStream(context));
    }

    //Write everything out to the stream
    writer.writeUTF("RCYTHR1"); //Special indicator to determine if we decrypt properly
    writer.writeInt(lookup.size());
    for (Entry<String, Key> entry : lookup.entrySet()) {
        writer.writeUTF(entry.getKey());
        entry.getValue().writeData(writer);
    }
    writer.writeByte(1); //Prevent null padding from causing too much truncation.

    writer.flush();

    //If we're password protecting we still need to encrypt and output to file
    if (passwordProtected) {
        OutputStream finalOut = getAssociatedOutFileStream(context);
        finalOut.write(AES.handle(true, output.toByteArray(), keyStoreKey));
        finalOut.close();
    }

    writer.close();
}

From source file:com.intel.xdk.device.Device.java

public void getRemoteData(String requestUrl, String requestMethod, String requestBody,
        CallbackContext callbackContext) {
    try {/*w  w w.  j ava 2s . c  o  m*/
        URL url = new URL(requestUrl);
        connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        connection.setRequestMethod(requestMethod);

        //Write requestBody
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(requestBody);
        outputStream.flush();
        outputStream.close();

        //Get response code and response message
        int responseCode = connection.getResponseCode();
        String responseMessage = connection.getResponseMessage();

        //Get response Message
        DataInputStream inputStream = new DataInputStream(connection.getInputStream());
        if (responseCode == 200) {
            String temp;
            String responseBody = "";
            while ((temp = inputStream.readLine()) != null) {
                responseBody += temp;
            }
            callbackContext.success(responseBody);
        } else {
            callbackContext.error("Fail to get the response, response code: " + responseCode
                    + ", response message: " + responseMessage);
        }

        inputStream.close();
    } catch (IOException e) {
        Log.d("request", e.getMessage());
    }
}

From source file:com.intel.xdk.device.Device.java

public void getRemoteData(String requestUrl, String requestMethod, String requestBody, String successCallback,
        String errorCallback) {/*from   ww w  .jav a  2s. com*/
    Log.d("getRemoteData", "url: " + requestUrl + ", method: " + requestMethod + ", body: " + requestBody);

    try {
        URL url = new URL(requestUrl);
        connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        connection.setRequestMethod(requestMethod);

        //Write requestBody
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(requestBody);
        outputStream.flush();
        outputStream.close();

        //Get response code and response message
        int responseCode = connection.getResponseCode();
        String responseMessage = connection.getResponseMessage();

        //Get response Message
        DataInputStream inputStream = new DataInputStream(connection.getInputStream());
        if (responseCode == 200) {
            String temp;
            String responseBody = "";
            while ((temp = inputStream.readLine()) != null) {
                responseBody += temp;
            }
            //callbackContext.success(responseBody);
            String js = "javascript:" + successCallback + "('" + responseBody + "');";
            injectJS(js);
        } else {
            //callbackContext.error("Fail to get the response, response code: " + responseCode + ", response message: " + responseMessage);
            String js = "javascript:" + errorCallback + "(" + "'response code :" + responseCode + "');";
            injectJS(js);
        }

        inputStream.close();
    } catch (IOException e) {
        Log.d("request", e.getMessage());
    }
}

From source file:com.envirover.spl.SPLGroungControlTest.java

@Test
public void testMTMessagePipeline() {
    System.out.println("MT TEST: Testing MT message pipeline...");

    Socket client = null;/*from   ww w.jav  a 2 s. co m*/
    DataOutputStream out = null;

    try {
        System.out.printf("MT TEST: Connecting to tcp://%s:%d", InetAddress.getLocalHost().getHostAddress(),
                config.getMAVLinkPort());
        System.out.println();

        client = new Socket(InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort());

        System.out.printf("MT TEST: Connected to tcp://%s:%d", InetAddress.getLocalHost().getHostAddress(),
                config.getMAVLinkPort());
        System.out.println();

        out = new DataOutputStream(client.getOutputStream());

        MAVLinkPacket packet = getSamplePacket();
        out.write(packet.encodePacket());
        out.flush();

        System.out.printf("MT TEST: MAVLink message sent: msgid = %d", packet.msgid);
        System.out.println();

        Thread.sleep(5000);

        System.out.println("MT TEST: Complete.");
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (out != null)
                out.close();

            if (client != null)
                client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}