Example usage for java.io DataOutputStream writeBytes

List of usage examples for java.io DataOutputStream writeBytes

Introduction

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

Prototype

public final void writeBytes(String s) throws IOException 

Source Link

Document

Writes out the string to the underlying output stream as a sequence of bytes.

Usage

From source file:com.wso2telco.dep.mediator.RequestExecutor.java

/**
 * Make delete request./*from ww w .j  a  va2  s .co  m*/
 *
 * @param operatorendpoint
 *            the operatorendpoint
 * @param url
 *            the url
 * @param requestStr
 *            the request str
 * @param auth
 *            the auth
 * @param messageContext
 *            the message context
 * @return the string
 */
public String makeDeleteRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth,
        MessageContext messageContext, boolean inclueHeaders) {

    int statusCode = 0;
    String retStr = "";
    URL neturl;
    HttpURLConnection connection = null;

    try {

        // String Authtoken = AccessToken;
        // //FileUtil.getApplicationProperty("wow.api.bearer.token");
        // DefaultHttpClient httpClient = new DefaultHttpClient();

        String encurl = (requestStr != null) ? url + requestStr : url;
        neturl = new URL(encurl);
        connection = (HttpURLConnection) neturl.openConnection();
        connection.setRequestMethod("DELETE");
        connection.setRequestProperty("Content-Type", "application/json");

        if (auth) {
            connection.setRequestProperty("Authorization",
                    "Bearer " + getAccessToken(operatorendpoint.getOperator(), messageContext));
            // Add JWT token header
            org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext)
                    .getAxis2MessageContext();
            Object headers = axis2MessageContext
                    .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
            if (headers != null && headers instanceof Map) {
                Map headersMap = (Map) headers;
                String jwtparam = (String) headersMap.get("x-jwt-assertion");
                if (jwtparam != null) {
                    connection.setRequestProperty("x-jwt-assertion", jwtparam);
                }
            }
        }

        if (inclueHeaders) {
            org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext)
                    .getAxis2MessageContext();
            Object headers = axis2MessageContext
                    .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
            if (headers != null && headers instanceof Map) {
                Map headersMap = (Map) headers;
                Iterator it = headersMap.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry entry = (Map.Entry) it.next();
                    connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); // avoids a
                    // ConcurrentModificationException
                }
            }
        }

        connection.setUseCaches(false);

        log.info("Southbound Request URL: " + connection.getRequestMethod() + " " + connection.getURL()
                + " Request ID: " + UID.getRequestID(messageContext));
        if (log.isDebugEnabled()) {
            log.debug("Southbound Request Headers: " + connection.getRequestProperties());
        }
        log.info("Southbound Request Body: " + requestStr + " Request ID: " + UID.getRequestID(messageContext));

        if (requestStr != null) {
            connection.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(requestStr);
            wr.flush();
            wr.close();
        }

        statusCode = connection.getResponseCode();
        log.info("response code: " + statusCode);

        if ((statusCode != 200) && (statusCode != 201) && (statusCode != 400) && (statusCode != 401)
                && (statusCode != 204)) {
            throw new RuntimeException("Failed : HTTP error code : " + statusCode);
        }

        InputStream is = null;
        if ((statusCode == 200) || (statusCode == 201) || (statusCode == 204)) {
            is = connection.getInputStream();
        } else {
            is = connection.getErrorStream();
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String output;
        while ((output = br.readLine()) != null) {
            retStr += output;
        }
        br.close();

        log.info("Southbound Response Status: " + statusCode + " " + connection.getResponseMessage()
                + " Request ID: " + UID.getRequestID(messageContext));
        if (log.isDebugEnabled()) {
            log.debug("Southbound Response Headers: " + connection.getHeaderFields());
        }
        log.info("Southbound Response Body: " + retStr + " Request ID: " + UID.getRequestID(messageContext));

    } catch (Exception e) {
        log.error("[WSRequestService ], makerequest, " + e.getMessage(), e);
        return null;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return retStr;
}

From source file:com.apptentive.android.sdk.comm.ApptentiveClient.java

