Example usage for java.io DataOutputStream write

List of usage examples for java.io DataOutputStream write

Introduction

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

Prototype

public synchronized void write(int b) throws IOException 

Source Link

Document

Writes the specified byte (the low eight bits of the argument b) to the underlying output stream.

Usage

From source file:org.apache.fontbox.ttf.TTFSubsetter.java

private byte[] buildOS2Table() throws IOException {
    OS2WindowsMetricsTable os2 = ttf.getOS2Windows();
    if (os2 == null || uniToGID.isEmpty() || keepTables != null && !keepTables.contains("OS/2")) {
        return null;
    }//from w ww. j av a  2 s. c o m

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(bos);

    writeUint16(out, os2.getVersion());
    writeSInt16(out, os2.getAverageCharWidth());
    writeUint16(out, os2.getWeightClass());
    writeUint16(out, os2.getWidthClass());

    writeSInt16(out, os2.getFsType());

    writeSInt16(out, os2.getSubscriptXSize());
    writeSInt16(out, os2.getSubscriptYSize());
    writeSInt16(out, os2.getSubscriptXOffset());
    writeSInt16(out, os2.getSubscriptYOffset());

    writeSInt16(out, os2.getSuperscriptXSize());
    writeSInt16(out, os2.getSuperscriptYSize());
    writeSInt16(out, os2.getSuperscriptXOffset());
    writeSInt16(out, os2.getSuperscriptYOffset());

    writeSInt16(out, os2.getStrikeoutSize());
    writeSInt16(out, os2.getStrikeoutPosition());
    writeSInt16(out, (short) os2.getFamilyClass());
    out.write(os2.getPanose());

    writeUint32(out, 0);
    writeUint32(out, 0);
    writeUint32(out, 0);
    writeUint32(out, 0);

    out.write(os2.getAchVendId().getBytes("US-ASCII"));

    writeUint16(out, os2.getFsSelection());
    writeUint16(out, uniToGID.firstKey());
    writeUint16(out, uniToGID.lastKey());
    writeUint16(out, os2.getTypoAscender());
    writeUint16(out, os2.getTypoDescender());
    writeUint16(out, os2.getTypoLineGap());
    writeUint16(out, os2.getWinAscent());
    writeUint16(out, os2.getWinDescent());

    out.flush();
    return bos.toByteArray();
}

From source file:com.kyne.webby.rtk.web.WebServer.java

/**
 * Read a print a static file (js, css, html or png).
 * @param path the path to the file//from www  . j av  a 2  s .co m
 * @param type the mimetype
 * @param jsStates some javascripts variables that may be initialized in the printed content. Null if not required.
 * @param clientSocket the client-side socket
 */
public void printStaticFile(final String path, final String type, final Socket clientSocket,
        final Map<String, String> jsStates) {
    try {
        final File htmlPage = new File(path);
        if (htmlPage.exists()) {
            final DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
            out.writeBytes("HTTP/1.1 200 OK\r\n");
            out.writeBytes("Content-Type: " + type + "; charset=utf-8\r\n");
            out.writeBytes("Cache-Control: no-cache \r\n");
            out.writeBytes("Server: Bukkit Webby\r\n");
            out.writeBytes("Connection: Close\r\n\r\n");
            if (jsStates != null) {
                out.writeBytes("<script type='text/javascript'>");
                for (final String var : jsStates.keySet()) {
                    out.writeBytes("var " + var + " = '" + jsStates.get(var) + "';");
                }
                out.writeBytes("</script>");
            }
            if (!this.htmlCache.containsKey(path)) { //Pages are static, so we can "pre-read" them. Dynamic content will be rendered with javascript
                final FileInputStream fis = new FileInputStream(htmlPage);
                final byte fileContent[] = new byte[(int) htmlPage.length()];
                fis.read(fileContent);
                fis.close();
                this.htmlCache.put(path, fileContent);
            } else {
                LogHelper.debug("File will be added in Webby's cache");
            }
            out.write(this.htmlCache.get(path));
            out.flush();
            out.close();
        } else {
            LogHelper.warn("Requested file " + path + " can't be found");
        }
    } catch (final SocketException e) {
        /* Or not ! */
    } catch (final Exception e) {
        LogHelper.error(e.getMessage(), e);
    }
}

From source file:org.apache.fop.render.pcl.PCLGenerator.java

