Uses {@link DataModelConverters#toWorkbook(IDataModel, InputStream)} with {@link ByteArrayOutputStream} as out stream
and new {@link XSSFWorkbook} as {@link InputStream} wrapper.
519152
static OutputStream toXlsxFile(final IDataModel dataModel, final InputStream formatting) {
        ByteArrayOutputStream xlsx = new ByteArrayOutputStream();
        
        try { toWorkbook(dataModel, ConverterUtils.newWorkbook(formatting)).write(xlsx); }
        catch (IOException e) { throw new CalculationEngineException(e); }
        
        return xlsx;
    }
1061972
public static <T extends XMLObject> T transformSamlObject(final OpenSamlConfigBean configBean, final byte[] data,
                                                              final Class<T> clazz) {
        try (InputStream in = new ByteArrayInputStream(data)) {
            val document = configBean.getParserPool().parse(in);
            val root = document.getDocumentElement();
            val marshaller = configBean.getUnmarshallerFactory().getUnmarshaller(root);
            if (marshaller != null) {
                val result = marshaller.unmarshall(root);
                if (!clazz.isAssignableFrom(result.getClass())) {
                    throw new ClassCastException("Result [" + result + " is of type " + result.getClass() + " when we were expecting " + clazz);
                }
                return (T) result;
            }
        } catch (final Exception e) {
            throw new SamlException(e.getMessage(), e);
        }
        return null;
    }
805783
public static void main(final String... args) throws Exception {
        if (args.length < 2 || args.length > 3) {
            System.out.println("Usage: XMLSerializer input-TT output.xml");
            System.exit(1);
        }

        System.out.print("Serializing '" + args[0] + "' to '" + args[1] + "' ... ");
        final long time = System.currentTimeMillis();

        Injector injector =
            Guice.createInjector(new ModuleSetter().setDataFacClass(TreeNodeFactory.class).setMetaFacClass(
                NodeMetaPageFactory.class).createModule());
        IBackendFactory storage = injector.getInstance(IBackendFactory.class);
        IRevisioning revision = injector.getInstance(IRevisioning.class);

        final File target = new File(args[1]);
        target.delete();
        final FileOutputStream outputStream = new FileOutputStream(target);

        final StorageConfiguration config = new StorageConfiguration(new File(args[0]));
        Storage.createStorage(config);
        final IStorage db = Storage.openStorage(new File(args[0]));
        Properties props = new Properties();
        props.setProperty(ConstructorProps.STORAGEPATH, target.getAbsolutePath());
        props.setProperty(ConstructorProps.RESOURCE, "shredded");
        db.createResource(new ResourceConfiguration(props, storage, revision, new TreeNodeFactory(),
            new NodeMetaPageFactory()));
        final ISession session = db.getSession(new SessionConfiguration("shredded", StandardSettings.KEY));

        final XMLSerializer serializer = new XMLSerializerBuilder(session, outputStream).build();
        serializer.call();

        session.close();
        outputStream.close();
        db.close();

        System.out.println(" done [" + (System.currentTimeMillis() - time) + "ms].");
    }
1154426
@Override
  public RecordStreamWithMetadata<DO, SO> processStream(RecordStreamWithMetadata<DI, SI> inputStream,
      WorkUnitState workUnitState) throws SchemaConversionException {
    init(workUnitState);
    this.outputGlobalMetadata = GlobalMetadata.<SI, SO>builderWithInput(inputStream.getGlobalMetadata(),
        Optional.fromNullable(convertSchema(inputStream.getGlobalMetadata().getSchema(), workUnitState))).build();
    Flowable<StreamEntity<DO>> outputStream =
        inputStream.getRecordStream()
            .flatMap(in -> {
              if (in instanceof ControlMessage) {
                ControlMessage out = (ControlMessage) in;

                getMessageHandler().handleMessage((ControlMessage) in);

                // update the output schema with the new input schema from the MetadataUpdateControlMessage
                if (in instanceof MetadataUpdateControlMessage) {
                  this.outputGlobalMetadata = GlobalMetadata.<SI, SO>builderWithInput(
                      ((MetadataUpdateControlMessage) in).getGlobalMetadata(),
                      Optional.fromNullable(convertSchema((SI)((MetadataUpdateControlMessage) in).getGlobalMetadata()
                          .getSchema(), workUnitState))).build();
                  out = new MetadataUpdateControlMessage<SO, DO>(this.outputGlobalMetadata);
                }

                return Flowable.just(((ControlMessage<DO>) out));
              } else if (in instanceof RecordEnvelope) {
                RecordEnvelope<DI> recordEnvelope = (RecordEnvelope<DI>) in;
                return convertRecordEnvelope(this.outputGlobalMetadata.getSchema(), recordEnvelope, workUnitState);
              } else {
                throw new UnsupportedOperationException();
              }
            }, 1);
    outputStream = outputStream.doOnComplete(this::close);
    return inputStream.withRecordStream(outputStream, this.outputGlobalMetadata);
  }
500788
public static Document getSOAPMessage(InputStream in) throws Exception {
        /*
         * ByteArrayOutputStream out = new ByteArrayOutputStream(); int b; while
         * ((b = in.read()) != -1) { out.write(b); }
         * 
         * System.out.println("OUT:" + out.toString());
         */
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
	   // Fortify Mod: Disable entity expansion to foil External Entity Injections
	   dbf.setExpandEntityReferences(false);
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document soapMessage = db.newDocument();
          // Fortify Mod: prevent external entity injection
        TransformerFactory tf = TransformerFactory.newInstance();
        tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        Transformer t = tf.newTransformer();
	   // End Fortify Mod
        t.transform(new StreamSource(in), new DOMResult(soapMessage));
        return soapMessage;
    }
754209
@Override
    public XMLStreamReader createXMLStreamReader(InputStream in)
        throws XMLStreamException
    {
        // false for auto-close, since caller has access to the input stream
        return createSR(null, in, null, false, false);
    }
1322877
public static byte[] inputStreamToBytes(InputStream in) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
        } catch (Exception e) {
            System.out.println("Error converting InputStream to byte[]: "
                    + e.getMessage());
        }
        return out.toByteArray();
    }
