List of usage examples for java.io ByteArrayInputStream close
public void close() throws IOException
From source file:com.flexive.sqlParser.FxStatement.java
/** * Parses a statement./* ww w. ja v a2 s .c o m*/ * * @param query the query to process * @return the statement * @throws SqlParserException ifthe function fails */ public static FxStatement parseSql(String query) throws SqlParserException { try { long startTime = System.currentTimeMillis(); query = cleanupQueryString(query); ByteArrayInputStream byis = new ByteArrayInputStream(query.getBytes(Charsets.UTF_8)); FxStatement stmt = new SQL(byis, "UTF-8").statement(); byis.close(); stmt.setParserExecutionTime((int) (System.currentTimeMillis() - startTime)); return stmt; } catch (TokenMgrError exc) { throw new SqlParserException(exc, query); } catch (ParseException exc) { throw new SqlParserException(exc, query); } catch (SqlParserException exc) { throw exc; } catch (Exception exc) { throw new SqlParserException(exc.getMessage()); } }
From source file:com.beetle.framework.util.ObjectUtil.java
/** * ?//w ww .j av a 2 s. c om * * @param bytes * @return */ public final static Object bytesToObj(byte[] bytes) { ByteArrayInputStream bai = null; ObjectInputStream ois; try { bai = new ByteArrayInputStream(bytes); ois = new ObjectInputStream(bai); Object obj = ois.readObject(); ois.close(); ois = null; return obj; } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (bai != null) { bai.close(); bai = null; } } catch (IOException e) { } } }
From source file:org.apache.accumulo.core.client.mapreduce.lib.util.InputConfigurator.java
/** * Gets a list of the iterator settings (for iterators to apply to a scanner) from this configuration. * /*from ww w.j a va2 s . com*/ * @param implementingClass * the class whose name will be used as a prefix for the property configuration key * @param conf * the Hadoop configuration object to configure * @return a list of iterators * @since 1.5.0 * @see #addIterator(Class, Configuration, IteratorSetting) */ public static List<IteratorSetting> getIterators(Class<?> implementingClass, Configuration conf) { String iterators = conf.get(enumToConfKey(implementingClass, ScanOpts.ITERATORS)); // If no iterators are present, return an empty list if (iterators == null || iterators.isEmpty()) return new ArrayList<IteratorSetting>(); // Compose the set of iterators encoded in the job configuration StringTokenizer tokens = new StringTokenizer(iterators, StringUtils.COMMA_STR); List<IteratorSetting> list = new ArrayList<IteratorSetting>(); try { while (tokens.hasMoreTokens()) { String itstring = tokens.nextToken(); ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decodeBase64(itstring.getBytes())); list.add(new IteratorSetting(new DataInputStream(bais))); bais.close(); } } catch (IOException e) { throw new IllegalArgumentException("couldn't decode iterator settings"); } return list; }
From source file:org.apache.synapse.message.store.impl.jdbc.util.JDBCMessageConverter.java
/** * Create SynapseMessage out of StorableMessage * * @param message StorableMessage// w ww . j ava2 s.c o m * @return synCtx SynapseMessage */ public static MessageContext createMessageContext(StorableMessage message) { SynapseConfiguration configuration = synapseEnvironment.getSynapseConfiguration(); MessageContext synCtx = null; org.apache.axis2.context.MessageContext msgCtx = ((Axis2SynapseEnvironment) synapseEnvironment) .getAxis2ConfigurationContext().createMessageContext(); AxisConfiguration axisConfiguration = msgCtx.getConfigurationContext().getAxisConfiguration(); JDBCAxis2Message jdbcAxis2MessageContext = message.getAxis2Message(); SOAPEnvelope envelope = getSoapEnvelope(jdbcAxis2MessageContext.getSoapEnvelope()); try { msgCtx.setEnvelope(envelope); // Set the properties msgCtx.getOptions().setAction(jdbcAxis2MessageContext.getAction()); if (jdbcAxis2MessageContext.getRelatesToMessageId() != null) { msgCtx.addRelatesTo(new RelatesTo(jdbcAxis2MessageContext.getRelatesToMessageId())); } msgCtx.setMessageID(jdbcAxis2MessageContext.getMessageID()); msgCtx.setDoingREST(jdbcAxis2MessageContext.isDoingPOX()); msgCtx.setDoingMTOM(jdbcAxis2MessageContext.isDoingMTOM()); msgCtx.setDoingSwA(jdbcAxis2MessageContext.isDoingSWA()); AxisService axisService = axisConfiguration .getServiceForActivation(jdbcAxis2MessageContext.getService()); AxisOperation axisOperation = axisService.getOperation(jdbcAxis2MessageContext.getOperationName()); msgCtx.setFLOW(jdbcAxis2MessageContext.getFlow()); ArrayList executionChain = new ArrayList(); if (jdbcAxis2MessageContext.getFlow() == org.apache.axis2.context.MessageContext.OUT_FLOW) { executionChain.addAll(axisOperation.getPhasesOutFlow()); executionChain.addAll(axisConfiguration.getOutFlowPhases()); } else if (jdbcAxis2MessageContext .getFlow() == org.apache.axis2.context.MessageContext.OUT_FAULT_FLOW) { executionChain.addAll(axisOperation.getPhasesOutFaultFlow()); executionChain.addAll(axisConfiguration.getOutFlowPhases()); } msgCtx.setExecutionChain(executionChain); ConfigurationContext configurationContext = msgCtx.getConfigurationContext(); msgCtx.setAxisService(axisService); ServiceGroupContext serviceGroupContext = configurationContext .createServiceGroupContext(axisService.getAxisServiceGroup()); ServiceContext serviceContext = serviceGroupContext.getServiceContext(axisService); OperationContext operationContext = serviceContext .createOperationContext(jdbcAxis2MessageContext.getOperationName()); msgCtx.setServiceContext(serviceContext); msgCtx.setOperationContext(operationContext); msgCtx.setAxisService(axisService); msgCtx.setAxisOperation(axisOperation); if (jdbcAxis2MessageContext.getReplyToAddress() != null) { msgCtx.setReplyTo(new EndpointReference(jdbcAxis2MessageContext.getReplyToAddress().trim())); } if (jdbcAxis2MessageContext.getFaultToAddress() != null) { msgCtx.setFaultTo(new EndpointReference(jdbcAxis2MessageContext.getFaultToAddress().trim())); } if (jdbcAxis2MessageContext.getFromAddress() != null) { msgCtx.setFrom(new EndpointReference(jdbcAxis2MessageContext.getFromAddress().trim())); } if (jdbcAxis2MessageContext.getToAddress() != null) { msgCtx.getOptions().setTo(new EndpointReference(jdbcAxis2MessageContext.getToAddress().trim())); } msgCtx.setProperties(jdbcAxis2MessageContext.getProperties()); msgCtx.setTransportIn(axisConfiguration.getTransportIn(jdbcAxis2MessageContext.getTransportInName())); msgCtx.setTransportOut( axisConfiguration.getTransportOut(jdbcAxis2MessageContext.getTransportOutName())); if (jdbcAxis2MessageContext.getJsonStream() != null) { JsonUtil.newJsonPayload(msgCtx, new ByteArrayInputStream(jdbcAxis2MessageContext.getJsonStream()), true, true); } JDBCSynapseMessage jdbcSynpaseMessageContext = message.getSynapseMessage(); synCtx = new Axis2MessageContext(msgCtx, configuration, synapseEnvironment); synCtx.setTracingState(jdbcSynpaseMessageContext.getTracingState()); Iterator<String> it = jdbcSynpaseMessageContext.getProperties().keySet().iterator(); while (it.hasNext()) { String key = it.next(); Object value = jdbcSynpaseMessageContext.getProperties().get(key); synCtx.setProperty(key, value); } Iterator<String> propertyObjects = jdbcSynpaseMessageContext.getPropertyObjects().keySet().iterator(); while (propertyObjects.hasNext()) { String key = propertyObjects.next(); Object value = jdbcSynpaseMessageContext.getPropertyObjects().get(key); if (key.startsWith(OM_ELEMENT_PREFIX)) { String originalKey = key.substring(OM_ELEMENT_PREFIX.length(), key.length()); ByteArrayInputStream is = new ByteArrayInputStream((byte[]) value); try { StAXOMBuilder builder = new StAXOMBuilder(is); OMElement omElement = builder.getDocumentElement(); synCtx.setProperty(originalKey, omElement); } catch (XMLStreamException e) { log.error("Error while deserializing the OM element prefix ", e); } finally { try { is.close(); } catch (IOException e) { log.error("Error while closing input stream ", e); } } } } synCtx.setFaultResponse(jdbcSynpaseMessageContext.isFaultResponse()); synCtx.setResponse(jdbcSynpaseMessageContext.isResponse()); } catch (Exception e) { log.error("Error while deserializing the JDBC Persistent Message ", e); } return synCtx; }
From source file:org.apache.myfaces.shared_impl.util.StateUtils.java
public static Object getAsObject(byte[] bytes, ExternalContext ctx) { ByteArrayInputStream input = new ByteArrayInputStream(bytes); // get the Factory that was instantiated @ startup SerialFactory serialFactory = (SerialFactory) ctx.getApplicationMap().get(SERIAL_FACTORY); if (serialFactory == null) throw new NullPointerException("serialFactory"); try {//w w w. j a v a 2 s. c o m ObjectInputStream s = serialFactory.getObjectInputStream(input); //new MyFacesObjectInputStream(input); Object object = s.readObject(); s.close(); input.close(); s = null; input = null; return object; } catch (Exception e) { throw new FacesException(e); } }
From source file:com.beligum.core.utils.AssetPacker.java
private static String decodeGzip(byte[] content) throws IOException { String retVal = null;//from www . ja va 2 s. c om ByteArrayInputStream in = null; GZIPInputStream gzip = null; try { in = new ByteArrayInputStream(content); gzip = new GZIPInputStream(in); BufferedReader reader = new BufferedReader(new InputStreamReader(gzip, "UTF-8")); StringBuilder sb = new StringBuilder(); String s; while ((s = reader.readLine()) != null) { sb.append(s); } gzip.close(); in.close(); retVal = sb.toString(); } catch (Exception e) { if (gzip != null) { gzip.close(); } if (in != null) { in.close(); } } return retVal; }
From source file:org.ofbiz.webapp.event.RestEventHandler.java
/** * ? //w w w.ja v a 2 s .com * * @param data * @return * @throws Exception */ public static byte[] decompress(byte[] data) throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(data); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // decompress(bais, baos); data = baos.toByteArray(); baos.flush(); baos.close(); bais.close(); return data; }
From source file:com.chenshu.compress.CompressSizeTest.java
public static int compress(StreamFactory factory, byte[] src) { byte[] dest = null; ByteArrayOutputStream bout = null; OutputStream out = null;//from w ww . ja va 2s . co m try { bout = new ByteArrayOutputStream(src.length); out = factory.getOutputStream(bout); out.write(src); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } if (bout != null) { try { bout.close(); } catch (IOException e) { e.printStackTrace(); } } } byte[] bs = bout.toByteArray(); ByteArrayInputStream bin = null; InputStream in = null; ByteArrayOutputStream os = null; try { bin = new ByteArrayInputStream(bs); in = factory.getInputStream(bin); dest = new byte[src.length]; os = new ByteArrayOutputStream(src.length); int count = 0; while ((count = in.read(dest)) != -1) { os.write(dest, 0, count); } dest = os.toByteArray(); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (bin != null) { try { bin.close(); } catch (IOException e) { e.printStackTrace(); } } if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println(src.length == dest.length); System.out.println(Arrays.equals(src, dest)); System.out.println( new String(src, Charset.forName("UTF-8")).equals(new String(dest, Charset.forName("UTF-8")))); return bs.length; }
From source file:org.dawnsci.common.richbeans.beans.BeanUI.java
/** * Bean from string using standard java serialization, useful for tables of beans with serialized strings. Used * externally to the GDA.//from w ww. j a v a 2 s. co m * * @param xml * @return the bean */ public static Object getBean(final String xml, final ClassLoader loader) throws Exception { final ClassLoader original = Thread.currentThread().getContextClassLoader(); final ByteArrayInputStream stream = new ByteArrayInputStream(xml.getBytes("UTF-8")); try { Thread.currentThread().setContextClassLoader(loader); XMLDecoder d = new XMLDecoder(new BufferedInputStream(stream)); final Object bean = d.readObject(); d.close(); return bean; } finally { Thread.currentThread().setContextClassLoader(original); stream.close(); } }
From source file:org.moqui.impl.entity.EntityJavaUtil.java
public static void setPreparedStatementValue(PreparedStatement ps, int index, Object value, FieldInfo fi, boolean useBinaryTypeForBlob, EntityFacade efi) throws EntityException { try {/*from w ww. j ava 2 s . co m*/ // allow setting, and searching for, String values for all types; JDBC driver should handle this okay if (value instanceof CharSequence) { ps.setString(index, value.toString()); } else { switch (fi.typeValue) { case 1: if (value != null) { ps.setString(index, value.toString()); } else { ps.setNull(index, Types.VARCHAR); } break; case 2: if (value != null) { Class valClass = value.getClass(); if (valClass == Timestamp.class) { ps.setTimestamp(index, (Timestamp) value, efi.getCalendarForTzLc()); } else if (valClass == java.sql.Date.class) { ps.setDate(index, (java.sql.Date) value, efi.getCalendarForTzLc()); } else if (valClass == java.util.Date.class) { ps.setTimestamp(index, new Timestamp(((java.util.Date) value).getTime()), efi.getCalendarForTzLc()); } else { throw new IllegalArgumentException("Class " + valClass.getName() + " not allowed for date-time (Timestamp) fields, for field " + fi.entityName + "." + fi.name); } } else { ps.setNull(index, Types.TIMESTAMP); } break; case 3: Time tm = (Time) value; // logger.warn("=================== setting time tm=${tm} tm long=${tm.getTime()}, cal=${cal}") if (value != null) { ps.setTime(index, tm, efi.getCalendarForTzLc()); } else { ps.setNull(index, Types.TIME); } break; case 4: if (value != null) { Class valClass = value.getClass(); if (valClass == java.sql.Date.class) { java.sql.Date dt = (java.sql.Date) value; // logger.warn("=================== setting date dt=${dt} dt long=${dt.getTime()}, cal=${cal}") ps.setDate(index, dt, efi.getCalendarForTzLc()); } else if (valClass == Timestamp.class) { ps.setDate(index, new java.sql.Date(((Timestamp) value).getTime()), efi.getCalendarForTzLc()); } else if (valClass == java.util.Date.class) { ps.setDate(index, new java.sql.Date(((java.util.Date) value).getTime()), efi.getCalendarForTzLc()); } else { throw new IllegalArgumentException("Class " + valClass.getName() + " not allowed for date fields, for field " + fi.entityName + "." + fi.name); } } else { ps.setNull(index, Types.DATE); } break; case 5: if (value != null) { ps.setInt(index, ((Number) value).intValue()); } else { ps.setNull(index, Types.NUMERIC); } break; case 6: if (value != null) { ps.setLong(index, ((Number) value).longValue()); } else { ps.setNull(index, Types.NUMERIC); } break; case 7: if (value != null) { ps.setFloat(index, ((Number) value).floatValue()); } else { ps.setNull(index, Types.NUMERIC); } break; case 8: if (value != null) { ps.setDouble(index, ((Number) value).doubleValue()); } else { ps.setNull(index, Types.NUMERIC); } break; case 9: if (value != null) { Class valClass = value.getClass(); // most common cases BigDecimal, Double, Float; then allow any Number if (valClass == BigDecimal.class) { ps.setBigDecimal(index, (BigDecimal) value); } else if (valClass == Double.class) { ps.setDouble(index, (Double) value); } else if (valClass == Float.class) { ps.setFloat(index, (Float) value); } else if (value instanceof Number) { ps.setDouble(index, ((Number) value).doubleValue()); } else { throw new IllegalArgumentException("Class " + valClass.getName() + " not allowed for number-decimal (BigDecimal) fields, for field " + fi.entityName + "." + fi.name); } } else { ps.setNull(index, Types.NUMERIC); } break; case 10: if (value != null) { ps.setBoolean(index, (Boolean) value); } else { ps.setNull(index, Types.BOOLEAN); } break; case 11: if (value != null) { try { ByteArrayOutputStream os = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(os); oos.writeObject(value); oos.close(); byte[] buf = os.toByteArray(); os.close(); ByteArrayInputStream is = new ByteArrayInputStream(buf); ps.setBinaryStream(index, is, buf.length); is.close(); } catch (IOException ex) { throw new EntityException( "Error setting serialized object, for field " + fi.entityName + "." + fi.name, ex); } } else { if (useBinaryTypeForBlob) { ps.setNull(index, Types.BINARY); } else { ps.setNull(index, Types.BLOB); } } break; case 12: if (value instanceof byte[]) { ps.setBytes(index, (byte[]) value); /* } else if (value instanceof ArrayList) { ArrayList valueAl = (ArrayList) value; byte[] theBytes = new byte[valueAl.size()]; valueAl.toArray(theBytes); ps.setBytes(index, theBytes); */ } else if (value instanceof ByteBuffer) { ByteBuffer valueBb = (ByteBuffer) value; ps.setBytes(index, valueBb.array()); } else if (value instanceof Blob) { Blob valueBlob = (Blob) value; // calling setBytes instead of setBlob // ps.setBlob(index, (Blob) value) // Blob blb = value ps.setBytes(index, valueBlob.getBytes(1, (int) valueBlob.length())); } else { if (value != null) { throw new IllegalArgumentException("Type not supported for BLOB field: " + value.getClass().getName() + ", for field " + fi.entityName + "." + fi.name); } else { if (useBinaryTypeForBlob) { ps.setNull(index, Types.BINARY); } else { ps.setNull(index, Types.BLOB); } } } break; case 13: if (value != null) { ps.setClob(index, (Clob) value); } else { ps.setNull(index, Types.CLOB); } break; case 14: if (value != null) { ps.setTimestamp(index, (Timestamp) value); } else { ps.setNull(index, Types.TIMESTAMP); } break; // TODO: is this the best way to do collections and such? case 15: if (value != null) { ps.setObject(index, value, Types.JAVA_OBJECT); } else { ps.setNull(index, Types.JAVA_OBJECT); } break; } } } catch (SQLException sqle) { throw new EntityException("SQL Exception while setting value [" + value + "](" + (value != null ? value.getClass().getName() : "null") + "), type " + fi.type + ", for field " + fi.entityName + "." + fi.name + ": " + sqle.toString(), sqle); } catch (Exception e) { throw new EntityException( "Error while setting value for field " + fi.entityName + "." + fi.name + ": " + e.toString(), e); } }