/**
 * Generates a user-defined pattern for a dithering pattern matching the grayscale value
 * of the color given./*w  ww  . j  a  v a 2 s .com*/
 * @param col the color to create the pattern for
 * @param patternID the pattern ID to use
 * @param ditherMatrixSize the size of the Bayer dither matrix to use (4 or 8 supported)
 * @throws IOException In case of an I/O error
 */
public void defineGrayscalePattern(Color col, int patternID, int ditherMatrixSize) throws IOException {
    ByteArrayOutputStream baout = new ByteArrayOutputStream();
    DataOutputStream data = new DataOutputStream(baout);
    data.writeByte(0); //Format
    data.writeByte(0); //Continuation
    data.writeByte(1); //Pixel Encoding
    data.writeByte(0); //Reserved
    data.writeShort(8); //Width in Pixels
    data.writeShort(8); //Height in Pixels
    //data.writeShort(600); //X Resolution (didn't manage to get that to work)
    //data.writeShort(600); //Y Resolution
    int gray255 = convertToGray(col.getRed(), col.getGreen(), col.getBlue());

    byte[] pattern;
    if (ditherMatrixSize == 8) {
        pattern = DitherUtil.getBayerDither(DitherUtil.DITHER_MATRIX_8X8, gray255, false);
    } else {
        //Since a 4x4 pattern did not work, the 4x4 pattern is applied 4 times to an
        //8x8 pattern. Maybe this could be changed to use an 8x8 bayer dither pattern
        //instead of the 4x4 one.
        pattern = DitherUtil.getBayerDither(DitherUtil.DITHER_MATRIX_4X4, gray255, true);
    }
    data.write(pattern);
    if ((baout.size() % 2) > 0) {
        baout.write(0);
    }
    writeCommand("*c" + patternID + "G");
    writeCommand("*c" + baout.size() + "W");
    baout.writeTo(this.out);
    writeCommand("*c4Q"); //temporary pattern
}

From source file:org.motechproject.mobile.web.OXDFormDownloadServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//ww w .  j a  v  a  2 s.co m
 *
 * @param request  servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException      if an I/O error occurs
 */
@RequestMapping(method = RequestMethod.POST)
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Get our raw input and output streams
    InputStream input = request.getInputStream();
    OutputStream output = response.getOutputStream();

    // Wrap the streams for compression
    ZOutputStream zOutput = new ZOutputStream(output, JZlib.Z_BEST_COMPRESSION);

    // Wrap the streams so we can use logical types
    DataInputStream dataInput = new DataInputStream(input);
    DataOutputStream dataOutput = new DataOutputStream(zOutput);

    try {

        // Read the common submission data from mobile phone
        String name = dataInput.readUTF();
        String password = dataInput.readUTF();
        String serializer = dataInput.readUTF();
        String locale = dataInput.readUTF();

        byte action = dataInput.readByte();

        // TODO: add authentication, possible M6 enhancement

        log.info("downloading: name=" + name + ", password=" + password + ", serializer=" + serializer
                + ", locale=" + locale + ", action=" + action);

        EpihandyXformSerializer serObj = new EpihandyXformSerializer();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // Perform the action specified by the mobile phone
        try {
            if (action == ACTION_DOWNLOAD_STUDY_LIST) {
                serObj.serializeStudies(baos, studyService.getStudies());
            } else if (action == ACTION_DOWNLOAD_USERS_AND_FORMS) {

                serObj.serializeUsers(baos, userService.getUsers());

                int studyId = dataInput.readInt();
                String studyName = studyService.getStudyName(studyId);
                List<String> studyForms = formService.getStudyForms(studyId);

                serObj.serializeForms(baos, studyForms, studyId, studyName);

            }
        } catch (Exception e) {
            dataOutput.writeByte(RESPONSE_ERROR);
            throw new ServletException("failed to serialize data", e);
        }

        // Write out successful upload response
        dataOutput.writeByte(RESPONSE_SUCCESS);
        dataOutput.write(baos.toByteArray());
        response.setStatus(HttpServletResponse.SC_OK);

    } finally {
        // Should always do this
        dataOutput.flush();
        zOutput.finish();
        response.flushBuffer();
    }
}

From source file:org.apache.hadoop.hbase.io.hfile.FixedFileTrailer.java

