Example usage for java.io ByteArrayInputStream close

List of usage examples for java.io ByteArrayInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closing a ByteArrayInputStream has no effect.

Usage

From source file:br.org.indt.ndg.server.client.TemporaryOpenRosaBussinessDelegate.java

/********** Uploading OpenRosa Surveys and Results **********/

public boolean parseAndPersistSurvey(InputStreamReader inputStreamReader, String contentType)
        throws IOException {
    String surveyString = parseMultipartEncodedFile(inputStreamReader, contentType, "filename");
    String surveyId = null;//from   ww w .j a  v  a 2  s  .c om
    String surveyIdOriginal = null;

    Document surveyDomDocument = null;
    ByteArrayInputStream streamToParse = new ByteArrayInputStream(surveyString.getBytes("UTF-8"));
    try {
        surveyDomDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(streamToParse);
    } catch (SAXException e) {
        e.printStackTrace();
        return false;
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        return false;
    } finally {
        streamToParse.close();
    }

    NodeList dataNodeList = surveyDomDocument.getElementsByTagName("data");
    if (dataNodeList.getLength() != 1) {
        return false; // there MUST be exactly 1 <data> node
    } else {
        Element dataElement = (Element) dataNodeList.item(0);
        Random rand = new Random(System.currentTimeMillis());
        int newId = rand.nextInt(Integer.MAX_VALUE);
        surveyId = String.valueOf(newId);
        surveyIdOriginal = dataElement.getAttribute("id");
        dataElement.setAttribute("id", String.valueOf(newId));
        StringWriter stringWriter = null;
        try {
            Source source = new DOMSource(surveyDomDocument);
            stringWriter = new StringWriter();
            Result result = new StreamResult(stringWriter);
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "no");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            transformer.transform(source, result);
            surveyString = stringWriter.getBuffer().toString();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            stringWriter.close();
        }
        log.info("========================");
        log.info("Original Survey Id: " + surveyIdOriginal);
        log.info("New Survey Id: " + surveyId);
        log.info("========================");
    }
    return persistSurvey(surveyString, surveyId, surveyIdOriginal);
}

From source file:org.kuali.coeus.s2sgen.impl.generate.S2SBaseFormGenerator.java

/**
 * Sort the attachments./*  w w  w.  j  a  v  a  2  s .  c  o m*/
 * @param byteArrayInputStream
 */
public void sortAttachments(ByteArrayInputStream byteArrayInputStream) {
    List<String> attachmentNameList = new ArrayList<String>();
    List<AttachmentData> attacmentList = getAttachments();
    List<AttachmentData> tempAttacmentList = new ArrayList<AttachmentData>();

    try {
        DocumentBuilderFactory domParserFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder domParser = domParserFactory.newDocumentBuilder();
        Document document = domParser.parse(byteArrayInputStream);
        byteArrayInputStream.close();
        NodeList fileLocationList = document.getElementsByTagName(NARRATIVE_ATTACHMENT_FILE_LOCATION);

        for (int itemLocation = 0; itemLocation < fileLocationList.getLength(); itemLocation++) {
            String attachmentName = fileLocationList.item(itemLocation).getAttributes().item(0).getNodeValue();
            String[] name = attachmentName.split(KEY_VALUE_SEPARATOR);
            String fileName = name[name.length - 1];
            attachmentNameList.add(fileName);
        }
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }

    for (String attachmentName : attachmentNameList) {
        for (AttachmentData attachment : attacmentList) {
            String[] names = attachment.getContentId().split(KEY_VALUE_SEPARATOR);
            String fileName = names[names.length - 1];
            if (fileName.equalsIgnoreCase(attachmentName)) {
                tempAttacmentList.add(attachment);
            }
        }
    }
    if (tempAttacmentList.size() > 0) {
        attachments.clear();
        for (AttachmentData tempAttachment : tempAttacmentList) {
            attachments.add(tempAttachment);
        }
    }
}