private static ApptentiveHttpResponse performMultipartFilePost(Context context, String oauthToken, String uri,
        String postBody, StoredFile storedFile) {
    Log.d("Performing multipart request to %s", uri);

    ApptentiveHttpResponse ret = new ApptentiveHttpResponse();

    if (storedFile == null) {
        Log.e("StoredFile is null. Unable to send.");
        return ret;
    }//from   ww w.j a  v a  2s.  com

    int bytesRead;
    int bufferSize = 4096;
    byte[] buffer;

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = UUID.randomUUID().toString();

    HttpURLConnection connection;
    DataOutputStream os = null;
    InputStream is = null;

    try {
        is = context.openFileInput(storedFile.getLocalFilePath());

        // Set up the request.
        URL url = new URL(uri);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setConnectTimeout(DEFAULT_HTTP_CONNECT_TIMEOUT);
        connection.setReadTimeout(DEFAULT_HTTP_SOCKET_TIMEOUT);
        connection.setRequestMethod("POST");

        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        connection.setRequestProperty("Authorization", "OAuth " + oauthToken);
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("X-API-Version", API_VERSION);
        connection.setRequestProperty("User-Agent", getUserAgentString());

        StringBuilder requestText = new StringBuilder();

        // Write form data
        requestText.append(twoHyphens).append(boundary).append(lineEnd);
        requestText.append("Content-Disposition: form-data; name=\"message\"").append(lineEnd);
        requestText.append("Content-Type: text/plain").append(lineEnd);
        requestText.append(lineEnd);
        requestText.append(postBody);
        requestText.append(lineEnd);

        // Write file attributes.
        requestText.append(twoHyphens).append(boundary).append(lineEnd);
        requestText.append(String.format("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"",
                storedFile.getFileName())).append(lineEnd);
        requestText.append("Content-Type: ").append(storedFile.getMimeType()).append(lineEnd);
        requestText.append(lineEnd);

        Log.d("Post body: " + requestText);

        // Open an output stream.
        os = new DataOutputStream(connection.getOutputStream());

        // Write the text so far.
        os.writeBytes(requestText.toString());

        try {
            // Write the actual file.
            buffer = new byte[bufferSize];
            while ((bytesRead = is.read(buffer, 0, bufferSize)) > 0) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            Log.d("Error writing file bytes to HTTP connection.", e);
            ret.setBadPayload(true);
            throw e;
        }

        os.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        os.close();

        ret.setCode(connection.getResponseCode());
        ret.setReason(connection.getResponseMessage());

        // TODO: These streams may not be ready to read now. Put this in a new thread.
        // Read the normal response.
        InputStream nis = null;
        ByteArrayOutputStream nbaos = null;
        try {
            Log.d("Sending file: " + storedFile.getLocalFilePath());
            nis = connection.getInputStream();
            nbaos = new ByteArrayOutputStream();
            byte[] eBuf = new byte[1024];
            int eRead;
            while (nis != null && (eRead = nis.read(eBuf, 0, 1024)) > 0) {
                nbaos.write(eBuf, 0, eRead);
            }
            ret.setContent(nbaos.toString());
        } catch (IOException e) {
            Log.w("Can't read return stream.", e);
        } finally {
            Util.ensureClosed(nis);
            Util.ensureClosed(nbaos);
        }

        // Read the error response.
        InputStream eis = null;
        ByteArrayOutputStream ebaos = null;
        try {
            eis = connection.getErrorStream();
            ebaos = new ByteArrayOutputStream();
            byte[] eBuf = new byte[1024];
            int eRead;
            while (eis != null && (eRead = eis.read(eBuf, 0, 1024)) > 0) {
                ebaos.write(eBuf, 0, eRead);
            }
            if (ebaos.size() > 0) {
                ret.setContent(ebaos.toString());
            }
        } catch (IOException e) {
            Log.w("Can't read error stream.", e);
        } finally {
            Util.ensureClosed(eis);
            Util.ensureClosed(ebaos);
        }

        Log.d("HTTP " + connection.getResponseCode() + ": " + connection.getResponseMessage() + "");
        Log.v(ret.getContent());
    } catch (FileNotFoundException e) {
        Log.e("Error getting file to upload.", e);
    } catch (MalformedURLException e) {
        Log.e("Error constructing url for file upload.", e);
    } catch (SocketTimeoutException e) {
        Log.w("Timeout communicating with server.");
    } catch (IOException e) {
        Log.e("Error executing file upload.", e);
    } finally {
        Util.ensureClosed(is);
        Util.ensureClosed(os);
    }
    return ret;
}

From source file:git.egatuts.nxtremotecontroller.fragment.OnlineControllerFragment.java