158650
static IDataModel toDataModel(final Workbook workbook) {
        if (workbook == null) { return null; }
        
        //add custom functions information
        workbook.addToolPack(getUdfFinder());
        
        Sheet s = workbook.getSheetAt(0); //TODO: only one sheet is supported
        if (s == null) { return null; }
        
        IDataModel dm = new DataModel(s.getSheetName());
        
        for (int i = s.getFirstRowNum(); i <= s.getLastRowNum(); i++) {
            Row r = s.getRow(i);
            if (r == null) { continue; }
            
            DmRow row = new DmRow(i);
            dm.setRow(i, row);
            
            for (int j = r.getFirstCellNum(); j < r.getLastCellNum(); j++) {
                Cell c = r.getCell(j);
                if (c == null) { continue; }
                
                DmCell cell = new DmCell();
                row.setCell(j, cell);
                
                cell.setAddress(new CellAddress(dm.getDataModelId(), A1Address.fromRowColumn(i, j)));
                cell.setContent(ConverterUtils.resolveCellValue(c));
            }
        }

        EvaluationWorkbook evaluationWbook = ConverterUtils.newEvaluationWorkbook(workbook);

        for (int nIdx = 0; nIdx < workbook.getNumberOfNames(); nIdx++) {
            Name name = workbook.getNameAt(nIdx);

            String reference = name.getRefersToFormula();
            if (reference == null) { continue; }

            if (A1Address.isAddress(removeSheetFromNameRef(reference))) {
                dm.setNamedAddress(name.getNameName(), A1Address.fromA1Address(removeSheetFromNameRef(reference)));
            } else if (isFormula(reference, evaluationWbook)) {
                dm.setNamedValue(name.getNameName(), new CellValue(FORMULA_PREFIX + reference));
            } else {
                dm.setNamedValue(name.getNameName(), CellValue.from(reference));
            }
        }

        return dm;
    }
376732
public static Document inputStreamToDocument(InputStream is) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setExpandEntityReferences(false);
        factory.setIgnoringComments(false);
        factory.setIgnoringElementContentWhitespace(false);
        factory.setValidating(false);

        DocumentBuilder builder = factory.newDocumentBuilder();
        Document root = builder.parse(is);

        return root;
    }
1121265
public Stream<T> asStream() {
        if (modelType == null) {
            throw new IllegalArgumentException("modelType can be not null");
        }

        if (fromFile == null && fromStream == null) {
            throw new IllegalArgumentException("Excel source not is null");
        }

        if (fromFile != null) {
            return ReaderFactory.readByFile(this);
        } else {
            return ReaderFactory.readByStream(this);
        }
    }