From source file:com.dream.library.utils.AbFileUtil.java

/**
 * ??byte[]./*from   ww  w. jav a 2 s  .co  m*/
 *
 * @param imgByte       byte[]
 * @param fileName      ?????.jpg
 * @param type          ???AbConstant
 * @param desiredWidth  
 * @param desiredHeight 
 * @return Bitmap 
 */
public static Bitmap getBitmapFromByte(byte[] imgByte, String fileName, int type, int desiredWidth,
        int desiredHeight) {
    FileOutputStream fos = null;
    DataInputStream dis = null;
    ByteArrayInputStream bis = null;
    Bitmap bitmap = null;
    File file = null;
    try {
        if (imgByte != null) {

            file = new File(AbDirUtils.getDownloadDir(), fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            int readLength = 0;
            bis = new ByteArrayInputStream(imgByte);
            dis = new DataInputStream(bis);
            byte[] buffer = new byte[1024];

            while ((readLength = dis.read(buffer)) != -1) {
                fos.write(buffer, 0, readLength);
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                }
            }
            fos.flush();

            bitmap = getBitmapFromSD(file, type, desiredWidth, desiredHeight);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dis != null) {
            try {
                dis.close();
            } catch (Exception e) {
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (Exception e) {
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (Exception e) {
            }
        }
    }
    return bitmap;
}

From source file:SortMixedRecordDataTypeExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);//from   w w w.j  a  va2  s .co  m
        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[] = { "Mary", "Bob", "Adam" };
            int outputInteger[] = { 15, 10, 5 };
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            for (int x = 0; x < 3; x++) {
                outputDataStream.writeUTF(outputString[x]);
                outputDataStream.writeInt(outputInteger[x]);
                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 = new String[3];
            int z = 0;
            byte[] byteInputData = new byte[300];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            StringBuffer buffer = new StringBuffer();
            comparator = new Comparator();
            recordEnumeration = recordstore.enumerateRecords(null, comparator, false);
            while (recordEnumeration.hasNextElement()) {
                recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                buffer.append(inputDataStream.readUTF());
                buffer.append(inputDataStream.readInt());
                buffer.append("\n");
                inputDataStream.reset();
            }
            alert = new Alert("Reading", buffer.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
            inputDataStream.close();
            inputStream.close();
        } 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");
                comparator.compareClose();
                recordEnumeration.destroy();
            } catch (Exception error) {
                alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
        }
    }
}

From source file:es.mityc.firmaJava.libreria.utilidades.Base64.java

/**
 * Attempts to decode Base64 data and deserialize a Java
 * Object within. Returns <tt>null</tt> if there was an error.
 *
 * @param encodedObject The Base64 data to decode
 * @return The decoded and deserialized object
 * @since 1.5//from  w  w w. j a va2s. c o m
 */
public static Object decodeToObject(String encodedObject) {
    // Decode and gunzip if necessary
    byte[] objBytes = decode(encodedObject);

    ByteArrayInputStream bais = null;
    ObjectInputStream ois = null;
    Object obj = null;

    try {
        bais = new ByteArrayInputStream(objBytes);
        ois = new ObjectInputStream(bais);

        obj = ois.readObject();
    } // end try
    catch (IOException e) {
        log.error(e);
        obj = null;
    } // end catch
    catch (ClassNotFoundException e) {
        log.error(e);
        obj = null;
    } // end catch
    finally {
        try {
            bais.close();
        } catch (Exception e) {
            log.error(e);
        }
        try {
            ois.close();
        } catch (Exception e) {
            log.error(e);
        }
    } // end finally

    return obj;
}

From source file:org.ms123.common.importing.BaseImportingServiceImpl.java

