List of usage examples for java.io ByteArrayInputStream close
public void close() throws IOException
From source file:org.jlibrary.servlet.JLibraryStartupAxisServlet.java
private void processWS(String url) { logger.info("Processing {" + url + "}"); try {/*from www. ja va 2 s .c o m*/ InputStream is = getClass().getClassLoader().getResourceAsStream(url); byte[] array = IOUtils.toByteArray(is); ByteArrayInputStream bais = new ByteArrayInputStream(array); AxisEngine engine = getEngine(); Document doc = XMLUtils.newDocument(bais); WSDDDocument wsddDoc = new WSDDDocument(doc.getDocumentElement()); EngineConfiguration config = engine.getConfig(); if (config instanceof WSDDEngineConfiguration) { WSDDDeployment deployment = ((WSDDEngineConfiguration) config).getDeployment(); wsddDoc.deploy(deployment); } engine.refreshGlobalOptions(); engine.saveConfiguration(); bais.close(); is.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } }
From source file:WriteReadMixedDataTypesExample.java
public void commandAction(Command command, Displayable displayable) { if (command == exit) { destroyApp(true);/* w ww . j av a 2 s. c o 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 = "First Record"; int outputInteger = 15; boolean outputBoolean = true; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DataOutputStream outputDataStream = new DataOutputStream(outputStream); outputDataStream.writeUTF(outputString); outputDataStream.writeBoolean(outputBoolean); outputDataStream.writeInt(outputInteger); 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 = null; int inputInteger = 0; boolean inputBoolean = false; byte[] byteInputData = new byte[100]; ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData); DataInputStream inputDataStream = new DataInputStream(inputStream); for (int x = 1; x <= recordstore.getNumRecords(); x++) { recordstore.getRecord(x, byteInputData, 0); inputString = inputDataStream.readUTF(); inputBoolean = inputDataStream.readBoolean(); inputInteger = inputDataStream.readInt(); inputStream.reset(); } inputStream.close(); inputDataStream.close(); alert = new Alert("Reading", inputString + " " + inputInteger + " " + inputBoolean, null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } 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"); } catch (Exception error) { alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } } } }
From source file:com.connexta.arbitro.ctx.RequestCtxFactory.java
/** * Creates DOM representation of the XACML request * * @param request XACML request as a String object * @return XACML request as a DOM element * @throws ParsingException throws, if fails *//* w w w . j av a 2s. c o m*/ public Element getXacmlRequest(String request) throws ParsingException { Document doc; ByteArrayInputStream inputStream; inputStream = new ByteArrayInputStream(request.getBytes()); DocumentBuilderFactory builder = Balana.getInstance().getBuilder(); if (builder == null) { throw new ParsingException("DOM Builder can not be null"); } try { doc = builder.newDocumentBuilder().parse(inputStream); } catch (Exception e) { throw new ParsingException("DOM of request element can not be created from String", e); } finally { try { inputStream.close(); } catch (IOException e) { log.error("Error in closing input stream of XACML request"); } } return doc.getDocumentElement(); }
From source file:com.nokia.carbide.installpackages.InstallPackages.java
private URL getAvailablePackagesURL() throws Exception { URL url = null;// w ww . ja v a 2s . c o m // see if the file is local (Ed's hack for testing...) String masterFilePathStr = getMasterFilePath(); url = new URL(masterFilePathStr); if (url.getProtocol().equals("file")) { return url; } // else, read the file to a local temporary location GetMethod getMethod = new GetMethod(masterFilePathStr); HttpClient client = new HttpClient(); setProxyData(client, getMethod); client.getHttpConnectionManager().getParams().setConnectionTimeout(8000); int serverStatus = 0; byte[] responseBody; try { serverStatus = client.executeMethod(getMethod); responseBody = getMethod.getResponseBody(); } catch (Exception e) { // could be HttpException or IOException throw new Exception(e); } finally { getMethod.releaseConnection(); } // HTTP status codes: 2xx = Success if (serverStatus >= 200 && serverStatus < 300) { File tempDir = FileUtils.getTemporaryDirectory(); IPath path = new Path(tempDir.getAbsolutePath()); IPath masterFilePath = path.append(getMasterFileName()); File masterFile = masterFilePath.toFile(); if (masterFile.exists()) masterFile.delete(); FileOutputStream fos = new FileOutputStream(masterFile); BufferedOutputStream out = new BufferedOutputStream(fos); ByteArrayInputStream in = new ByteArrayInputStream(responseBody); boolean foundOpenBrace = false; int c; while ((c = in.read()) != -1) { if (c == '<') foundOpenBrace = true; if (foundOpenBrace) out.write(c); } out.close(); in.close(); url = masterFile.toURI().toURL(); return url; } return null; }
From source file:org.apache.lens.driver.hive.TestRemoteHiveDriver.java
/** * Test hive driver persistence.//from w w w . jav a 2s . c om * * @throws Exception the exception */ @Test public void testHiveDriverPersistence() throws Exception { System.out.println("@@@@ start_persistence_test"); Configuration driverConf = new Configuration(remoteConf); driverConf.addResource("drivers/hive/hive1/hivedriver-site.xml"); driverConf.setLong(HiveDriver.HS2_CONNECTION_EXPIRY_DELAY, 10000); driverConf.setBoolean(HiveDriver.HS2_CALCULATE_PRIORITY, false); final HiveDriver oldDriver = new HiveDriver(); oldDriver.configure(driverConf, "hive", "hive1"); queryConf.setBoolean(LensConfConstants.QUERY_ADD_INSERT_OVEWRITE, false); queryConf.setBoolean(LensConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, false); QueryContext ctx = createContext("USE " + dataBase, queryConf, oldDriver); oldDriver.execute(ctx); Assert.assertEquals(0, oldDriver.getHiveHandleSize()); String tableName = "test_hive_driver_persistence"; // Create some ops with a driver String createTable = "CREATE TABLE IF NOT EXISTS " + tableName + "(ID STRING)"; ctx = createContext(createTable, queryConf, oldDriver); oldDriver.execute(ctx); // Load some data into the table String dataLoad = "LOAD DATA LOCAL INPATH '" + TEST_DATA_FILE + "' OVERWRITE INTO TABLE " + tableName; ctx = createContext(dataLoad, queryConf, oldDriver); oldDriver.execute(ctx); queryConf.setBoolean(LensConfConstants.QUERY_ADD_INSERT_OVEWRITE, true); queryConf.setBoolean(LensConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, true); // Fire two queries QueryContext ctx1 = createContext("SELECT * FROM " + tableName, queryConf, oldDriver); oldDriver.executeAsync(ctx1); QueryContext ctx2 = createContext("SELECT ID FROM " + tableName, queryConf, oldDriver); oldDriver.executeAsync(ctx2); Assert.assertEquals(2, oldDriver.getHiveHandleSize()); byte[] ctx1bytes = persistContext(ctx1); byte[] ctx2bytes = persistContext(ctx2); // Write driver to stream ByteArrayOutputStream driverBytes = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(driverBytes); try { oldDriver.writeExternal(out); } finally { out.close(); driverBytes.close(); } // Create another driver from the stream ByteArrayInputStream driverInput = new ByteArrayInputStream(driverBytes.toByteArray()); HiveDriver newDriver = new HiveDriver(); newDriver.readExternal(new ObjectInputStream(driverInput)); newDriver.configure(driverConf, "hive", "hive1"); driverInput.close(); ctx1 = readContext(ctx1bytes, newDriver); ctx2 = readContext(ctx2bytes, newDriver); Assert.assertEquals(2, newDriver.getHiveHandleSize()); validateExecuteAsync(ctx1, DriverQueryState.SUCCESSFUL, true, false, newDriver); validateExecuteAsync(ctx2, DriverQueryState.SUCCESSFUL, true, false, newDriver); }
From source file:org.apache.nifi.processors.standard.util.TestJdbcCommon.java
@Test public void testBlob() throws Exception { try (final Statement stmt = con.createStatement()) { stmt.executeUpdate("CREATE TABLE blobtest (id INT, b BLOB(64 K))"); stmt.execute("INSERT INTO blobtest VALUES (41, NULL)"); PreparedStatement ps = con.prepareStatement("INSERT INTO blobtest VALUES (?, ?)"); ps.setInt(1, 42);//ww w . j a v a 2 s. c om final byte[] buffer = new byte[4002]; IntStream.range(0, 4002).forEach((i) -> buffer[i] = (byte) ((i % 10) + 65)); ByteArrayInputStream bais = new ByteArrayInputStream(buffer); // - set the value of the input parameter to the input stream ps.setBlob(2, bais, 4002); ps.execute(); bais.close(); final ResultSet resultSet = stmt.executeQuery("select * from blobtest"); final ByteArrayOutputStream outStream = new ByteArrayOutputStream(); JdbcCommon.convertToAvroStream(resultSet, outStream, false); final byte[] serializedBytes = outStream.toByteArray(); assertNotNull(serializedBytes); // Deserialize bytes to records final InputStream instream = new ByteArrayInputStream(serializedBytes); final DatumReader<GenericRecord> datumReader = new GenericDatumReader<>(); try (final DataFileStream<GenericRecord> dataFileReader = new DataFileStream<>(instream, datumReader)) { GenericRecord record = null; while (dataFileReader.hasNext()) { // Reuse record object by passing it to next(). This saves us from // allocating and garbage collecting many objects for files with // many items. record = dataFileReader.next(record); Integer id = (Integer) record.get("ID"); Object o = record.get("B"); if (id == 41) { assertNull(o); } else { assertNotNull(o); assertTrue(o instanceof ByteBuffer); assertEquals(4002, ((ByteBuffer) o).array().length); } } } } }
From source file:org.gephi.filters.GenericPropertyEditor.java
@Override public void setAsText(String text) throws IllegalArgumentException { if (!text.equals("null")) { ByteArrayInputStream bis = null; ObjectInputStream ois = null; try {/*from w ww. j av a2s . c o m*/ bis = new ByteArrayInputStream(Base64.decodeBase64(text)); ois = new ObjectInputStream(bis); val = ois.readObject(); } catch (Exception e) { e.printStackTrace(); ; } finally { if (ois != null) { try { ois.close(); } catch (IOException ex) { } } if (bis != null) { try { bis.close(); } catch (IOException ex) { } } } } }
From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java
public static Object readObjectFromXml(Element node) throws Exception { String nodeName = node.getNodeName(); String nodeValue = ((Element) node).getAttribute("value"); if (nodeName.equals("java.lang.Boolean")) { return new Boolean(nodeValue); } else if (nodeName.equals("java.lang.Byte")) { return new Byte(nodeValue); } else if (nodeName.equals("java.lang.Character")) { return new Character(nodeValue.charAt(0)); } else if (nodeName.equals("java.lang.Integer")) { return new Integer(nodeValue); } else if (nodeName.equals("java.lang.Double")) { return new Double(nodeValue); } else if (nodeName.equals("java.lang.Float")) { return new Float(nodeValue); } else if (nodeName.equals("java.lang.Long")) { return new Long(nodeValue); } else if (nodeName.equals("java.lang.Short")) { return new Short(nodeValue); } else if (nodeName.equals("java.lang.String")) { return nodeValue; } else if (nodeName.equals("array")) { String className = node.getAttribute("classname"); String length = node.getAttribute("length"); int len = (new Integer(length)).intValue(); Object array;/*from w w w . j a v a2 s . c o m*/ if (className.equals("byte")) { array = new byte[len]; } else if (className.equals("boolean")) { array = new boolean[len]; } else if (className.equals("char")) { array = new char[len]; } else if (className.equals("double")) { array = new double[len]; } else if (className.equals("float")) { array = new float[len]; } else if (className.equals("int")) { array = new int[len]; } else if (className.equals("long")) { array = new long[len]; } else if (className.equals("short")) { array = new short[len]; } else { array = Array.newInstance(Class.forName(className), len); } Node xmlNode = null; NodeList nl = node.getChildNodes(); int len_nl = nl.getLength(); int i = 0; for (int j = 0; j < len_nl; j++) { xmlNode = nl.item(j); if (xmlNode.getNodeType() == Node.ELEMENT_NODE) { Object o = XMLUtils.readObjectFromXml((Element) xmlNode); Array.set(array, i, o); i++; } } return array; } // XMLization else if (nodeName.equals("xmlizable")) { String className = node.getAttribute("classname"); Node xmlNode = findChildNode(node, Node.ELEMENT_NODE); Object xmlizable = Class.forName(className).newInstance(); ((XMLizable) xmlizable).readXml(xmlNode); return xmlizable; } // Serialization else if (nodeName.equals("serializable")) { Node cdata = findChildNode(node, Node.CDATA_SECTION_NODE); String objectSerializationData = cdata.getNodeValue(); Engine.logEngine.debug("Object serialization data:\n" + objectSerializationData); byte[] objectBytes = org.apache.commons.codec.binary.Base64.decodeBase64(objectSerializationData); // We read the object to a bytes array ByteArrayInputStream inputStream = new ByteArrayInputStream(objectBytes); ObjectInputStream objectInputStream = new ObjectInputStream(inputStream); Object object = objectInputStream.readObject(); inputStream.close(); return object; } return null; }
From source file:org.apache.axis2.context.externalize.SafeObjectInputStream.java
/** * Read the input stream and place the key/value pairs in the * indicated Map/*from ww w . j a v a 2 s . co m*/ * @param map input map * @return map or null * @throws IOException * @see SafeObjectOutputStream.writeMap() */ public Map readMap(Map map) throws IOException { boolean isActive = in.readBoolean(); if (!isActive) { return null; } while (in.readBoolean()) { Object key = null; Object value = null; boolean isObjectForm = in.readBoolean(); try { if (isObjectForm) { if (isDebug) { log.debug(" reading using object form"); } // Read the key and value directly key = in.readObject(); value = in.readObject(); } else { if (isDebug) { log.debug(" reading using byte form"); } // Get the byte stream ByteArrayInputStream bais = getByteStream(in); // Now get the real key and value ObjectInputStream tempOIS = createObjectInputStream(bais); key = tempOIS.readObject(); value = tempOIS.readObject(); tempOIS.close(); bais.close(); } // Put the key and value in the map if (isDebug) { log.debug("Read key=" + valueName(key) + " value=" + valueName(value)); } map.put(key, value); } catch (ClassNotFoundException e) { // Swallow the error and try to continue log.error(e); } catch (IOException e) { throw e; } catch (Exception e) { throw AxisFault.makeFault(e); } } return map; }
From source file:org.kuali.kra.proposaldevelopment.budget.service.impl.BudgetSubAwardServiceImpl.java
/** * updates the XMl with hashcode for the files *//*from w ww. ja v a2s . co m*/ protected BudgetSubAwards updateXML(byte xmlContents[], Map fileMap, BudgetSubAwards budgetSubAwardBean) throws Exception { javax.xml.parsers.DocumentBuilderFactory domParserFactory = javax.xml.parsers.DocumentBuilderFactory .newInstance(); javax.xml.parsers.DocumentBuilder domParser = domParserFactory.newDocumentBuilder(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xmlContents); org.w3c.dom.Document document = domParser.parse(byteArrayInputStream); byteArrayInputStream.close(); String namespace = null; if (document != null) { Node node; String formName; Element element = document.getDocumentElement(); NamedNodeMap map = element.getAttributes(); String namespaceHolder = element.getNodeName().substring(0, element.getNodeName().indexOf(':')); node = map.getNamedItem("xmlns:" + namespaceHolder); namespace = node.getNodeValue(); FormMappingInfo formMappingInfo = new FormMappingLoader().getFormInfo(namespace); formName = formMappingInfo.getFormName(); budgetSubAwardBean.setNamespace(namespace); budgetSubAwardBean.setFormName(formName); } String xpathEmptyNodes = "//*[not(node()) and local-name(.) != 'FileLocation' and local-name(.) != 'HashValue']"; String xpathOtherPers = "//*[local-name(.)='ProjectRole' and local-name(../../.)='OtherPersonnel' and count(../NumberOfPersonnel)=0]"; removeAllEmptyNodes(document, xpathEmptyNodes, 0); removeAllEmptyNodes(document, xpathOtherPers, 1); removeAllEmptyNodes(document, xpathEmptyNodes, 0); changeDataTypeForNumberOfOtherPersons(document); List<String> fedNonFedSubAwardForms = getFedNonFedSubawardForms(); NodeList budgetYearList = XPathAPI.selectNodeList(document, "//*[local-name(.) = 'BudgetYear']"); for (int i = 0; i < budgetYearList.getLength(); i++) { Node bgtYearNode = budgetYearList.item(i); String period = getValue(XPathAPI.selectSingleNode(bgtYearNode, "BudgetPeriod")); if (fedNonFedSubAwardForms.contains(namespace)) { Element newBudgetYearElement = copyElementToName((Element) bgtYearNode, bgtYearNode.getNodeName()); bgtYearNode.getParentNode().replaceChild(newBudgetYearElement, bgtYearNode); } else { Element newBudgetYearElement = copyElementToName((Element) bgtYearNode, bgtYearNode.getNodeName() + period); bgtYearNode.getParentNode().replaceChild(newBudgetYearElement, bgtYearNode); } } Node oldroot = document.removeChild(document.getDocumentElement()); Node newroot = document.appendChild(document.createElement("Forms")); newroot.appendChild(oldroot); org.w3c.dom.NodeList lstFileName = document.getElementsByTagName("att:FileName"); org.w3c.dom.NodeList lstFileLocation = document.getElementsByTagName("att:FileLocation"); org.w3c.dom.NodeList lstMimeType = document.getElementsByTagName("att:MimeType"); org.w3c.dom.NodeList lstHashValue = document.getElementsByTagName("glob:HashValue"); if ((lstFileName.getLength() != lstFileLocation.getLength()) || (lstFileLocation.getLength() != lstHashValue.getLength())) { // throw new RuntimeException("Tag occurances mismatch in XML File"); } org.w3c.dom.Node fileNode, hashNode, mimeTypeNode; org.w3c.dom.NamedNodeMap fileNodeMap, hashNodeMap; String fileName; byte fileBytes[]; String contentId; List attachmentList = new ArrayList(); for (int index = 0; index < lstFileName.getLength(); index++) { fileNode = lstFileName.item(index); Node fileNameNode = fileNode.getFirstChild(); fileName = fileNameNode.getNodeValue(); fileBytes = (byte[]) fileMap.get(fileName); if (fileBytes == null) { throw new RuntimeException("FileName mismatch in XML and PDF extracted file"); } String hashVal = GrantApplicationHash.computeAttachmentHash(fileBytes); hashNode = lstHashValue.item(index); hashNodeMap = hashNode.getAttributes(); Node temp = document.createTextNode(hashVal); hashNode.appendChild(temp); hashNode = hashNodeMap.getNamedItem("glob:hashAlgorithm"); hashNode.setNodeValue(S2SConstants.HASH_ALGORITHM); fileNode = lstFileLocation.item(index); fileNodeMap = fileNode.getAttributes(); fileNode = fileNodeMap.getNamedItem("att:href"); contentId = fileNode.getNodeValue(); String encodedContentId = cleanContentId(contentId); fileNode.setNodeValue(encodedContentId); mimeTypeNode = lstMimeType.item(0); String contentType = mimeTypeNode.getFirstChild().getNodeValue(); BudgetSubAwardAttachment budgetSubAwardAttachmentBean = new BudgetSubAwardAttachment(); budgetSubAwardAttachmentBean.setAttachment(fileBytes); budgetSubAwardAttachmentBean.setContentId(encodedContentId); budgetSubAwardAttachmentBean.setContentType(contentType); budgetSubAwardAttachmentBean.setBudgetId(budgetSubAwardBean.getBudgetId()); budgetSubAwardAttachmentBean.setSubAwardNumber(budgetSubAwardBean.getSubAwardNumber()); attachmentList.add(budgetSubAwardAttachmentBean); } budgetSubAwardBean.setBudgetSubAwardAttachments(attachmentList); javax.xml.transform.Transformer transformer = javax.xml.transform.TransformerFactory.newInstance() .newTransformer(); transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(bos); javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource(document); transformer.transform(source, result); budgetSubAwardBean.setSubAwardXmlFileData(new String(bos.toByteArray())); bos.close(); return budgetSubAwardBean; }