/**
 * Write the trailer to a data stream. We support writing version 1 for
 * testing and for determining version 1 trailer size. It is also easy to see
 * what fields changed in version 2./*ww w  .j  av a  2  s.  c o m*/
 *
 * @param outputStream
 * @throws IOException
 */
void serialize(DataOutputStream outputStream) throws IOException {
    HFile.checkFormatVersion(majorVersion);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutput baosDos = new DataOutputStream(baos);

    BlockType.TRAILER.write(baosDos);
    baosDos.writeLong(fileInfoOffset);
    baosDos.writeLong(loadOnOpenDataOffset);
    baosDos.writeInt(dataIndexCount);

    if (majorVersion == 1) {
        // This used to be metaIndexOffset, but it was not used in version 1.
        baosDos.writeLong(0);
    } else {
        baosDos.writeLong(uncompressedDataIndexSize);
    }

    baosDos.writeInt(metaIndexCount);
    baosDos.writeLong(totalUncompressedBytes);
    if (majorVersion == 1) {
        baosDos.writeInt((int) Math.min(Integer.MAX_VALUE, entryCount));
    } else {
        // This field is long from version 2 onwards.
        baosDos.writeLong(entryCount);
    }
    baosDos.writeInt(compressionCodec.ordinal());

    if (majorVersion > 1) {
        baosDos.writeInt(numDataIndexLevels);
        baosDos.writeLong(firstDataBlockOffset);
        baosDos.writeLong(lastDataBlockOffset);
        Bytes.writeStringFixedSize(baosDos, comparatorClassName, MAX_COMPARATOR_NAME_LENGTH);
    }

    // serialize the major and minor versions
    baosDos.writeInt(materializeVersion(majorVersion, minorVersion));

    outputStream.write(baos.toByteArray());
}

From source file:org.fcrepo.test.api.TestRESTAPI.java

