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:it.jnrpe.net.JNRPEProtocolPacket.java

/**
 * Converts the packet object to its byte array representation.
 * /* w  ww . j av  a  2 s . co m*/
        
 * @return The byte array representation of this packet. */
public byte[] toByteArray() {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(bout);

    try {
        dout.writeShort(packetVersion);
        dout.writeShort(packetTypeCode);
        dout.writeInt(crcValue);
        dout.writeShort(resultCode);
        dout.write(byteBufferAry);
        dout.write(dummyBytesAry);

        dout.close();
    } catch (IOException e) {
        // Never happens...
        throw new IllegalStateException(e.getMessage(), e);
    }
    return bout.toByteArray();
}

From source file:com.mbrlabs.mundus.assets.EditorAssetManager.java

public void saveTerrainAssets() throws IOException {
    for (TerrainAsset terrain : getTerrainAssets()) {

        // save .terra file
        DataOutputStream outputStream = new DataOutputStream(
                new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(terrain.getFile().file()))));
        for (float f : terrain.getData()) {
            outputStream.writeFloat(f);//from  www . j  a va  2  s  .  com
        }
        outputStream.flush();
        outputStream.close();

        // save splatmap
        PixmapTextureAsset splatmap = terrain.getSplatmap();
        if (splatmap != null) {
            PixmapIO.writePNG(splatmap.getFile(), splatmap.getPixmap());
        }

        // save meta file
        terrain.getMeta().save();
    }
}

From source file:it.jnrpe.net.JNRPEProtocolPacket.java

/**
 * Validates the packet CRC./*w ww  .ja v a  2  s  . c  om*/
 * 
 * @throws BadCRCException
 *             If the CRC can't be validated 
 */