437186
public static Element sourceToElement(Source source) throws IOException
   {
      Element retElement = null;

      if (source instanceof StreamSource)
      {
         StreamSource streamSource = (StreamSource)source;

         InputStream ins = streamSource.getInputStream();
         if (ins != null)
         {
            retElement = DOMUtils.parse(ins);
         }
         Reader reader = streamSource.getReader();
         if (reader != null)
         {
            retElement = DOMUtils.parse(new InputSource(reader));
         }
      }
      else if (source instanceof DOMSource)
      {
         DOMSource domSource = (DOMSource)source;
         Node node = domSource.getNode();
         if (node instanceof Element)
         {
            retElement = (Element)node;
         }
         else if (node instanceof Document)
         {
            retElement = ((Document)node).getDocumentElement();
         }
      }
      else if (source instanceof SAXSource)
      {
         // The fact that JAXBSource derives from SAXSource is an implementation detail.
         // Thus in general applications are strongly discouraged from accessing methods defined on SAXSource.
         // The XMLReader object obtained by the getXMLReader method shall be used only for parsing the InputSource object returned by the getInputSource method.

         final boolean hasInputSource = ((SAXSource) source).getInputSource() != null; 
         final boolean hasXMLReader = ((SAXSource) source).getXMLReader() != null;

         if (hasInputSource || hasXMLReader)
         {
            try
            {
               TransformerFactory tf = TransformerFactory.newInstance();
               ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
               Transformer transformer = tf.newTransformer();
               transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
               transformer.setOutputProperty(OutputKeys.METHOD, "xml");
               transformer.transform(source, new StreamResult(baos));
               retElement = DOMUtils.parse(new ByteArrayInputStream(baos.toByteArray()));
            }
            catch (TransformerException ex)
            {
               throw new IOException(ex);
            }
         }
      }
      else
      {
         throw MESSAGES.sourceTypeNotImplemented(source.getClass());
      }

      return retElement;
   }
1046197
public static Workbook getWorkbook(String filename, InputStream stream) 
        throws IOException
    {
        Workbook ret = null;
        String lowerFilename = filename.toLowerCase();
        if(lowerFilename.endsWith("."+CommonFiles.XLS_EXT))
        {
            ret = XlsWorkbook.getWorkbook(stream);
        }
        else if(lowerFilename.endsWith("."+CommonFiles.XLSX_EXT))
        {
            XlsxWorkbook.initJaxbContexts();
            ret = XlsxWorkbook.getWorkbook(stream);
        }
        return ret;
    }
543317
@Override
    public InputStream openInputStream() throws IOException {
        if (outputStream != null) {
            return new ByteArrayInputStream(outputStream.toByteArray());
        } else {
            return new ByteArrayInputStream(new byte[0]);
        }
    }
1078482
public static Workbook createBook(boolean isXlsx) {
		Workbook workbook;
		if (isXlsx) {
			workbook = new XSSFWorkbook();
		} else {
			workbook = new org.apache.poi.hssf.usermodel.HSSFWorkbook();
		}
		return workbook;
	}
148121
public static XlsxWorkbook getWorkbook(InputStream stream) throws IOException
    {
        try
        {
            return new XlsxWorkbook(stream);
        }
        catch(Docx4JException e)
        {
            throw new IOException(e);
        }
    }
847337
public void generateXls(OutputStream out, List<Map<String, Object>> rows, List<ColumnDef> columns) {
        try {
            Workbook wb = new HSSFWorkbook();  // or new XSSFWorkbook();
            String safeName = WorkbookUtil.createSafeSheetName("Report"); // returns " O'Brien's sales   "
            Sheet reportSheet = wb.createSheet(safeName);

            short rowc = 0;
            Row nrow = reportSheet.createRow(rowc++);
            short cellc = 0;
            if (rows == null) return;
            if (columns == null && rows.size() > 0)
            {
                columns = new ArrayList<ColumnDef>(CollectionUtils.collect(rows.get(0).keySet(), new Transformer() {
                    @Override
                    public Object transform(final Object input) {
                        return new ColumnDef()
                        {{
                                setName((String)input);
                            }};
                    }
                }));
            }
            if (columns != null)
            {
                for (ColumnDef column : columns)
                {
                    Cell cell = nrow.createCell(cellc++);
                    cell.setCellValue(column.getName());
                }
            }
            for (Map<String, Object> row : rows)
            {
                nrow = reportSheet.createRow(rowc++);
                cellc = 0;
                for (ColumnDef column : columns)
                {
                    Cell cell = nrow.createCell(cellc++);
                    cell.setCellValue(String.valueOf(row.get(column.getName())));
                }
            }
            wb.write(out);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }
354367
@Deprecated
    public void marshalMarshall(Object o, OutputStream out) {
        try {
            XStream xStream = newXStream();
            out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".getBytes());
            OutputStreamWriter ows = new OutputStreamWriter(out, "UTF-8");
            xStream.toXML(o, ows);
        } catch ( Exception e ) {
            e.printStackTrace();
        }
    }