public TokenRequester getTokenRequester() {
    final OnlineControllerFragment self = this;
    final TokenRequester requester = new TokenRequester();
    requester.setRunnable(new Runnable() {
        @Override//from   w  w  w  .j a  va  2 s.  c  o m
        public void run() {
            String url = self.getPreferencesEditor().getString("preference_server_login",
                    self.getString(R.string.preference_value_login));
            try {
                URL location = new URL(url);
                HttpsURLConnection s_connection = null;
                HttpURLConnection connection = null;
                InputStream input;
                int responseCode;
                boolean isHttps = url.contains("https");
                DataOutputStream writeStream;
                if (isHttps) {
                    s_connection = (HttpsURLConnection) location.openConnection();
                    s_connection.setRequestMethod("POST");
                    writeStream = new DataOutputStream(s_connection.getOutputStream());
                } else {
                    connection = (HttpURLConnection) location.openConnection();
                    connection.setRequestMethod("POST");
                    writeStream = new DataOutputStream(connection.getOutputStream());
                }
                StringBuilder urlParams = new StringBuilder();
                urlParams.append("name=").append(Build.MODEL).append("&email=").append(self.getOwnerEmail())
                        .append("&host=").append(true).append("&longitude=").append(self.longitude)
                        .append("&latitude=").append(self.latitude);
                writeStream.writeBytes(urlParams.toString());
                writeStream.flush();
                writeStream.close();
                if (isHttps) {
                    input = s_connection.getInputStream();
                    responseCode = s_connection.getResponseCode();
                } else {
                    input = connection.getInputStream();
                    responseCode = connection.getResponseCode();
                }
                if (input != null) {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input));
                    String line;
                    String result = "";
                    while ((line = bufferedReader.readLine()) != null) {
                        result += line;
                    }
                    input.close();
                    requester.finishRequest(result);
                }
            } catch (IOException e) {
                //e.printStackTrace();
                requester.cancelRequest(e);
            }
        }
    });
    return requester;
}

From source file:ffx.xray.parsers.MTZWriter.java

/**
 * <p>//from www . java2  s  .  com
 * write</p>
 */
