Example usage for java.io DataOutputStream writeShort

List of usage examples for java.io DataOutputStream writeShort

Introduction

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

Prototype

public final void writeShort(int v) throws IOException 

Source Link

Document

Writes a short to the underlying output stream as two bytes, high byte first.

Usage

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w w w . ja  va2s. c  o  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 {

    long startTime = System.currentTimeMillis();

    IMPService impService = (IMPService) appCtx.getBean("impService");
    StudyProcessor studyProcessor = (StudyProcessor) appCtx.getBean("studyProcessor");

    InputStream input = request.getInputStream();
    OutputStream output = response.getOutputStream();

    ZOutputStream zOutput = null; // Wrap the streams for compression

    // Wrap the streams so for logical types
    DataInputStream dataInput = null;
    DataOutputStream dataOutput = null;

    // Set the MIME type so clients don't misinterpret
    response.setContentType("application/octet-stream");

    try {
        zOutput = new ZOutputStream(output, JZlib.Z_BEST_COMPRESSION);
        dataInput = new DataInputStream(input);
        dataOutput = new DataOutputStream(zOutput);

        if (rawUploadLog.isInfoEnabled()) {
            byte[] rawPayload = IOUtils.toByteArray(dataInput);
            String hexEncodedPayload = Hex.encodeHexString(rawPayload);
            rawUploadLog.info(hexEncodedPayload);
            // Replace the original input stream with one using read payload
            dataInput.close();
            dataInput = new DataInputStream(new ByteArrayInputStream(rawPayload));
        }

        String name = dataInput.readUTF();
        String password = dataInput.readUTF();
        String serializer = dataInput.readUTF();
        String locale = dataInput.readUTF();

        byte action = dataInput.readByte();

        // TODO Authentication of usename and password. Possible M6
        // enhancement
        log.info("uploading: name=" + name + ", password=" + password + ", serializer=" + serializer
                + ", locale=" + locale + ", action=" + action);

        EpihandyXformSerializer serObj = new EpihandyXformSerializer();
        serObj.addDeserializationListener(studyProcessor);

        try {
            Map<Integer, String> formVersionMap = formService.getXForms();
            serObj.deserializeStudiesWithEvents(dataInput, formVersionMap);
        } catch (FormNotFoundException fne) {
            String msg = "failed to deserialize forms: ";
            log.error(msg + fne.getMessage());
            dataOutput.writeByte(ResponseHeader.STATUS_FORMS_STALE);
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        } catch (Exception e) {
            String msg = "failed to deserialize forms";
            log.error(msg, e);
            dataOutput.writeByte(ResponseHeader.STATUS_ERROR);
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        String[][] studyForms = studyProcessor.getConvertedStudies();
        int numForms = studyProcessor.getNumForms();

        log.debug("upload contains: studies=" + studyForms.length + ", forms=" + numForms);

        // Starting processing here, only process until we run out of time
        int processedForms = 0;
        int faultyForms = 0;
        if (studyForms != null && numForms > 0) {
            formprocessing: for (int i = 0; i < studyForms.length; i++) {
                for (int j = 0; j < studyForms[i].length; j++, processedForms++) {

                    if (maxProcessingTime > 0 && System.currentTimeMillis() - startTime > maxProcessingTime)
                        break formprocessing;

                    try {
                        studyForms[i][j] = impService.processXForm(studyForms[i][j]);
                    } catch (Exception ex) {
                        log.error("processing form failed", ex);
                        studyForms[i][j] = ex.getMessage();
                    }
                    if (!impService.getFormProcessSuccess().equalsIgnoreCase(studyForms[i][j])) {
                        faultyForms++;
                    }
                }
            }
        }

        // Write out usual upload response
        dataOutput.writeByte(ResponseHeader.STATUS_SUCCESS);

        dataOutput.writeInt(processedForms);
        dataOutput.writeInt(faultyForms);

        for (int s = 0; s < studyForms.length; s++) {
            for (int f = 0; f < studyForms[s].length; f++) {
                if (!impService.getFormProcessSuccess().equalsIgnoreCase(studyForms[s][f])) {
                    dataOutput.writeByte((byte) s);
                    dataOutput.writeShort((short) f);
                    dataOutput.writeUTF(studyForms[s][f]);
                }
            }
        }

        response.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        log.error("failure during upload", e);
    } finally {
        if (dataOutput != null)
            dataOutput.flush();
        if (zOutput != null)
            zOutput.finish();
        response.flushBuffer();
    }
}

From source file:org.ramadda.repository.database.DatabaseManager.java

/**
 * _more_/*from  w  ww  .  jav a2s  . c o m*/
 *
 * @param os _more_
 * @param all _more_
 * @param actionId _more_
 *
 * @throws Exception _more_
 */
public void makeDatabaseCopy(OutputStream os, boolean all, Object actionId) throws Exception {

    XmlEncoder encoder = new XmlEncoder();
    DataOutputStream dos = new DataOutputStream(os);
    Connection connection = getConnection();
    try {
        HashSet<String> skip = new HashSet<String>();
        skip.add(Tables.SESSIONS.NAME);

        List<TableInfo> tableInfos = getTableInfos(connection, false);
        String xml = encoder.toXml(tableInfos, false);
        writeString(dos, xml);

        int rowCnt = 0;
        System.err.println("Exporting database");
        for (TableInfo tableInfo : tableInfos) {
            if (tableInfo.getName().equalsIgnoreCase("base")) {
                continue;
            }
            if (tableInfo.getName().equalsIgnoreCase("agggregation")) {
                continue;
            }
            if (tableInfo.getName().equalsIgnoreCase("entry")) {
                continue;
            }
            System.err.println("Exporting table: " + tableInfo.getName());
            List<ColumnInfo> columns = tableInfo.getColumns();
            List valueList = new ArrayList();
            Statement statement = execute("select * from " + tableInfo.getName(), 10000000, 0);
            SqlUtil.Iterator iter = getIterator(statement);
            ResultSet results;
            dos.writeInt(DUMPTAG_TABLE);
            writeString(dos, tableInfo.getName());
            if (skip.contains(tableInfo.getName().toLowerCase())) {
                continue;
            }
            while ((results = iter.getNext()) != null) {
                dos.writeInt(DUMPTAG_ROW);
                rowCnt++;
                if ((rowCnt % 1000) == 0) {
                    if (actionId != null) {
                        getActionManager().setActionMessage(actionId, "Written " + rowCnt + " database rows");
                    }
                    System.err.println("rows:" + rowCnt);
                }
                for (int i = 1; i <= columns.size(); i++) {
                    ColumnInfo colInfo = columns.get(i - 1);
                    int type = colInfo.getType();
                    if (type == ColumnInfo.TYPE_TIMESTAMP) {
                        Timestamp ts = results.getTimestamp(i);
                        if (ts == null) {
                            dos.writeLong((long) -1);
                        } else {
                            dos.writeLong(ts.getTime());
                        }
                    } else if (type == ColumnInfo.TYPE_VARCHAR) {
                        writeString(dos, results.getString(i));
                    } else if (type == ColumnInfo.TYPE_TIME) {
                        //TODO: What is the format of a type time?
                        //                            writeString(dos, results.getString(i));
                    } else if (type == ColumnInfo.TYPE_INTEGER) {
                        writeInteger(dos, (Integer) results.getObject(i));
                    } else if (type == ColumnInfo.TYPE_DOUBLE) {
                        writeDouble(dos, (Double) results.getObject(i));
                    } else if (type == ColumnInfo.TYPE_CLOB) {
                        writeString(dos, results.getString(i));
                    } else if (type == ColumnInfo.TYPE_BLOB) {
                        writeString(dos, results.getString(i));
                    } else if (type == ColumnInfo.TYPE_BIGINT) {
                        writeLong(dos, results.getLong(i));
                    } else if (type == ColumnInfo.TYPE_SMALLINT) {
                        dos.writeShort(results.getShort(i));
                    } else if (type == ColumnInfo.TYPE_TINYINT) {
                        //TODO:
                        //dos.write(results.getChar(i));
                    } else {
                        Object object = results.getObject(i);

                        throw new IllegalArgumentException(
                                "Unknown type:" + type + "  c:" + object.getClass().getName());
                    }
                }
            }
        }
        System.err.println("Wrote " + rowCnt + " rows");
    } finally {
        closeConnection(connection);
    }
    //Write the end tag
    dos.writeInt(DUMPTAG_END);
    IOUtil.close(dos);

}