@Test
public void testAddDatastream() throws Exception {
    // inline (X) datastream
    String xmlData = "<foo>bar</foo>";
    String dsPath = "/objects/" + DEMO_REST_PID + "/datastreams/FOO";
    URI url = getURI(dsPath + "?controlGroup=X&dsLabel=foo");
    StringEntity entity = getStringEntity(xmlData, TEXT_XML);
    verifyPOSTStatusOnly(url, SC_UNAUTHORIZED, entity, false);
    HttpPost post = new HttpPost(url);
    HttpResponse response = putOrPost(post, entity, true);
    String expected = readString(response);
    assertEquals(SC_CREATED, response.getStatusLine().getStatusCode());
    Header locationHeader = response.getFirstHeader(HttpHeaders.LOCATION);
    assertNotNull(locationHeader);//  w  w w  . j  a v a2  s  .  c  o  m
    assertEquals(getURI(dsPath), URI.create(locationHeader.getValue()));
    assertEquals(TEXT_XML, response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
    url = getURI(dsPath + "?format=xml");
    String actual = verifyGETStatusString(url, SC_OK, true, true);
    assertEquals(expected, actual);

    // managed (M) datastream
    String mimeType = "text/plain";
    Datastream ds = apim.getDatastream(DEMO_REST_PID.toString(), "BAR", null);
    assertNull(ds);
    dsPath = "/objects/" + DEMO_REST_PID + "/datastreams/BAR";
    url = getURI(dsPath + "?controlGroup=M&dsLabel=bar&mimeType=" + mimeType);
    File temp = File.createTempFile("test", null);
    DataOutputStream os = new DataOutputStream(new FileOutputStream(temp));
    os.write(42);
    os.close();
    response = post(url, temp, false);
    EntityUtils.consumeQuietly(response.getEntity());
    assertEquals(SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
    response = post(url, temp, true);
    expected = readString(response);
    assertEquals(SC_CREATED, response.getStatusLine().getStatusCode());
    locationHeader = response.getFirstHeader(HttpHeaders.LOCATION);
    assertNotNull(locationHeader);
    assertEquals(getURI(dsPath), URI.create(locationHeader.getValue()));
    assertEquals(TEXT_XML, response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
    url = getURI(dsPath + "?format=xml");
    actual = verifyGETStatusString(url, SC_OK, true, true);
    assertEquals(expected, actual);
    ds = apim.getDatastream(DEMO_REST_PID.toString(), "BAR", null);
    assertNotNull(ds);
    assertEquals(ds.getMIMEType(), mimeType);
}

From source file:org.fcrepo.test.api.TestRESTAPI.java

@Test
public void testModifyDatastreamByReference() throws Exception {
    // Create BAR datastream
    URI url = getURI(String.format(
            "/objects/%s/datastreams/BAR?controlGroup=M&dsLabel=testModifyDatastreamByReference(bar)",
            DEMO_REST_PID.toString()));/*from  ww w.  j ava  2  s.com*/
    File temp = File.createTempFile("test", null);
    DataOutputStream os = new DataOutputStream(new FileOutputStream(temp));
    os.write(42);
    os.close();
    HttpResponse response = post(url, temp, false);
    EntityUtils.consumeQuietly(response.getEntity());
    assertEquals(SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
    response = post(url, temp, true);
    EntityUtils.consumeQuietly(response.getEntity());
    assertEquals(SC_CREATED, response.getStatusLine().getStatusCode());

    // Update the content of the BAR datastream (using PUT)
    url = getURI(String.format("/objects/%s/datastreams/BAR", DEMO_REST_PID.toString()));
    assertEquals(SC_UNAUTHORIZED, put(url, temp, false).getStatusLine().getStatusCode());
    response = put(url, temp, true);
    String expected = readString(response);
    assertEquals(SC_OK, response.getStatusLine().getStatusCode());
    assertEquals(TEXT_XML, response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
    url = getURI(url.toString() + "?format=xml");
    String actual = verifyGETStatusString(url, SC_OK, true, true);
    assertEquals(expected, actual);

    // Ensure 404 on attempt to update BOGUS_DS via PUT
    url = getURI("/objects/" + DEMO_REST_PID + "/datastreams/BOGUS_DS");
    response = put(url, temp, true);
    EntityUtils.consumeQuietly(response.getEntity());
    assertEquals(SC_NOT_FOUND, response.getStatusLine().getStatusCode());

    // Update the content of the BAR datastream (using POST)
    url = getURI(String.format("/objects/%s/datastreams/BAR", DEMO_REST_PID.toString()));
    response = post(url, temp, true);
    expected = readString(response);
    assertEquals(SC_CREATED, response.getStatusLine().getStatusCode());
    Header locationHeader = response.getFirstHeader(HttpHeaders.LOCATION);
    assertNotNull(locationHeader);
    assertEquals(url.toString(), locationHeader.getValue());
    assertEquals(TEXT_XML, response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
    url = getURI(url.toString() + "?format=xml");
    actual = verifyGETStatusString(url, SC_OK, true, true);
    assertEquals(expected, actual);

    // Update the label of the BAR datastream
    String newLabel = "tikibar";
    url = getURI(String.format("/objects/%s/datastreams/BAR?dsLabel=%s", DEMO_REST_PID.toString(), newLabel));
    verifyPUTStatusOnly(url, SC_UNAUTHORIZED, null, false);
    verifyPUTStatusOnly(url, SC_OK, null, true);
    assertEquals(newLabel, apim.getDatastream(DEMO_REST_PID.toString(), "BAR", null).getLabel());

    // Update the location of the EXTDS datastream (E type datastream)
    String newLocation = "http://" + getHost() + ":" + getPort() + "/" + getFedoraAppServerContext()
            + "/get/demo:REST/DC";
    url = getURI(String.format("/objects/%s/datastreams/EXTDS?dsLocation=%s", DEMO_REST_PID.toString(),
            newLocation));
    verifyPUTStatusOnly(url, SC_UNAUTHORIZED, null, false);
    verifyPUTStatusOnly(url, SC_OK, null, true);

    assertEquals(newLocation, apim.getDatastream(DEMO_REST_PID.toString(), "EXTDS", null).getLocation());
    String dcDS = new String(TypeUtility.convertDataHandlerToBytes(
            apia.getDatastreamDissemination(DEMO_REST_PID.toString(), "DC", null).getStream()));
    String extDS = new String(TypeUtility.convertDataHandlerToBytes(
            apia.getDatastreamDissemination(DEMO_REST_PID.toString(), "EXTDS", null).getStream()));
    assertEquals(dcDS, extDS);

    // Update DS1 by reference (X type datastream)
    // Error expected because attempting to access internal DS with API-A auth on
    if (getAuthAccess()) {
        // only ConfigB has API-A auth on
        url = getURI(String.format("/objects/%s/datastreams/DS1?dsLocation=%s", DEMO_REST_PID.toString(),
                newLocation));
        verifyPUTStatusOnly(url, SC_UNAUTHORIZED, null, false);
        verifyPUTStatusOnly(url, SC_INTERNAL_SERVER_ERROR, null, true);
    }

    // Update DS1 by reference (X type datastream) - Success expected
    newLocation = getBaseURL() + "/ri/index.xsl";
    url = getURI(
            String.format("/objects/%s/datastreams/DS1?dsLocation=%s", DEMO_REST_PID.toString(), newLocation));
    verifyPUTStatusOnly(url, SC_UNAUTHORIZED, null, false);
    verifyPUTStatusOnly(url, SC_OK, null, true);
}

From source file:org.apache.jmeter.protocol.mqttws.client.MqttPublisher.java

public byte[] createPayload(String message, String useTimeStamp, String useNumSeq, String type_value,
        String format, String charset) throws IOException, NumberFormatException {
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    DataOutputStream d = new DataOutputStream(b);
    // flags     
    byte flags = 0x00;
    if ("TRUE".equals(useTimeStamp))
        flags |= 0x80;//from   w  w w.  j a  v  a  2s .  c  o  m
    if ("TRUE".equals(useNumSeq))
        flags |= 0x40;
    if (MQTTPublisherGui.INT.equals(type_value))
        flags |= 0x20;
    if (MQTTPublisherGui.LONG.equals(type_value))
        flags |= 0x10;
    if (MQTTPublisherGui.FLOAT.equals(type_value))
        flags |= 0x08;
    if (MQTTPublisherGui.DOUBLE.equals(type_value))
        flags |= 0x04;
    if (MQTTPublisherGui.STRING.equals(type_value))
        flags |= 0x02;
    if (!"TEXT".equals(type_value)) {
        d.writeByte(flags);
    }
    // TimeStamp
    if ("TRUE".equals(useTimeStamp)) {
        Date date = new java.util.Date();
        d.writeLong(date.getTime());
    }
    // Number Sequence
    if ("TRUE".equals(useNumSeq)) {
        d.writeInt(numSeq++);

    }
    // Value            
    if (MQTTPublisherGui.INT.equals(type_value)) {
        d.writeInt(Integer.parseInt(message));
    } else if (MQTTPublisherGui.LONG.equals(type_value)) {
        d.writeLong(Long.parseLong(message));
    } else if (MQTTPublisherGui.DOUBLE.equals(type_value)) {
        d.writeDouble(Double.parseDouble(message));
    } else if (MQTTPublisherGui.FLOAT.equals(type_value)) {
        d.writeDouble(Float.parseFloat(message));
    } else if (MQTTPublisherGui.STRING.equals(type_value)) {
        d.write(message.getBytes());
    } else if ("TEXT".equals(type_value)) {
        d.write(message.getBytes());
    } else if ("TEXT_POOL".equals(type_value)) {
        String random_message = createRandomMessageFromPool(message);
        d.write(random_message.getBytes());
    }

    // Format: Encoding        
    if (MQTTPublisherGui.BINARY.equals(format)) {
        BinaryCodec encoder = new BinaryCodec();
        return encoder.encode(b.toByteArray());
    } else if (MQTTPublisherGui.BASE64.equals(format)) {
        return Base64.encodeBase64(b.toByteArray());
    } else if (MQTTPublisherGui.BINHEX.equals(format)) {
        Hex encoder = new Hex();
        return encoder.encode(b.toByteArray());
    } else if (MQTTPublisherGui.PLAIN_TEXT.equals(format)) {
        String s = new String(b.toByteArray(), charset);
        return s.getBytes();

    } else
        return b.toByteArray();
}

From source file:org.apache.hadoop.hive.ql.metadata.formatting.TextMetaDataFormatter.java

@Override
public void describeTable(DataOutputStream outStream, String colPath, String tableName, Table tbl,
        Partition part, List<FieldSchema> cols, boolean isFormatted, boolean isExt, boolean isPretty,
        boolean isOutputPadded, List<ColumnStatisticsObj> colStats, PrimaryKeyInfo pkInfo,
        ForeignKeyInfo fkInfo, UniqueConstraint ukInfo, NotNullConstraint nnInfo) throws HiveException {
    try {/*from   w w  w . j  a v a  2  s .com*/
        String output;
        if (colPath.equals(tableName)) {
            List<FieldSchema> partCols = tbl.isPartitioned() ? tbl.getPartCols() : null;
            output = isPretty
                    ? MetaDataPrettyFormatUtils.getAllColumnsInformation(cols, partCols, prettyOutputNumCols)
                    : MetaDataFormatUtils.getAllColumnsInformation(cols, partCols, isFormatted, isOutputPadded,
                            showPartColsSeparately);
        } else {
            output = MetaDataFormatUtils.getAllColumnsInformation(cols, isFormatted, isOutputPadded, colStats);
            String statsState;
            if (tbl.getParameters() != null
                    && (statsState = tbl.getParameters().get(StatsSetupConst.COLUMN_STATS_ACCURATE)) != null) {
                StringBuilder str = new StringBuilder();
                MetaDataFormatUtils.formatOutput(StatsSetupConst.COLUMN_STATS_ACCURATE,
                        isFormatted ? StringEscapeUtils.escapeJava(statsState)
                                : HiveStringUtils.escapeJava(statsState),
                        str, isOutputPadded);
                output = output.concat(str.toString());
            }
        }
        outStream.write(output.getBytes("UTF-8"));

        if (tableName.equals(colPath)) {
            if (isFormatted) {
                if (part != null) {
                    output = MetaDataFormatUtils.getPartitionInformation(part);
                } else {
                    output = MetaDataFormatUtils.getTableInformation(tbl, isOutputPadded);
                }
                outStream.write(output.getBytes("UTF-8"));

                if ((pkInfo != null && !pkInfo.getColNames().isEmpty())
                        || (fkInfo != null && !fkInfo.getForeignKeys().isEmpty())
                        || (ukInfo != null && !ukInfo.getUniqueConstraints().isEmpty())
                        || (nnInfo != null && !nnInfo.getNotNullConstraints().isEmpty())) {
                    output = MetaDataFormatUtils.getConstraintsInformation(pkInfo, fkInfo, ukInfo, nnInfo);
                    outStream.write(output.getBytes("UTF-8"));
                }
            }

            // if extended desc table then show the complete details of the table
            if (isExt) {
                // add empty line
                outStream.write(terminator);
                if (part != null) {
                    // show partition information
                    outStream.write(("Detailed Partition Information").getBytes("UTF-8"));
                    outStream.write(separator);
                    outStream.write(part.getTPartition().toString().getBytes("UTF-8"));
                    outStream.write(separator);
                    // comment column is empty
                    outStream.write(terminator);
                } else {
                    // show table information
                    outStream.write(("Detailed Table Information").getBytes("UTF-8"));
                    outStream.write(separator);
                    outStream.write(tbl.getTTable().toString().getBytes("UTF-8"));
                    outStream.write(separator);
                    outStream.write(terminator);
                }
                if ((pkInfo != null && !pkInfo.getColNames().isEmpty())
                        || (fkInfo != null && !fkInfo.getForeignKeys().isEmpty())
                        || (ukInfo != null && !ukInfo.getUniqueConstraints().isEmpty())
                        || (nnInfo != null && !nnInfo.getNotNullConstraints().isEmpty())) {
                    outStream.write(("Constraints").getBytes("UTF-8"));
                    outStream.write(separator);
                    if (pkInfo != null && !pkInfo.getColNames().isEmpty()) {
                        outStream.write(pkInfo.toString().getBytes("UTF-8"));
                        outStream.write(terminator);
                    }
                    if (fkInfo != null && !fkInfo.getForeignKeys().isEmpty()) {
                        outStream.write(fkInfo.toString().getBytes("UTF-8"));
                        outStream.write(terminator);
                    }
                    if (ukInfo != null && !ukInfo.getUniqueConstraints().isEmpty()) {
                        outStream.write(ukInfo.toString().getBytes("UTF-8"));
                        outStream.write(terminator);
                    }
                    if (nnInfo != null && !nnInfo.getNotNullConstraints().isEmpty()) {
                        outStream.write(nnInfo.toString().getBytes("UTF-8"));
                        outStream.write(terminator);
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new HiveException(e);
    }
}

From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java

/**
 * This assumes that authentication is the last piece of info in handshake
 *//* w ww.  jav a 2 s.  co m*/
public void writeCredentials(DataOutputStream dos, DataInputStream dis, Properties p_credentials,
        boolean isNotification, DistributedMember member, HeapDataOutputStream heapdos)
        throws IOException, GemFireSecurityException {

    if (p_credentials == null) {
        // No credentials indicator
        heapdos.writeByte(CREDENTIALS_NONE);
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();
        return;
    }

    if (dhSKAlgo == null || dhSKAlgo.length() == 0) {
        // Normal credentials without encryption indicator
        heapdos.writeByte(CREDENTIALS_NORMAL);
        DataSerializer.writeProperties(p_credentials, heapdos);
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();
        return;
    }

    try {
        InternalLogWriter securityLogWriter = (InternalLogWriter) this.system.getSecurityLogWriter();
        securityLogWriter.fine("HandShake: using Diffie-Hellman key exchange with algo " + dhSKAlgo);
        boolean requireAuthentication = (certificateFilePath != null && certificateFilePath.length() > 0);
        if (requireAuthentication) {
            securityLogWriter.fine("HandShake: server authentication using digital " + "signature required");
        }
        // Credentials with encryption indicator
        heapdos.writeByte(CREDENTIALS_DHENCRYPT);
        heapdos.writeBoolean(requireAuthentication);
        // Send the symmetric encryption algorithm name
        DataSerializer.writeString(dhSKAlgo, heapdos);
        // Send the DH public key
        byte[] keyBytes = dhPublicKey.getEncoded();
        DataSerializer.writeByteArray(keyBytes, heapdos);
        byte[] clientChallenge = null;
        if (requireAuthentication) {
            // Authentication of server should be with the client supplied
            // challenge
            clientChallenge = new byte[64];
            random.nextBytes(clientChallenge);
            DataSerializer.writeByteArray(clientChallenge, heapdos);
        }
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();

        // Expect the alias and signature in the reply
        byte acceptanceCode = dis.readByte();
        if (acceptanceCode != REPLY_OK && acceptanceCode != REPLY_AUTH_NOT_REQUIRED) {
            // Ignore the useless data
            dis.readByte();
            dis.readInt();
            if (!isNotification) {
                DataSerializer.readByteArray(dis);
            }
            readMessage(dis, dos, acceptanceCode, member);
        } else if (acceptanceCode == REPLY_OK) {
            // Get the public key of the other side
            keyBytes = DataSerializer.readByteArray(dis);
            if (requireAuthentication) {
                String subject = DataSerializer.readString(dis);
                byte[] signatureBytes = DataSerializer.readByteArray(dis);
                if (!certificateMap.containsKey(subject)) {
                    throw new AuthenticationFailedException(
                            LocalizedStrings.HandShake_HANDSHAKE_FAILED_TO_FIND_PUBLIC_KEY_FOR_SERVER_WITH_SUBJECT_0
                                    .toLocalizedString(subject));
                }

                // Check the signature with the public key
                X509Certificate cert = (X509Certificate) certificateMap.get(subject);
                Signature sig = Signature.getInstance(cert.getSigAlgName());
                sig.initVerify(cert);
                sig.update(clientChallenge);
                // Check the challenge string
                if (!sig.verify(signatureBytes)) {
                    throw new AuthenticationFailedException(
                            "Mismatch in client " + "challenge bytes. Malicious server?");
                }
                securityLogWriter
                        .fine("HandShake: Successfully verified the " + "digital signature from server");
            }

            byte[] challenge = DataSerializer.readByteArray(dis);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFact = KeyFactory.getInstance("DH");
            // PublicKey pubKey = keyFact.generatePublic(x509KeySpec);
            this.clientPublicKey = keyFact.generatePublic(x509KeySpec);

            HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT);
            try {
                DataSerializer.writeProperties(p_credentials, hdos);
                // Also add the challenge string
                DataSerializer.writeByteArray(challenge, hdos);

                // byte[] encBytes = encrypt.doFinal(hdos.toByteArray());
                byte[] encBytes = encryptBytes(hdos.toByteArray(),
                        getEncryptCipher(dhSKAlgo, this.clientPublicKey));
                DataSerializer.writeByteArray(encBytes, dos);
            } finally {
                hdos.close();
            }
        }
    } catch (IOException ex) {
        throw ex;
    } catch (GemFireSecurityException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new AuthenticationFailedException("HandShake failed in Diffie-Hellman key exchange", ex);
    }
    dos.flush();
}