public void write() {
    ByteOrder byteOrder = ByteOrder.nativeOrder();
    FileOutputStream fileOutputStream;
    DataOutputStream dataOutputStream;

    try {
        if (logger.isLoggable(Level.INFO)) {
            StringBuilder sb = new StringBuilder();
            sb.append(format("\n Writing MTZ HKL file: \"%s\"\n", fileName));
            logger.info(sb.toString());
        }

        fileOutputStream = new FileOutputStream(fileName);
        dataOutputStream = new DataOutputStream(fileOutputStream);

        byte bytes[] = new byte[80];
        int offset = 0;
        int writeLen = 0;

        int iMapData;
        float fMapData;

        // Header.
        StringBuilder sb = new StringBuilder();
        sb.append("MTZ ");
        dataOutputStream.writeBytes(sb.toString());

        // Header offset.
        int headerOffset = n * nCol + 21;
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
        byteBuffer.order(byteOrder).putInt(headerOffset);

        // Machine code: double, float, int, uchar
        // 0x4441 for LE, 0x1111 for BE
        if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
            iMapData = 0x4441;
        } else {
            iMapData = 0x1111;
        }
        byteBuffer.order(byteOrder).putInt(iMapData);
        dataOutputStream.write(bytes, offset, 8);

        sb = new StringBuilder();
        sb.append(" ");
        sb.setLength(68);
        dataOutputStream.writeBytes(sb.toString());

        // Data.
        Vector<String> colname = new Vector<>(nCol);
        char colType[] = new char[nCol];
        double res[] = new double[2];
        res[0] = Double.POSITIVE_INFINITY;
        res[1] = Double.NEGATIVE_INFINITY;
        float colMinMax[][] = new float[nCol][2];
        for (int i = 0; i < nCol; i++) {
            colMinMax[i][0] = Float.POSITIVE_INFINITY;
            colMinMax[i][1] = Float.NEGATIVE_INFINITY;
        }
        ReflectionSpline sigmaASpline = new ReflectionSpline(reflectionList, refinementData.sigmaa.length);
        int col = 0;

        colname.add("H");
        colType[col++] = 'H';
        colname.add("K");
        colType[col++] = 'H';
        colname.add("L");
        colType[col++] = 'H';
        writeLen += 12;

        if (mtzType != MTZType.FCONLY) {
            colname.add("FO");
            colType[col++] = 'F';
            colname.add("SIGFO");
            colType[col++] = 'Q';
            colname.add("FreeR");
            colType[col++] = 'I';
            writeLen += 12;
        }

        if (mtzType != MTZType.DATAONLY) {
            colname.add("Fs");
            colType[col++] = 'F';
            colname.add("PHIFs");
            colType[col++] = 'P';
            colname.add("Fc");
            colType[col++] = 'F';
            colname.add("PHIFc");
            colType[col++] = 'P';
            writeLen += 16;
        }

        if (mtzType == MTZType.ALL) {
            colname.add("FOM");
            colType[col++] = 'W';
            colname.add("PHIW");
            colType[col++] = 'P';
            colname.add("SigmaAs");
            colType[col++] = 'F';
            colname.add("SigmaAw");
            colType[col++] = 'Q';
            colname.add("FWT");
            colType[col++] = 'F';
            colname.add("PHWT");
            colType[col++] = 'P';
            colname.add("DELFWT");
            colType[col++] = 'F';
            colname.add("PHDELWT");
            colType[col++] = 'P';
            writeLen += 32;
        }

        for (HKL ih : reflectionList.hkllist) {
            col = 0;
            int i = ih.index();

            // Skip the 0 0 0 reflection.
            if (ih.h() == 0 && ih.k() == 0 && ih.l() == 0) {
                continue;
            }

            double ss = Crystal.invressq(crystal, ih);
            res[0] = min(ss, res[0]);
            res[1] = max(ss, res[1]);

            // HKL first (3)
            fMapData = ih.h();
            colMinMax[col][0] = min(fMapData, colMinMax[0][0]);
            colMinMax[col][1] = max(fMapData, colMinMax[0][1]);
            byteBuffer.rewind();
            byteBuffer.order(byteOrder).putFloat(fMapData);
            col++;

            fMapData = ih.k();
            colMinMax[col][0] = min(fMapData, colMinMax[1][0]);
            colMinMax[col][1] = max(fMapData, colMinMax[1][1]);
            byteBuffer.order(byteOrder).putFloat(fMapData);
            col++;

            fMapData = ih.l();
            colMinMax[col][0] = min(fMapData, colMinMax[2][0]);
            colMinMax[col][1] = max(fMapData, colMinMax[2][1]);
            byteBuffer.order(byteOrder).putFloat(fMapData);
            col++;

            if (mtzType != MTZType.FCONLY) {
                // F/sigF (2)
                fMapData = (float) refinementData.getF(i);
                if (!isNaN(fMapData)) {
                    colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                    colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                }
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
                fMapData = (float) refinementData.getSigF(i);
                if (!isNaN(fMapData)) {
                    colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                    colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                }
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;

                // Free R (1)
                fMapData = (float) refinementData.getFreeR(i);
                if (!isNaN(fMapData)) {
                    colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                    colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                }
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
            }

            if (mtzType == MTZType.FCONLY) {
                // Fs (2)
                fMapData = (float) refinementData.fsF(i);
                colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
                fMapData = (float) toDegrees(refinementData.fsPhi(i));
                colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;

                // Fc (unscaled!) (2)
                fMapData = (float) refinementData.fcF(i);
                if (!isNaN(fMapData)) {
                    colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                    colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                }
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
                fMapData = (float) Math.toDegrees(refinementData.fcPhi(i));
                if (!isNaN(fMapData)) {
                    colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                    colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                }
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
            }

            if (mtzType == MTZType.ALL) {
                // Fs (2)
                fMapData = (float) refinementData.fsF(i);
                colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
                fMapData = (float) toDegrees(refinementData.fsPhi(i));
                colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;

                // Fctot (2)
                fMapData = (float) refinementData.fcTotF(i);
                if (!isNaN(fMapData)) {
                    colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                    colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                }
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
                fMapData = (float) toDegrees(refinementData.fcTotPhi(i));
                if (!isNaN(fMapData)) {
                    colMinMax[col][0] = Math.min(fMapData, colMinMax[col][0]);
                    colMinMax[col][1] = Math.max(fMapData, colMinMax[col][1]);
                }
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;

                // FOM/phase (2)
                fMapData = (float) refinementData.fomphi[i][0];
                if (!isNaN(fMapData)) {
                    colMinMax[col][0] = Math.min(fMapData, colMinMax[col][0]);
                    colMinMax[col][1] = Math.max(fMapData, colMinMax[col][1]);
                }
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
                fMapData = (float) toDegrees(refinementData.fomphi[i][1]);
                colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;

                // Spline setup.
                double fh = spline.f(ss, refinementData.spline);
                double sa = sigmaASpline.f(ss, refinementData.sigmaa);
                double wa = sigmaASpline.f(ss, refinementData.sigmaw);

                // sigmaA/w (2)
                fMapData = (float) sa;
                if (!isNaN(fMapData)) {
                    colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                    colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                }
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
                fMapData = (float) wa;
                if (!isNaN(fMapData)) {
                    colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                    colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                }
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;

                // Map coeffs (4).
                fMapData = (float) refinementData.FoFc2F(i);
                colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
                fMapData = (float) toDegrees(refinementData.FoFc2Phi(i));
                colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
                fMapData = (float) refinementData.foFc1F(i);
                colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
                fMapData = (float) toDegrees(refinementData.foFc1Phi(i));
                colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
            }

            dataOutputStream.write(bytes, offset, writeLen);
        }

        // Header.
        sb = new StringBuilder();
        sb.append("VERS MTZ:V1.1 ");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss ");
        sb = new StringBuilder();
        sb.append("TITLE FFX output: " + sdf.format(now));
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        sb.append(String.format("NCOL %8d %12d %8d", nCol, n, 0));
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        sb.append("SORT    0    0    0    0    0 ");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        char cdata = spaceGroup.shortName.charAt(0);
        if (cdata == 'H') {
            cdata = 'R';
        }
        sb.append(String.format("SYMINF %3d %2d %c %5d %22s %5s", spaceGroup.getNumberOfSymOps(),
                spaceGroup.numPrimitiveSymEquiv, cdata, spaceGroup.number, "'" + spaceGroup.shortName + "'",
                spaceGroup.pointGroupName));
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        for (int i = 0; i < spaceGroup.symOps.size(); i++) {
            sb = new StringBuilder();
            sb.append("SYMM ");
            SymOp symop = spaceGroup.symOps.get(i);
            sb.append(symop.toXYZString());
            while (sb.length() < 80) {
                sb.append(" ");
            }
            dataOutputStream.writeBytes(sb.toString());
        }

        sb = new StringBuilder();
        sb.append(String.format("RESO %8.6f%13s%8.6f", res[0], " ", res[1]));
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        sb.append("VALM NAN ");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        sb.append("NDIF        1 ");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        sb.append("PROJECT       1 project ");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        sb.append("CRYSTAL       1 crystal ");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        sb.append("DATASET       1 dataset ");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        for (int j = 0; j < nCol; j++) {
            sb = new StringBuilder();
            sb.append(String.format("COLUMN %-30s %c %17.4f %17.4f    1", colname.get(j), colType[j],
                    colMinMax[j][0], colMinMax[j][1]));
            dataOutputStream.writeBytes(sb.toString());
        }

        sb = new StringBuilder();
        sb.append(String.format("CELL %10.4f %9.4f %9.4f %9.4f %9.4f %9.4f ", crystal.a, crystal.b, crystal.c,
                crystal.alpha, crystal.beta, crystal.gamma));
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        sb.append(String.format("DCELL %9d %10.4f %9.4f %9.4f %9.4f %9.4f %9.4f ", 1, crystal.a, crystal.b,
                crystal.c, crystal.alpha, crystal.beta, crystal.gamma));
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        sb.append("DWAVEL        1    1.00000 ");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        sb.append("END ");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        sb.append("MTZENDOFHEADERS ");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        dataOutputStream.close();
    } catch (Exception e) {
        String message = "Fatal exception evaluating structure factors.\n";
        logger.log(Level.SEVERE, message, e);
    }
}