protected synchronized String detectCharset(byte[] content) throws Exception {
    if (content == null || content.length == 0)
        return null;
    ByteArrayInputStream bis = new ByteArrayInputStream(content);
    try {//from  ww  w .jav  a  2 s  .c  o  m
        org.apache.tika.parser.txt.UniversalEncodingDetector ued = new org.apache.tika.parser.txt.UniversalEncodingDetector();
        Charset charset = ued.detect(bis, new org.apache.tika.metadata.Metadata());
        System.out.println("detectCharset:" + charset);
        return charset.toString();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        bis.close();
    }
    return "unknown";
}

From source file:org.apache.hadoop.hbase.crosssite.CrossSiteZNodes.java

/**
 * Gets the table descriptor for the table descriptor znode.
 * /*from ww  w.jav a  2s  .co  m*/
 * @param tableName
 * @return
 * @throws KeeperException
 * @throws IOException
 */
public HTableDescriptor getTableDesc(String tableName) throws KeeperException, IOException {
    // Do table existence check
    getTableState(tableName);
    byte[] data = ZKUtil.getData(this.zkw, getTableDescZNode(tableName));
    ByteArrayInputStream stream = new ByteArrayInputStream(data);
    DataInput in = new DataInputStream(stream);
    HTableDescriptor htd = new HTableDescriptor();
    htd.readFields(in);
    stream.close();
    return htd;
}

From source file:org.apache.hadoop.hbase.crosssite.CrossSiteZNodes.java

/**
 * Gets proposed HTD written to zk./*  w  ww  . j a  v  a  2  s . com*/
 * 
 * @param tableName
 * @return
 * @throws KeeperException
 * @throws IOException
 */
public HTableDescriptor getProposedTableDesc(String tableName) throws KeeperException, IOException {
    byte[] data = ZKUtil.getData(zkw,
            ZKUtil.joinZNode(getTableZNode(tableName), TABLE_PROPOSED_DESC_ZNODE_NAME));
    if (data == null)
        return null;
    ByteArrayInputStream stream = new ByteArrayInputStream(data);
    DataInput in = new DataInputStream(stream);
    HTableDescriptor htd = new HTableDescriptor();
    htd.readFields(in);
    stream.close();
    return htd;
}

From source file:org.dasein.cloud.azure.AzureMethod.java

public @Nonnull Document parseResponse(@Nonnull String responseBody, boolean withWireLogging)
        throws CloudException, InternalException {
    try {//from   w ww  .j  a va2  s  . c o  m
        if (wire != null && wire.isDebugEnabled()) {
            String[] lines = responseBody.split("\n");

            if (lines.length < 1) {
                lines = new String[] { responseBody };
            }
            for (String l : lines) {
                wire.debug(l);
            }
            wire.debug("");
        }
        ByteArrayInputStream bas = new ByteArrayInputStream(responseBody.getBytes());

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder parser = factory.newDocumentBuilder();
        Document doc = parser.parse(bas);

        bas.close();
        return doc;
    } catch (IOException e) {
        throw new CloudException(e);
    } catch (ParserConfigurationException e) {
        throw new CloudException(e);
    } catch (SAXException e) {
        throw new CloudException(e);
    }
}

From source file:org.apache.hadoop.hbase.crosssite.CrossSiteZNodes.java

/**
 * Gets the table descriptor for the table descriptor znode.
 * //w  ww .j a v  a  2s .  c  o  m
 * @param tableName
 * @return null if the table is not existent
 * @throws KeeperException
 * @throws IOException
 */
public HTableDescriptor getTableDescAllowNull(String tableName) throws KeeperException, IOException {
    // Do table existence check
    byte[] stateData = ZKUtil.getData(this.zkw, getTableStateZNode(tableName));
    if (stateData == null) {
        return null;
    }
    byte[] data = ZKUtil.getData(this.zkw, getTableDescZNode(tableName));
    ByteArrayInputStream stream = new ByteArrayInputStream(data);
    DataInput in = new DataInputStream(stream);
    HTableDescriptor htd = new HTableDescriptor();
    htd.readFields(in);
    stream.close();
    return htd;
}