public void validate() throws BadCRCException {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(bout);

    try {
        dout.writeShort(packetVersion);
        dout.writeShort(packetTypeCode);
        dout.writeInt(0); // NO CRC
        dout.writeShort(resultCode);
        dout.write(byteBufferAry);
        dout.write(dummyBytesAry);

        dout.close();

        byte[] vBytes = bout.toByteArray();

        CRC32 crcAlg = new CRC32();
        crcAlg.update(vBytes);

        if (!(((int) crcAlg.getValue()) == crcValue)) {
            throw new BadCRCException("Bad CRC");
        }
    } catch (IOException e) {
        // Never happens...
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:Bookmark.java

protected void javaToNative(Object object, TransferData transferData) {
    if (object == null || !(object instanceof Bookmark))
        return;/*from   ww w.ja  va 2 s .  c  om*/

    Bookmark bookmark = (Bookmark) object;

    if (isSupportedType(transferData)) {
        try {
            // Writes data to a byte array.
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            DataOutputStream out = new DataOutputStream(stream);
            out.writeUTF(bookmark.name);
            out.writeUTF(bookmark.href);
            out.writeUTF(bookmark.addDate);
            out.writeUTF(bookmark.lastVisited);
            out.writeUTF(bookmark.lastModified);
            out.close();

            super.javaToNative(stream.toByteArray(), transferData);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.wavemaker.runtime.service.WaveMakerService.java

public String remoteRESTCall(String remoteURL, String params, String method, String contentType) {
    proxyCheck(remoteURL);/*from  ww w . j ava 2s .  co  m*/
    String charset = "UTF-8";
    StringBuffer returnString = new StringBuffer();
    try {
        if (method.toLowerCase().equals("put") || method.toLowerCase().equals("post") || params == null
                || params.equals("")) {
        } else {
            if (remoteURL.indexOf("?") != -1) {
                remoteURL += "&" + params;
            } else {
                remoteURL += "?" + params;
            }
        }

        URL url = new URL(remoteURL);
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Opening URL: " + url);
        }
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod(method);
        connection.setDoInput(true);
        connection.setRequestProperty("Accept-Charset", "application/json");
        connection.setRequestProperty("Accept-Encoding", "text/plain");
        connection.setRequestProperty("Content-Language", charset);
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Transfer-Encoding", "identity");
        connection.setUseCaches(false);

        HttpServletRequest request = RuntimeAccess.getInstance().getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            Enumeration<String> headers = request.getHeaders(name);
            if (headers != null && !name.toLowerCase().equals("accept-encoding")
                    && !name.toLowerCase().equals("accept-charset")
                    && !name.toLowerCase().equals("content-type")) {
                while (headers.hasMoreElements()) {
                    String headerValue = headers.nextElement();
                    connection.setRequestProperty(name, headerValue);
                    if (this.logger.isDebugEnabled()) {
                        this.logger.debug("HEADER: " + name + ": " + headerValue);
                    }
                }
            }
        }

        // Re-wrap single quotes into double quotes
        String finalParams;
        if (contentType.toLowerCase().equals("application/json")) {
            finalParams = params.replace("\'", "\"");
            if (!method.toLowerCase().equals("post") && !method.toLowerCase().equals("put") && method != null
                    && !method.equals("")) {
                URLEncoder.encode(finalParams, charset);
            }
        } else {
            finalParams = params;
        }

        connection.setRequestProperty("Content-Length", "" + Integer.toString(finalParams.getBytes().length));

        // set payload
        if (method.toLowerCase().equals("post") || method.toLowerCase().equals("put") || method == null
                || method.equals("")) {
            DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
            writer.writeBytes(finalParams);
            writer.flush();
            writer.close();
        }

        InputStream response = connection.getInputStream();
        BufferedReader reader = null;
        int responseLen = 0;
        try {
            int i = 0;
            String field;
            HttpServletResponse wmResponse = RuntimeAccess.getInstance().getResponse();
            while ((field = connection.getHeaderField(i)) != null) {
                String key = connection.getHeaderFieldKey(i);
                if (key == null || field == null) {
                } else {
                    if (key.toLowerCase().equals("proxy-connection") || key.toLowerCase().equals("expires")) {
                        logger.debug("Remote server returned header of: " + key + " " + field
                                + " it was not forwarded");
                    } else if (key.toLowerCase().equals("transfer-encoding")
                            && field.toLowerCase().equals("chunked")) {
                        logger.debug("Remote server returned header of: " + key + " " + field
                                + " it was not forwarded");
                    } else if (key.toLowerCase().equals("content-length")) {
                        // do NOT use this length as return header value
                        responseLen = new Integer(field);
                    } else {
                        wmResponse.addHeader(key, field);
                    }
                }
                i++;
            }
            reader = new BufferedReader(new InputStreamReader(response, charset));
            for (String line; (line = reader.readLine()) != null;) {
                returnString.append(line);
            }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                }
            }
        }
        connection.disconnect();
        return returnString.toString();
    } catch (Exception e) {
        logger.error("ERROR in XHR proxy call: " + e.getMessage());
        throw new WMRuntimeException(e);
    }
}

From source file:com.skcraft.launcher.util.HttpRequest.java

/**
 * Execute the request./*from w w w . ja va  2 s  .  c  o m*/
 * <p/>
 * After execution, {@link #close()} should be called.
 *
 * @return this object
 * @throws java.io.IOException on I/O error
 */
public HttpRequest execute() throws IOException {
    boolean successful = false;

    try {
        if (conn != null) {
            throw new IllegalArgumentException("Connection already executed");
        }

        conn = (HttpURLConnection) reformat(url).openConnection();
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Java) SKMCLauncher");

        if (body != null) {
            conn.setRequestProperty("Content-Type", contentType);
            conn.setRequestProperty("Content-Length", Integer.toString(body.length));
            conn.setDoInput(true);
        }

        for (Map.Entry<String, String> entry : headers.entrySet()) {
            conn.setRequestProperty(entry.getKey(), entry.getValue());
        }

        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setDoOutput(true);
        conn.setReadTimeout(READ_TIMEOUT);

        conn.connect();

        if (body != null) {
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            out.write(body);
            out.flush();
            out.close();
        }

        inputStream = conn.getResponseCode() == HttpURLConnection.HTTP_OK ? conn.getInputStream()
                : conn.getErrorStream();

        successful = true;
    } finally {
        if (!successful) {
            close();
        }
    }

    return this;
}

From source file:com.sk89q.squirrelid.util.HttpRequest.java

/**
 * Execute the request./*from  w w  w.  ja va2s . c om*/
 * <p/>
 * After execution, {@link #close()} should be called.
 *
 * @return this object
 * @throws java.io.IOException on I/O error
 */
public HttpRequest execute() throws IOException {
    boolean successful = false;

    try {
        if (conn != null) {
            throw new IllegalArgumentException("Connection already executed");
        }

        conn = (HttpURLConnection) reformat(url).openConnection();

        if (body != null) {
            conn.setRequestProperty("Content-Type", contentType);
            conn.setRequestProperty("Content-Length", Integer.toString(body.length));
            conn.setDoInput(true);
        }

        for (Map.Entry<String, String> entry : headers.entrySet()) {
            conn.setRequestProperty(entry.getKey(), entry.getValue());
        }

        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setDoOutput(true);
        conn.setReadTimeout(READ_TIMEOUT);

        conn.connect();

        if (body != null) {
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            out.write(body);
            out.flush();
            out.close();
        }

        inputStream = conn.getResponseCode() == HttpURLConnection.HTTP_OK ? conn.getInputStream()
                : conn.getErrorStream();

        successful = true;
    } finally {
        if (!successful) {
            close();
        }
    }

    return this;
}

From source file:it.greenvulcano.gvesb.virtual.rest.RestCallOperation.java

@Override
public GVBuffer perform(GVBuffer gvBuffer) throws ConnectionException, CallException, InvalidDataException {

    try {//  w  ww  .j  a v  a  2s .c o m
        final GVBufferPropertyFormatter formatter = new GVBufferPropertyFormatter(gvBuffer);

        String expandedUrl = formatter.format(url);
        String querystring = "";

        if (!params.isEmpty()) {

            querystring = params.entrySet().stream().map(
                    e -> formatter.formatAndEncode(e.getKey()) + "=" + formatter.formatAndEncode(e.getValue()))
                    .collect(Collectors.joining("&"));

            expandedUrl = expandedUrl.concat("?").concat(querystring);
        }

        StringBuffer callDump = new StringBuffer();
        callDump.append("Performing RestCallOperation " + name).append("\n        ").append("URL: ")
                .append(expandedUrl);

        URL requestUrl = new URL(expandedUrl);

        HttpURLConnection httpURLConnection;
        if (truststorePath != null && expandedUrl.startsWith("https://")) {
            httpURLConnection = openSecureConnection(requestUrl);
        } else {
            httpURLConnection = (HttpURLConnection) requestUrl.openConnection();
        }
        callDump.append("\n        ").append("Method: " + method);

        callDump.append("\n        ").append("Connection timeout: " + connectionTimeout);
        callDump.append("\n        ").append("Read timeout: " + readTimeout);

        httpURLConnection.setRequestMethod(method);
        httpURLConnection.setConnectTimeout(connectionTimeout);
        httpURLConnection.setReadTimeout(readTimeout);

        for (Entry<String, String> header : headers.entrySet()) {
            String k = formatter.format(header.getKey());
            String v = formatter.format(header.getValue());
            httpURLConnection.setRequestProperty(k, v);
            callDump.append("\n        ").append("Header: " + k + "=" + v);
            if ("content-type".equalsIgnoreCase(k) && "application/x-www-form-urlencoded".equalsIgnoreCase(v)) {
                body = querystring;
            }

        }

        if (sendGVBufferObject && gvBuffer.getObject() != null) {
            byte[] requestData;
            if (gvBuffer.getObject() instanceof byte[]) {
                requestData = (byte[]) gvBuffer.getObject();
            } else {
                requestData = gvBuffer.getObject().toString().getBytes();

            }
            httpURLConnection.setRequestProperty("Content-Length", Integer.toString(requestData.length));
            callDump.append("\n        ").append("Content-Length: " + requestData.length);
            callDump.append("\n        ").append("Request body: binary");
            logger.debug(callDump.toString());

            httpURLConnection.setDoOutput(true);

            DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            dataOutputStream.write(requestData);

            dataOutputStream.flush();
            dataOutputStream.close();

        } else if (Objects.nonNull(body) && body.length() > 0) {

            String expandedBody = formatter.format(body);
            callDump.append("\n        ").append("Request body: " + expandedBody);
            logger.debug(callDump.toString());

            httpURLConnection.setDoOutput(true);

            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream());
            outputStreamWriter.write(expandedBody);
            outputStreamWriter.flush();
            outputStreamWriter.close();

        }

        httpURLConnection.connect();

        InputStream responseStream = null;

        try {
            httpURLConnection.getResponseCode();
            responseStream = httpURLConnection.getInputStream();
        } catch (IOException connectionFail) {
            responseStream = httpURLConnection.getErrorStream();
        }

        for (Entry<String, List<String>> header : httpURLConnection.getHeaderFields().entrySet()) {
            if (Objects.nonNull(header.getKey()) && Objects.nonNull(header.getValue())) {
                gvBuffer.setProperty(RESPONSE_HEADER_PREFIX.concat(header.getKey().toUpperCase()),
                        header.getValue().stream().collect(Collectors.joining(";")));
            }
        }

        if (responseStream != null) {

            byte[] responseData = IOUtils.toByteArray(responseStream);
            String responseContentType = Optional
                    .ofNullable(gvBuffer.getProperty(RESPONSE_HEADER_PREFIX.concat("CONTENT-TYPE"))).orElse("");

            if (responseContentType.startsWith("application/json")
                    || responseContentType.startsWith("application/javascript")) {
                gvBuffer.setObject(new String(responseData, "UTF-8"));
            } else {
                gvBuffer.setObject(responseData);
            }

        } else { // No content
            gvBuffer.setObject(null);
        }

        gvBuffer.setProperty(RESPONSE_STATUS, String.valueOf(httpURLConnection.getResponseCode()));
        gvBuffer.setProperty(RESPONSE_MESSAGE,
                Optional.ofNullable(httpURLConnection.getResponseMessage()).orElse("NULL"));

        httpURLConnection.disconnect();

    } catch (Exception exc) {
        throw new CallException("GV_CALL_SERVICE_ERROR",
                new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() },
                        { "tid", gvBuffer.getId().toString() }, { "message", exc.getMessage() } },
                exc);
    }
    return gvBuffer;
}

From source file:WriteReadMixedDataTypesExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);//ww  w  . j a  v  a2s . com
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
        } catch (Exception error) {
            alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            byte[] outputRecord;
            String outputString = "First Record";
            int outputInteger = 15;
            boolean outputBoolean = true;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            outputDataStream.writeUTF(outputString);
            outputDataStream.writeBoolean(outputBoolean);
            outputDataStream.writeInt(outputInteger);
            outputDataStream.flush();
            outputRecord = outputStream.toByteArray();
            recordstore.addRecord(outputRecord, 0, outputRecord.length);
            outputStream.reset();
            outputStream.close();
            outputDataStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            String inputString = null;
            int inputInteger = 0;
            boolean inputBoolean = false;
            byte[] byteInputData = new byte[100];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            for (int x = 1; x <= recordstore.getNumRecords(); x++) {
                recordstore.getRecord(x, byteInputData, 0);
                inputString = inputDataStream.readUTF();
                inputBoolean = inputDataStream.readBoolean();
                inputInteger = inputDataStream.readInt();
                inputStream.reset();
            }
            inputStream.close();
            inputDataStream.close();
            alert = new Alert("Reading", inputString + " " + inputInteger + " " + inputBoolean, null,
                    AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        } catch (Exception error) {
            alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            recordstore.closeRecordStore();
        } catch (Exception error) {
            alert = new Alert("Error Closing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        if (RecordStore.listRecordStores() != null) {
            try {
                RecordStore.deleteRecordStore("myRecordStore");
            } catch (Exception error) {
                alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
        }
    }
}