From source file:ManagerQuery.java

private void notifyEvent(String eventType, String furtherDetails) {
    Properties conf2 = new Properties();

    try {/*  ww w. j a v  a 2  s .c om*/
        FileInputStream in = new FileInputStream("./config.properties");
        conf2.load(in);
        in.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex);
    }

    String url = conf2.getProperty("notificatorRestInterfaceUrl");
    String charset = java.nio.charset.StandardCharsets.UTF_8.name();
    String apiUsr = conf2.getProperty("notificatorRestInterfaceUsr");
    String apiPwd = conf2.getProperty("notificatorRestInterfacePwd");
    String operation = "notifyEvent";
    String generatorOriginalName = this.idProc;
    String generatorOriginalType = this.metricType;
    String containerName = this.dataSourceId;

    Calendar date = new GregorianCalendar();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String eventTime = sdf.format(date.getTime());
    String appName = "Dashboard Data Process";
    String params = null;

    URL obj = null;
    HttpURLConnection con = null;
    try {
        obj = new URL(url);
        con = (HttpURLConnection) obj.openConnection();

        con.setRequestMethod("POST");
        con.setRequestProperty("Accept-Charset", charset);
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);

        params = String.format(
                "apiUsr=%s&apiPwd=%s&appName=%s&operation=%s&generatorOriginalName=%s&generatorOriginalType=%s&containerName=%s&eventType=%s&eventTime=%s&furtherDetails=%s",
                URLEncoder.encode(apiUsr, charset), URLEncoder.encode(apiPwd, charset),
                URLEncoder.encode(appName, charset), URLEncoder.encode(operation, charset),
                URLEncoder.encode(generatorOriginalName, charset),
                URLEncoder.encode(generatorOriginalType, charset), URLEncoder.encode(containerName, charset),
                URLEncoder.encode(eventType, charset), URLEncoder.encode(eventTime, charset),
                URLEncoder.encode(furtherDetails, charset));
    } catch (MalformedURLException ex) {
        Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex);
    }

    // Questo rende la chiamata una POST
    con.setDoOutput(true);
    DataOutputStream wr = null;

    try {
        wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(params);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        String responseMessage = con.getResponseMessage();
    } catch (IOException ex) {
        Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ManagerQuery.java

private void notifyEvent(double valueNum, Rule rule) {
    Properties conf2 = new Properties();

    try {/*from w  w w.  j  av  a 2  s  .co  m*/
        FileInputStream in = new FileInputStream("./config.properties");
        conf2.load(in);
        in.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex);
    }

    String url = conf2.getProperty("notificatorRestInterfaceUrl");
    String charset = java.nio.charset.StandardCharsets.UTF_8.name();
    String apiUsr = conf2.getProperty("notificatorRestInterfaceUsr");
    String apiPwd = conf2.getProperty("notificatorRestInterfacePwd");
    String operation = "notifyEvent";
    String generatorOriginalName = rule.getWidgetTitle();
    String generatorOriginalType = rule.getMetricName();
    String containerName = rule.getDashboardTitle();
    String eventType = rule.getEventType();
    String value = Double.toString(valueNum);

    Calendar date = new GregorianCalendar();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String eventTime = sdf.format(date.getTime());
    String appName = "Dashboard Manager";
    String params = null;

    URL obj = null;
    HttpURLConnection con = null;
    try {
        obj = new URL(url);
        con = (HttpURLConnection) obj.openConnection();

        con.setRequestMethod("POST");
        con.setRequestProperty("Accept-Charset", charset);
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);

        params = String.format(
                "apiUsr=%s&apiPwd=%s&appName=%s&operation=%s&generatorOriginalName=%s&generatorOriginalType=%s&containerName=%s&eventType=%s&eventTime=%s&value=%s",
                URLEncoder.encode(apiUsr, charset), URLEncoder.encode(apiPwd, charset),
                URLEncoder.encode(appName, charset), URLEncoder.encode(operation, charset),
                URLEncoder.encode(generatorOriginalName, charset),
                URLEncoder.encode(generatorOriginalType, charset), URLEncoder.encode(containerName, charset),
                URLEncoder.encode(eventType, charset), URLEncoder.encode(eventTime, charset),
                URLEncoder.encode(value, charset));
    } catch (MalformedURLException ex) {
        Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex);
    }

    // Questo rende la chiamata una POST
    con.setDoOutput(true);
    DataOutputStream wr = null;

    try {
        wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(params);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        String responseMessage = con.getResponseMessage();
    } catch (IOException ex) {
        Logger.getLogger(ManagerQuery.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.hellofyc.base.net.http.HttpUtils.java

protected void configConnection(HttpURLConnection connection) throws IOException {
    connection.setConnectTimeout(mConnectTimeout);
    connection.setReadTimeout(mReadTimeout);
    connection.setUseCaches(false);/*from w ww.j  a  v a 2  s  . c o m*/
    connection.setDoInput(true);
    connection.setRequestProperty("Charset", Charset.defaultCharset().name());
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("User-Agent", mUserAgent);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestProperty("Cookie", CookieHelper.parse(mRequestParams.getCookies()));

    switch (mType) {
    case TYPE_TEXT: {
        connection.setRequestMethod(mMethod.name());
        if (mMethod == Method.POST) {
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", CONTENT_TYPE_TEXT);
            String paramsString;
            if (!TextUtils.isEmpty(mRequestParams.getString())) {
                paramsString = mRequestParams.getString();
            } else {
                paramsString = parseMapToUrlParamsString(mRequestParams.getArrayMap());
            }
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.write(paramsString.getBytes());
            outputStream.flush();
            outputStream.close();
        }
        break;
    }
    case TYPE_BITMAP: {
        connection.setRequestMethod(Method.POST.name());
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", CONTENT_TYPE_FILE);
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, Object> entry : mRequestParams.getArrayMap().entrySet()) {
            builder.append(PREFIX).append(BOUNDARY).append(LINE_END);
            builder.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"")
                    .append(LINE_END);
            builder.append("Content-Type: text/plain; charset=\"utf-8\"").append(LINE_END);
            builder.append("Content-Transfer-Encoding: 8bit").append(LINE_END);
            builder.append(LINE_END);
            builder.append(entry.getValue());
            builder.append(LINE_END);
        }
        outputStream.write(builder.toString().getBytes());

        outputStream.writeBytes(PREFIX + BOUNDARY + LINE_END);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + "bitmap" + "\";filename=\""
                + "bitmap.jpg" + "\"" + LINE_END);
        outputStream.writeBytes(LINE_END);
        outputStream.write(bitmapToBytes(mBitmap));
        outputStream.writeBytes(LINE_END);
        outputStream.writeBytes(PREFIX + BOUNDARY + PREFIX + LINE_END);
        outputStream.flush();
        outputStream.close();
        break;
    }
    case TYPE_FILE: {
        connection.setRequestMethod(Method.POST.name());
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", CONTENT_TYPE_FILE);

        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, Object> entry : mRequestParams.getArrayMap().entrySet()) {
            builder.append(PREFIX).append(BOUNDARY).append(LINE_END);
            builder.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"")
                    .append(LINE_END);
            builder.append("Content-Type: text/plain; charset=\"utf-8\"").append(LINE_END);
            builder.append("Content-Transfer-Encoding: 8bit").append(LINE_END);
            builder.append(LINE_END);
            builder.append(entry.getValue());
            builder.append(LINE_END);
        }

        for (ArrayMap.Entry<String, File> entry : mFileMap.entrySet()) {
            String text = PREFIX + BOUNDARY + LINE_END + "Content-Disposition: form-data; name=\""
                    + entry.getKey() + "\"; filename=\"" + entry.getValue().getName() + "\"" + LINE_END
                    + "Content-Type:" + "application/octet-stream" + LINE_END
                    + "Content-Transfer-Encoding: binary" + LINE_END + LINE_END;
            outputStream.writeBytes(builder.append(text).toString());

            BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(entry.getValue()));
            int length;
            byte[] bytes = new byte[1024 * 1024];
            while ((length = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }
            inputStream.close();
        }

        String endTag = LINE_END + PREFIX + BOUNDARY + PREFIX + LINE_END;
        outputStream.writeBytes(endTag);
        outputStream.flush();
        outputStream.close();
        break;
    }
    }
}

