List of usage examples for java.io ByteArrayInputStream close
public void close() throws IOException
From source file:com.joliciel.jochre.graphics.GraphicsDaoJdbc.java
@Override public void loadOriginalImage(JochreImageInternal jochreImage) { NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(this.getDataSource()); String sql = "SELECT image_image FROM ocr_image WHERE image_id=:image_id"; MapSqlParameterSource paramSource = new MapSqlParameterSource(); paramSource.addValue("image_id", jochreImage.getId()); LOG.debug(sql);//from www . ja va2s. c o m logParameters(paramSource); byte[] pixels = (byte[]) jt.query(sql, paramSource, new ResultSetExtractor() { @Override public Object extractData(ResultSet rs) throws SQLException, DataAccessException { if (rs.next()) { byte[] pixels = rs.getBytes("image_image"); return pixels; } else { return null; } } }); ByteArrayInputStream is = new ByteArrayInputStream(pixels); BufferedImage image; try { image = ImageIO.read(is); is.close(); } catch (IOException e) { throw new RuntimeException(e); } jochreImage.setOriginalImageDB(image); }
From source file:org.bibalex.gallery.model.BAGGalleryAbstract.java
public void loadTempXml() throws BAGException { if (this.tempXml != null) { throw new BAGException("Already loaded"); }//ww w. ja va 2 s. c o m SAXBuilder saxBuilder = new SAXBuilder(); saxBuilder.setFeature("http://xml.org/sax/features/validation", false); saxBuilder.setFeature("http://xml.org/sax/features/namespaces", true); saxBuilder.setFeature("http://xml.org/sax/features/namespace-prefixes", true); // Unsupported: saxBuilder.setFeature("http://xml.org/sax/features/xmlns-uris", false); String metaDataUrl = this.getMetaGalleryFileUrlStr(); // URLPathStrUtils.appendParts(this.metaGalleryRoot, FILENAME_GALLERY_METADATA_XML); try { ByteArrayOutputStream remoteFileOS = new ByteArrayOutputStream(); ByteArrayInputStream metaGalleryIn = null; try { BAGStorage.readRemoteFile(metaDataUrl, remoteFileOS); metaGalleryIn = new ByteArrayInputStream(remoteFileOS.toByteArray()); this.tempXml = saxBuilder.build(metaGalleryIn); } finally { try { remoteFileOS.close(); metaGalleryIn.close(); } catch (IOException e) { throw new BAGException(e); } } } catch (JDOMException e) { throw new BAGException(e); } catch (IOException e) { throw new BAGException(e); } }
From source file:J2MEMixedRecordEnumerationExample.java
public void commandAction(Command command, Displayable displayable) { if (command == exit) { destroyApp(true);/*ww w . j a v a 2s . c o m*/ notifyDestroyed(); } else if (command == start) { try { recordstore = RecordStore.openRecordStore("myRecordStore", true); byte[] outputRecord; String outputString[] = { "First Record", "Second Record", "Third Record" }; int outputInteger[] = { 15, 10, 5 }; boolean outputBoolean[] = { true, false, true }; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DataOutputStream outputDataStream = new DataOutputStream(outputStream); for (int x = 0; x < 3; x++) { outputDataStream.writeUTF(outputString[x]); outputDataStream.writeBoolean(outputBoolean[x]); outputDataStream.writeInt(outputInteger[x]); outputDataStream.flush(); outputRecord = outputStream.toByteArray(); recordstore.addRecord(outputRecord, 0, outputRecord.length); } outputStream.reset(); outputStream.close(); outputDataStream.close(); StringBuffer buffer = new StringBuffer(); byte[] byteInputData = new byte[300]; ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData); DataInputStream inputDataStream = new DataInputStream(inputStream); recordEnumeration = recordstore.enumerateRecords(null, null, false); while (recordEnumeration.hasNextElement()) { recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0); buffer.append(inputDataStream.readUTF()); buffer.append("\n"); buffer.append(inputDataStream.readBoolean()); buffer.append("\n"); buffer.append(inputDataStream.readInt()); buffer.append("\n"); alert = new Alert("Reading", buffer.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } inputStream.close(); recordstore.closeRecordStore(); if (RecordStore.listRecordStores() != null) { RecordStore.deleteRecordStore("myRecordStore"); 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:fr.dyade.aaa.util.MySqlDBRepository.java
/** * Loads the object.//from w w w. ja v a 2s . c o m * * @return The loaded object or null if it does not exist. * @throws ClassNotFoundException */ public Object loadobj(String dirName, String name) throws IOException, ClassNotFoundException { if (logger.isLoggable(BasicLevel.DEBUG)) logger.log(BasicLevel.DEBUG, "loadobj, b4 load call"); byte[] content = load(dirName, name); if (logger.isLoggable(BasicLevel.DEBUG)) logger.log(BasicLevel.DEBUG, "loadobj, after load call"); ByteArrayInputStream bis = new ByteArrayInputStream(content); ObjectInputStream ois = new ObjectInputStream(bis); try { Object obj = ois.readObject(); return obj; } catch (Exception e) { String exceptionString = e.toString(); if (exceptionString.indexOf("KNOWN PROBLEM") == -1) { e.printStackTrace(); } throw new IOException(e.getMessage()); } finally { ois.close(); bis.close(); } }
From source file:com.vkassin.mtrade.Common.java
public static String generalWebServiceCall(String urlStr, ContentHandler handler) { String errorMsg = ""; try {//from w w w. ja va 2 s.co m URL url = new URL(urlStr); HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); urlc.setRequestProperty("User-Agent", "Android Application: aMTrade"); urlc.setRequestProperty("Connection", "close"); // urlc.setRequestProperty("Accept-Charset", "windows-1251"); // urlc.setRequestProperty("Accept-Charset", // "windows-1251,utf-8;q=0.7,*;q=0.7"); urlc.setRequestProperty("Accept-Charset", "utf-8"); urlc.setConnectTimeout(1000 * 5); // mTimeout is in seconds urlc.setDoInput(true); urlc.connect(); if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) { // Get a SAXParser from the SAXPArserFactory. SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); // Get the XMLReader of the SAXParser we created. XMLReader xr = sp.getXMLReader(); // Apply the handler to the XML-Reader xr.setContentHandler(handler); // Parse the XML-data from our URL. InputStream is = urlc.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(500); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } ByteArrayInputStream bais = new ByteArrayInputStream(baf.toByteArray()); // Reader isr = new InputStreamReader(bais, "windows-1251"); Reader isr = new InputStreamReader(bais, "utf-8"); InputSource ist = new InputSource(); // ist.setEncoding("UTF-8"); ist.setCharacterStream(isr); xr.parse(ist); // Parsing has finished. bis.close(); baf.clear(); bais.close(); is.close(); } urlc.disconnect(); } catch (SAXException e) { // All is OK :) } catch (MalformedURLException e) { Log.e(TAG, errorMsg = "MalformedURLException"); } catch (IOException e) { Log.e(TAG, errorMsg = "IOException"); } catch (ParserConfigurationException e) { Log.e(TAG, errorMsg = "ParserConfigurationException"); } catch (ArrayIndexOutOfBoundsException e) { Log.e(TAG, errorMsg = "ArrayIndexOutOfBoundsException"); } return errorMsg; }
From source file:com.t_oster.liblasercut.drivers.LaosCutter.java
@Override public void sendJob(LaserJob job, ProgressListener pl, List<String> warnings) throws IllegalJobException, Exception { currentFrequency = -1;// www . j a va 2 s . co m currentPower = -1; currentSpeed = -1; currentFocus = 0; currentPurge = false; currentVentilation = false; pl.progressChanged(this, 0); BufferedOutputStream out; ByteArrayOutputStream buffer = null; pl.taskChanged(this, "checking job"); checkJob(job); job.applyStartPoint(); if (!useTftp) { pl.taskChanged(this, "connecting"); Socket connection = new Socket(); connection.connect(new InetSocketAddress(hostname, port), 3000); out = new BufferedOutputStream(connection.getOutputStream()); pl.taskChanged(this, "sending"); } else { buffer = new ByteArrayOutputStream(); out = new BufferedOutputStream(buffer); pl.taskChanged(this, "buffering"); } this.writeJobCode(job, out, pl); if (this.isUseTftp()) { pl.taskChanged(this, "connecting"); TFTPClient tftp = new TFTPClient(); tftp.setDefaultTimeout(5000); //open a local UDP socket tftp.open(); pl.taskChanged(this, "sending"); ByteArrayInputStream bain = new ByteArrayInputStream(buffer.toByteArray()); tftp.sendFile(job.getName().replace(" ", "") + ".lgc", TFTP.BINARY_MODE, bain, this.getHostname(), this.getPort()); tftp.close(); bain.close(); if (debugFilename != null && !"".equals(debugFilename)) { pl.taskChanged(this, "writing " + debugFilename); FileOutputStream o = new FileOutputStream(new File(debugFilename)); o.write(buffer.toByteArray()); o.close(); } pl.taskChanged(this, "sent."); } pl.progressChanged(this, 100); }
From source file:loci.formats.in.KLBReader.java
/** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) *//*from ww w . j a v a2 s. co m*/ @Override public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { in.close(); String fileName; int[] currentCoords = getZCTCoords(no); int currentSeries = getSeries(); Set<String> keys = filelist.keySet(); fileName = filelist.get(keys.toArray()[currentSeries])[currentCoords[2]][currentCoords[1]]; in = new RandomAccessInputStream(fileName); FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); //As number of offsets can be greater than INT_MAX only storing enough required for given plane //New offsets are read from header each time openBytes is called reCalculateBlockOffsets(no); //Calculate block offsets for tiled reading int xBlockOffset = x % dims_blockSize[0]; int yBlockOffset = y % dims_blockSize[1]; int xBlockRemainder = dims_blockSize[0] - xBlockOffset; int yBlockRemainder = dims_blockSize[1] - yBlockOffset; int xNumBlocks = 1 + (int) (Math.ceil((float) (w - xBlockRemainder) / dims_blockSize[0])); int yNumBlocks = 1 + (int) (Math.ceil((float) (h - yBlockRemainder) / dims_blockSize[1])); int blocksPerImageRow = (int) (Math.ceil((float) getSizeX() / dims_blockSize[0])); int xBlockStartIndex = 0; if (x > 0) xBlockStartIndex = x / dims_blockSize[0]; int yBlockStartIndex = 0; if (y > 0) yBlockStartIndex = y / dims_blockSize[1]; int bytesPerPixel = FormatTools.getBytesPerPixel(getPixelType()); int[] dimsBlock = new int[KLB_DATA_DIMS]; //Number of blocks on each dimension int[] coordBlock = new int[KLB_DATA_DIMS]; //Coordinates int[] blockSizeAux = new int[KLB_DATA_DIMS]; //Block sizes taking into account border cases for (int ii = 0; ii < KLB_DATA_DIMS; ii++) { dimsBlock[ii] = (int) Math.ceil((float) dims_xyzct[ii] / (float) dims_blockSize[ii]); } long compressedBlockSize = blockOffsets[1] - blockOffsets[0]; int outputOffset = 0; for (int yy = 0; yy < yNumBlocks; yy++) { for (int xx = 0; xx < xNumBlocks; xx++) { //calculate coordinate (in block space) int blockId = (yBlockStartIndex + yy) * blocksPerImageRow + xBlockStartIndex + xx; for (int ii = 0; ii < KLB_DATA_DIMS; ii++) { //parsing coordinates to image space (not block anymore) if (ii == 1) { coordBlock[1] = blockId / dimsBlock[0]; } else { coordBlock[ii] = blockId % dimsBlock[ii]; } coordBlock[ii] *= dims_blockSize[ii]; } // Calculate block size in case we had border block blockSizeAux[0] = Math.min(dims_blockSize[0], (x + w - coordBlock[0])); blockSizeAux[0] = Math.min(blockSizeAux[0], coordBlock[0] + dims_blockSize[0] - x); blockSizeAux[1] = Math.min(dims_blockSize[1], (y + h - coordBlock[1])); blockSizeAux[1] = Math.min(blockSizeAux[1], coordBlock[1] + dims_blockSize[1] - y); for (int ii = 2; ii < KLB_DATA_DIMS; ii++) { blockSizeAux[ii] = Math.min(dims_blockSize[ii], (dims_xyzct[ii] - coordBlock[ii])); } int blockSizeBytes = bytesPerPixel; for (int ii = 0; ii < KLB_DATA_DIMS; ii++) { if (ii == 0 && coordBlock[ii] + blockSizeAux[ii] >= dims_xyzct[ii]) { blockSizeBytes *= blockSizeAux[0]; } else { blockSizeBytes *= dims_blockSize[ii]; } } compressedBlockSize = blockOffsets[blockId + 1] - blockOffsets[blockId]; long offset = blockOffsets[blockId]; //Seek to start of block in.seek((long) (headerSize + offset)); //Read compressed block byte[] block = new byte[(int) compressedBlockSize]; in.read(block); //Decompress block if (compressionType == COMPRESSION_BZIP2) { // Discard first two bytes of BZIP2 header byte[] tempPixels = block; block = new byte[tempPixels.length - 2]; System.arraycopy(tempPixels, 2, block, 0, block.length); try { ByteArrayInputStream bais = new ByteArrayInputStream(block); CBZip2InputStream bzip = new CBZip2InputStream(bais); block = new byte[blockSizeBytes]; bzip.read(block, 0, block.length); tempPixels = null; bais.close(); bzip.close(); bais = null; bzip = null; } catch (IOException e) { LOGGER.error("IOException while decompressing block {}", xx); throw e; } } else if (compressionType == COMPRESSION_ZLIB) { CodecOptions options = new CodecOptions(); block = new ZlibCodec().decompress(block, options); } try { int imageRowSize = w * bytesPerPixel; int blockRowSize = blockSizeAux[0] * bytesPerPixel; int fullBlockRowSize = dims_blockSize[0] * bytesPerPixel; // Location in output buffer to copy block outputOffset = (imageRowSize * (coordBlock[1] - y)) + ((coordBlock[0] - x) * bytesPerPixel); if (coordBlock[0] < x && blockSizeAux[0] != dims_blockSize[0]) outputOffset += (dims_blockSize[0] - blockSizeAux[0]) * bytesPerPixel; if (coordBlock[1] < y && blockSizeAux[1] != dims_blockSize[1]) outputOffset = (coordBlock[0] - x) * bytesPerPixel; if (coordBlock[1] < y && coordBlock[0] < x && blockSizeAux[1] != dims_blockSize[1] && blockSizeAux[0] != dims_blockSize[0]) outputOffset = 0; // Location within the block for required XY plane int inputOffset = (coordBlock[2] % dims_blockSize[2]) * blockRowSize * blockSizeAux[1]; if (coordBlock[0] < x && coordBlock[1] < y && blockSizeAux[1] != dims_blockSize[1] && blockSizeAux[0] != dims_blockSize[0]) inputOffset += ((dims_blockSize[0] * (dims_blockSize[1] - blockSizeAux[1])) + (x - coordBlock[0])) * bytesPerPixel; // Partial block at the start of x tile else if (coordBlock[0] < x && blockSizeAux[0] != dims_blockSize[0]) inputOffset += (dims_blockSize[0] - blockSizeAux[0]) * bytesPerPixel; // Partial block at the start of y tile else if (coordBlock[1] < y && blockSizeAux[1] != dims_blockSize[1] && coordBlock[0] + blockSizeAux[0] == dims_xyzct[0]) inputOffset += blockSizeAux[0] * (dims_blockSize[1] - blockSizeAux[1]) * bytesPerPixel; else if (coordBlock[1] < y && blockSizeAux[1] != dims_blockSize[1]) inputOffset += dims_blockSize[0] * (dims_blockSize[1] - blockSizeAux[1]) * bytesPerPixel; inputOffset += (coordBlock[3] % dims_blockSize[3]) * blockRowSize * blockSizeAux[1] * blockSizeAux[2]; inputOffset += (coordBlock[4] % dims_blockSize[4]) * blockRowSize * blockSizeAux[1] * blockSizeAux[2] * blockSizeAux[3]; // If its the last block in a row then use the corrected rowSize if (coordBlock[0] + blockSizeAux[0] == dims_xyzct[0]) { fullBlockRowSize = blockRowSize; } // Copy row at a time from decompressed block to output buffer for (int numRows = 0; numRows < blockSizeAux[1]; numRows++) { int destPos = outputOffset + (numRows * imageRowSize); if (destPos + blockRowSize <= buf.length) { System.arraycopy(block, inputOffset + (numRows * fullBlockRowSize), buf, destPos, blockRowSize); } } } catch (Exception e) { throw new FormatException( "Exception caught while copying decompressed block data to output buffer : " + e); } } } return buf; }
From source file:org.ms123.common.importing.BaseImportingServiceImpl.java
protected synchronized String detectFileType(byte[] content) throws Exception { if (content == null || content.length == 0) return null; ByteArrayInputStream bis = new ByteArrayInputStream(content); try {/*from w w w. j a va2s. c o m*/ Tika tika = new Tika(); String ftype = tika.detect(bis); System.out.println("getFileModel.ftype:" + ftype); return ftype; } catch (Exception e) { e.printStackTrace(); } finally { bis.close(); } return "unknown"; }
From source file:SearchMixedRecordDataTypeExample.java
public void commandAction(Command command, Displayable displayable) { if (command == exit) { destroyApp(true);/* w w w.j a v a2s. 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[] = { "Adam", "Bob", "Mary" }; 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; byte[] byteInputData = new byte[300]; ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData); DataInputStream inputDataStream = new DataInputStream(inputStream); if (recordstore.getNumRecords() > 0) { filter = new Filter("Mary"); recordEnumeration = recordstore.enumerateRecords(filter, null, false); while (recordEnumeration.hasNextElement()) { recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0); inputString = inputDataStream.readUTF() + " " + inputDataStream.readInt(); alert = new Alert("Reading", inputString, null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } } 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"); filter.filterClose(); 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:com.verisign.epp.codec.verificationcode.EPPEncodedSignedCodeValue.java
/** * Creates an <code>EPPEncodedSignedCodeValue</code> that is initialized by * decoding the input <code>byte[]</code>. * //from w w w .j a v a2 s . co m * @param aEncodedSignedCodeArray * <code>byte[]</code> to decode the attribute values * @throws EPPDecodeException * Error decoding the input <code>byte[]</code>. */ public EPPEncodedSignedCodeValue(byte[] aEncodedSignedCodeArray) throws EPPDecodeException { cat.debug("EPPSignedCode(byte[]): enter"); byte[] signedCodeXML = null; Element elm; ByteArrayInputStream is = null; try { is = new ByteArrayInputStream(aEncodedSignedCodeArray); DocumentBuilder parser = new EPPSchemaCachingParser(); // Disable the validation parser.setErrorHandler(null); Document doc = parser.parse(is); elm = doc.getDocumentElement(); String base64SignedCode = EPPUtil.getTextContent(elm); signedCodeXML = Base64.decodeBase64(base64SignedCode); } catch (Exception ex) { throw new EPPDecodeException("Error decoding signed code array: " + ex); } finally { if (is != null) { try { is.close(); is = null; } catch (IOException e) { } } } super.decode(signedCodeXML); cat.debug("EPPSignedCode.decode(byte[]): exit"); }