From source file:org.eclipse.skalli.testutil.HttpServerMock.java

@Override
public void run() {
    BufferedReader request = null;
    DataOutputStream response = null;
    try {//from  w w  w.ja  v  a2 s  .c o m
        server = new ServerSocket(port);
        while (true) {
            Socket connection = server.accept();

            request = new BufferedReader(new InputStreamReader(connection.getInputStream(), "ISO8859_1"));
            response = new DataOutputStream(connection.getOutputStream());

            String httpCode;
            String contentId = "";
            String requestLine = request.readLine();

            if (!StringUtils.startsWithIgnoreCase(requestLine, "GET")) {
                httpCode = "405";
            } else {
                String path = StringUtils.split(requestLine, " ")[1];
                int n = StringUtils.lastIndexOf(path, "/");
                contentId = StringUtils.substring(path, 1, n);
                httpCode = StringUtils.substring(path, n + 1);
            }

            String content = bodies.get(contentId);
            StringBuffer sb = new StringBuffer();
            sb.append("HTTP/1.1 ").append(httpCode).append(" CustomStatus\r\n");
            sb.append("Server: MiniMockUnitServer\r\n");
            sb.append("Content-Type: text/plain\r\n");
            if (content != null) {
                sb.append("Content-Length: ").append(content.length()).append("\r\n");
            }
            sb.append("Connection: close\r\n");
            sb.append("\r\n");
            if (content != null) {
                sb.append(content);
            }

            response.writeBytes(sb.toString());
            IOUtils.closeQuietly(response);
        }
    } catch (IOException e) {
        IOUtils.closeQuietly(request);
        IOUtils.closeQuietly(response);
    } finally {
        try {
            server.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.stratuscom.harvester.codebase.ClassServer.java

private boolean processRequest(Socket sock) {
    try {/*from  w  w w  . jav a2 s.  c om*/
        DataOutputStream out = new DataOutputStream(sock.getOutputStream());
        String req;
        try {
            req = getInput(sock, true);
        } catch (Exception e) {
            logger.log(Level.FINE, "reading request", e);
            return true;
        }
        if (req == null) {
            return true;
        }
        String[] args = new String[3];
        boolean get = req.startsWith("GET ");
        if (!get && !req.startsWith("HEAD ")) {
            processBadRequest(args, out);
        }
        String path = parsePathFromRequest(req, get);
        if (path == null) {
            return processBadRequest(args, out);
        }
        if (args != null) {
            args[0] = path;
        }
        args[1] = sock.getInetAddress().getHostName();
        args[2] = Integer.toString(sock.getPort());

        logger.log(Level.FINER,
                get ? MessageNames.CLASS_SERVER_RECEIVED_REQUEST : MessageNames.CLASS_SERVER_RECEIVED_PROBE,
                args);
        byte[] bytes;
        try {
            bytes = getBytes(path);
        } catch (Exception e) {
            logger.log(Level.WARNING, MessageNames.CLASS_SERVER_EXCEPTION_GETTING_BYTES, e);
            out.writeBytes("HTTP/1.0 500 Internal Error\r\n\r\n");
            out.flush();
            return true;
        }
        if (bytes == null) {
            logger.log(Level.FINE, MessageNames.CLASS_SERVER_NO_CONTENT_FOUND, path);
            out.writeBytes("HTTP/1.0 404 Not Found\r\n\r\n");
            out.flush();
            return true;
        }
        writeHeader(out, bytes);
        if (get) {
            out.write(bytes);
        }
        out.flush();
        return false;
    } catch (Exception e) {
        logger.log(Level.FINE, MessageNames.CLASS_SERVER_EXCEPTION_WRITING_RESPONSE, e);
    } finally {
        try {
            sock.close();
        } catch (IOException e) {
        }
    }
    return false;
}

From source file:com.citrus.mobile.RESTclient.java

public JSONObject makeSendMoneyRequest(String accessToken, CitrusUser toUser, Amount amount, String message) {
    HttpsURLConnection conn;//w  w w  .j  a v a 2  s  .c  o  m
    DataOutputStream wr = null;
    JSONObject txnDetails = null;
    BufferedReader in = null;

    try {
        String url = null;

        StringBuffer postDataBuff = new StringBuffer("amount=");
        postDataBuff.append(amount.getValue());

        postDataBuff.append("&currency=");
        postDataBuff.append(amount.getCurrency());

        postDataBuff.append("&message=");
        postDataBuff.append(message);

        if (!TextUtils.isEmpty(toUser.getEmailId())) {
            url = urls.getString(base_url) + urls.getString("transfer");
            postDataBuff.append("&to=");
            postDataBuff.append(toUser.getEmailId());

        } else if (!TextUtils.isEmpty(toUser.getMobileNo())) {
            url = urls.getString(base_url) + urls.getString("suspensetransfer");

            postDataBuff.append("&to=");
            postDataBuff.append(toUser.getMobileNo());

        }

        conn = (HttpsURLConnection) new URL(url).openConnection();

        //add reuqest header
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Bearer " + accessToken);

        conn.setDoOutput(true);
        wr = new DataOutputStream(conn.getOutputStream());

        wr.writeBytes(postDataBuff.toString());
        wr.flush();

        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + postDataBuff.toString());
        System.out.println("Response Code : " + responseCode);

        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

        txnDetails = new JSONObject(response.toString());

    } catch (JSONException exception) {
        exception.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

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

    return txnDetails;
}