Example usage for java.io ByteArrayInputStream available

List of usage examples for java.io ByteArrayInputStream available

Introduction

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

Prototype

public synchronized int available() 

Source Link

Document

Returns the number of remaining bytes that can be read (or skipped over) from this input stream.

Usage

From source file:org.fao.geonet.arcgis.ArcSDEApiConnection.java

@Override
public Map<String, String> retrieveMetadata(AtomicBoolean cancelMonitor, String arcSDEVersion)
        throws Exception {
    Log.info(ARCSDE_LOG_MODULE_NAME, "Start retrieve metadata");
    Map<String, String> results = new HashMap<>();
    try {/*from  w w w .ja  v  a 2  s.  c  om*/
        ArcSDEVersionFactory arcSDEVersionFactory = new ArcSDEVersionFactory();
        String metadataTable = arcSDEVersionFactory.getTableName(arcSDEVersion);
        String columnName = arcSDEVersionFactory.getMetadataColumnName(arcSDEVersion);

        // query table containing XML metadata
        SeSqlConstruct sqlConstruct = new SeSqlConstruct();
        String[] tables = { metadataTable };
        sqlConstruct.setTables(tables);
        String[] propertyNames = { columnName, "uuid" };
        SeQuery query = new SeQuery(seConnection);
        query.prepareQuery(propertyNames, sqlConstruct);
        query.execute();

        // it is not documented in the ArcSDE API how you know there are no more rows to fetch!
        // I'm assuming: query.fetch returns null (empiric tests indicate this assumption is correct).
        boolean allRowsFetched = false;
        while (!allRowsFetched) {
            if (cancelMonitor.get()) {
                return Collections.emptyMap();
            }
            SeRow row = query.fetch();

            if (row != null) {
                if (row.getObject(0) != null) {
                    Log.info(ARCSDE_LOG_MODULE_NAME, "Retrieving row metadata");

                    SeColumnDefinition colDef = row.getColumnDef(0);

                    String document = "";

                    if (colDef.getType() == SeColumnDefinition.TYPE_BLOB
                            || colDef.getType() == SeColumnDefinition.TYPE_CLOB) {
                        ByteArrayInputStream bytes = row.getBlob(0);
                        byte[] buff = new byte[bytes.available()];
                        bytes.read(buff);
                        document = new String(buff, Constants.ENCODING);

                    } else if (colDef.getType() == SeColumnDefinition.TYPE_XML) {
                        SeXmlDoc xmlDoc = row.getXml(0);
                        document = xmlDoc.getText();
                    } else if (colDef.getType() == SeColumnDefinition.TYPE_STRING) {
                        document = row.getString(0);
                    }

                    if (StringUtils.isNotEmpty(document)) {
                        String uuid = row.getString(1);
                        results.put(uuid, document);
                    }
                } else {
                    Log.info(ARCSDE_LOG_MODULE_NAME, "Ignoring row without metadata");
                }
            } else {
                allRowsFetched = true;
            }
        }
        query.close();
        Log.info(ARCSDE_LOG_MODULE_NAME,
                "Finished retrieving metadata, found: #" + results.size() + " metadata records");
        return results;
    } catch (SeException x) {
        SeError error = x.getSeError();
        String description = error.getExtError() + " " + error.getExtErrMsg() + " " + error.getErrDesc();
        Log.error(ARCSDE_LOG_MODULE_NAME,
                "Error retrieving the metadata from " + "ArcSDE connection (via API):" + description, x);
        throw new Exception(x);
    }
}

From source file:org.efaps.esjp.admin.program.CSS.java

/**
 * Used to update the wiki including compilation.
 *
 * @param _parameter Paarmeter as passed from the eFaps API
 * @return new Return/*from ww  w  .j av  a 2 s.c o  m*/
 * @throws EFapsException on error
 */
public Return updateCSS(final Parameter _parameter) throws EFapsException {
    final Instance instance = _parameter.getInstance();
    final PrintQuery print = new PrintQuery(instance);
    print.addAttribute(CIAdminProgram.Abstract.Name);
    print.execute();

    final String css = _parameter.getParameterValue("css");
    try {
        final ByteArrayInputStream in = new ByteArrayInputStream(css.getBytes("UTF8"));
        final Checkin checkin = new Checkin(instance);
        checkin.execute(print.<String>getAttribute(CIAdminProgram.Abstract.Name), in, in.available());
    } catch (final UnsupportedEncodingException e) {
        throw new EFapsException(CSS.class, "updateCSS.UnsupportedEncodingException", e);
    }
    return new Return();
}

From source file:org.apache.pdfbox.pdmodel.interactive.digitalsignature.visible.PDFTemplateCreator.java

/**
 * this method builds pdf  step by step, and finally it returns stream of visible signature
 * @param properties/*from  ww  w .  ja v a  2  s .c o m*/
 * @return InputStream
 * @throws IOException
 */
public InputStream buildPDF(PDVisibleSignDesigner properties) throws IOException {
    logger.info("pdf building has been started");
    PDFTemplateStructure pdfStructure = pdfBuilder.getStructure();

    // we create array of [Text, ImageB, ImageC, ImageI]
    pdfBuilder.createProcSetArray();

    //create page
    pdfBuilder.createPage(properties);
    PDPage page = pdfStructure.getPage();

    //create template
    pdfBuilder.createTemplate(page);
    PDDocument template = pdfStructure.getTemplate();

    //create /AcroForm
    pdfBuilder.createAcroForm(template);
    PDAcroForm acroForm = pdfStructure.getAcroForm();

    // AcroForm contains singature fields
    pdfBuilder.createSignatureField(acroForm);
    PDSignatureField pdSignatureField = pdfStructure.getSignatureField();

    // create signature
    pdfBuilder.createSignature(pdSignatureField, page, properties.getSignatureFieldName());

    // that is /AcroForm/DR entry
    pdfBuilder.createAcroFormDictionary(acroForm, pdSignatureField);

    // create AffineTransform
    pdfBuilder.createAffineTransform(properties.getAffineTransformParams());
    AffineTransform transform = pdfStructure.getAffineTransform();

    // rectangle, formatter, image. /AcroForm/DR/XObject contains that form
    pdfBuilder.createSignatureRectangle(pdSignatureField, properties);
    pdfBuilder.createFormaterRectangle(properties.getFormaterRectangleParams());
    PDRectangle formater = pdfStructure.getFormaterRectangle();
    pdfBuilder.createSignatureImage(template, properties.getImage());

    // create form stream, form and  resource. 
    pdfBuilder.createHolderFormStream(template);
    PDStream holderFormStream = pdfStructure.getHolderFormStream();
    pdfBuilder.createHolderFormResources();
    PDResources holderFormResources = pdfStructure.getHolderFormResources();
    pdfBuilder.createHolderForm(holderFormResources, holderFormStream, formater);

    // that is /AP entry the appearance dictionary.
    pdfBuilder.createAppearanceDictionary(pdfStructure.getHolderForm(), pdSignatureField);

    // inner form stream, form and resource (hlder form containts inner form)
    pdfBuilder.createInnerFormStream(template);
    pdfBuilder.createInnerFormResource();
    PDResources innerFormResource = pdfStructure.getInnerFormResources();
    pdfBuilder.createInnerForm(innerFormResource, pdfStructure.getInnterFormStream(), formater);
    PDFormXObject innerForm = pdfStructure.getInnerForm();

    // inner form must be in the holder form as we wrote
    pdfBuilder.insertInnerFormToHolerResources(innerForm, holderFormResources);

    //  Image form is in this structure: /AcroForm/DR/FRM0/Resources/XObject/n0
    pdfBuilder.createImageFormStream(template);
    PDStream imageFormStream = pdfStructure.getImageFormStream();
    pdfBuilder.createImageFormResources();
    PDResources imageFormResources = pdfStructure.getImageFormResources();
    pdfBuilder.createImageForm(imageFormResources, innerFormResource, imageFormStream, formater, transform,
            pdfStructure.getImage());

    // now inject procSetArray
    pdfBuilder.injectProcSetArray(innerForm, page, innerFormResource, imageFormResources, holderFormResources,
            pdfStructure.getProcSet());

    COSName imgFormName = pdfStructure.getImageFormName();
    COSName imgName = pdfStructure.getImageName();
    COSName innerFormName = pdfStructure.getInnerFormName();

    // now create Streams of AP
    pdfBuilder.injectAppearanceStreams(holderFormStream, imageFormStream, imageFormStream, imgFormName, imgName,
            innerFormName, properties);
    pdfBuilder.createVisualSignature(template);
    pdfBuilder.createWidgetDictionary(pdSignatureField, holderFormResources);

    ByteArrayInputStream in = pdfStructure.getTemplateAppearanceStream();
    logger.info("stream returning started, size= " + in.available());

    // we must close the document
    template.close();

    // return result of the stream 
    return in;
}

From source file:org.geoserver.wfs.response.SpatiaLiteOutputFormatTest.java

/**
 * Test not null content.//from   w w  w. j av  a2s.  co  m
 * @throws Exception
 */
public void testContentNotNull() throws Exception {
    MockHttpServletResponse resp = getAsServletResponse(
            "wfs?request=GetFeature&typeName=Points&outputFormat=spatialite");
    ByteArrayInputStream sResponse = getBinaryInputStream(resp);
    int dataLengh = sResponse.available();
    boolean contentNull = true;
    byte[] data = new byte[dataLengh];
    sResponse.read(data);
    for (byte aByte : data)
        if (aByte != 0) {
            contentNull = false;
            break;
        }
    assertFalse(contentNull);
}

From source file:com.wabacus.config.database.type.AbsDatabaseType.java

public void setBlobValue(int iindex, byte[] value, PreparedStatement pstmt) throws SQLException {
    if (value == null) {
        pstmt.setBinaryStream(iindex, null, 0);
    } else {/*from  w  w w . j a  v a 2 s .  co m*/
        try {
            ByteArrayInputStream in = Tools.getInputStreamFromBytesArray(value);
            pstmt.setBinaryStream(iindex, in, in.available());
            in.close();
        } catch (IOException e) {
            throw new WabacusRuntimeException("??", e);
        }
    }
}

From source file:org.eclipse.swt.snippets.Snippet319.java

public void go() {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 319");
    shell.setBounds(10, 10, 600, 200);//from  w w  w .j a v  a 2 s. c  o  m

    /* Create SWT controls and add drag source */
    final Label swtLabel = new Label(shell, SWT.BORDER);
    swtLabel.setBounds(10, 10, 580, 50);
    swtLabel.setText("SWT drag source");
    DragSource dragSource = new DragSource(swtLabel, DND.DROP_COPY);
    dragSource.setTransfer(new MyTypeTransfer());
    dragSource.addDragListener(new DragSourceAdapter() {
        @Override
        public void dragSetData(DragSourceEvent event) {
            MyType object = new MyType();
            object.name = "content dragged from SWT";
            object.time = System.currentTimeMillis();
            event.data = object;
        }
    });

    /* Create AWT/Swing controls */
    Composite embeddedComposite = new Composite(shell, SWT.EMBEDDED);
    embeddedComposite.setBounds(10, 100, 580, 50);
    embeddedComposite.setLayout(new FillLayout());
    Frame frame = SWT_AWT.new_Frame(embeddedComposite);
    final JLabel jLabel = new JLabel("AWT/Swing drop target");
    frame.add(jLabel);

    /* Register the custom data flavour */
    final DataFlavor flavor = new DataFlavor(MIME_TYPE, "MyType custom flavor");
    /*
     * Note that according to jre/lib/flavormap.properties, the preferred way to
     * augment the default system flavor map is to specify the AWT.DnD.flavorMapFileURL
     * property in an awt.properties file.
     *
     * This snippet uses the alternate approach below in order to provide a simple
     * stand-alone snippet that demonstrates the functionality.  This implementation
     * works well, but if the instanceof check below fails for some reason when used
     * in a different context then the drop will not be accepted.
     */
    FlavorMap map = SystemFlavorMap.getDefaultFlavorMap();
    if (map instanceof SystemFlavorMap) {
        SystemFlavorMap systemMap = (SystemFlavorMap) map;
        systemMap.addFlavorForUnencodedNative(MIME_TYPE, flavor);
    }

    /* add drop target */
    DropTargetListener dropTargetListener = new DropTargetAdapter() {
        @Override
        public void drop(DropTargetDropEvent dropTargetDropEvent) {
            try {
                dropTargetDropEvent.acceptDrop(DnDConstants.ACTION_COPY);
                ByteArrayInputStream inStream = (ByteArrayInputStream) dropTargetDropEvent.getTransferable()
                        .getTransferData(flavor);
                int available = inStream.available();
                byte[] bytes = new byte[available];
                inStream.read(bytes);
                MyType object = restoreFromByteArray(bytes);
                String string = object.name + ": " + new Date(object.time).toString();
                jLabel.setText(string);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    new DropTarget(jLabel, dropTargetListener);

    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:org.apache.sandesha2.storage.jdbc.PersistentStorageManager.java

synchronized public void storeMessageContext(String key, MessageContext msgContext)
        throws SandeshaStorageException {
    if (log.isDebugEnabled())
        log.debug("Enter storeMessageContext for key " + key + " context " + msgContext);
    storageMap.put(key, msgContext);// w w w.j a v a 2 s .c om
    try {
        PreparedStatement pstmt = getDbConnection()
                .prepareStatement("insert into wsrm_msgctx(ctx_key,ctx)values(?,?)");
        pstmt.setString(1, key);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        msgContext.writeExternal(oos);
        oos.close();
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        pstmt.setBinaryStream(2, bais, bais.available());
        pstmt.execute();
        pstmt.close();
    } catch (Exception ex) {
        throw new SandeshaStorageException(ex);
    }
}

From source file:org.apache.sandesha2.storage.jdbc.PersistentStorageManager.java

synchronized public void updateMessageContext(String key, MessageContext msgContext)
        throws SandeshaStorageException {
    if (log.isDebugEnabled())
        log.debug("updateMessageContext key : " + key);
    storageMap.put(key, msgContext);/*  www .  java  2 s . c om*/
    PreparedStatement pstmt = null;
    try {
        pstmt = getDbConnection()
                .prepareStatement("update wsrm_msgctx set ctx=?" + "where ctx_key='" + key + "'");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        msgContext.writeExternal(oos);
        oos.close();
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        pstmt.setBinaryStream(1, bais, bais.available());
        pstmt.executeQuery();
        pstmt.close();
    } catch (Exception ex) {
        throw new SandeshaStorageException("Exception in updateMessageContext", ex);
    }
}

From source file:org.glukit.dexcom.sync.responses.ManufacturingDataDatabasePagesResponse.java

public List<ManufacturingParameters> getManufacturingParameters() {
    List<ManufacturingParameters> manufacturingParameters = newArrayList();
    try {/*from www .  j a  va2  s. c  o m*/
        for (DatabasePage page : getPages()) {
            ByteArrayInputStream inputStream = new ByteArrayInputStream(page.getPageData());
            DataInput input = this.dataInputFactory.create(inputStream);
            // TODO: something better than ignoring the data?
            long systemSeconds = UnsignedInts.toLong(input.readInt());
            long displaySeconds = UnsignedInts.toLong(input.readInt());

            byte[] xmlBytes = new byte[inputStream.available() - 2];
            input.readFully(xmlBytes);

            validateCrc(input.readUnsignedShort(), page.getPageData());

            XmlMapper xmlMapper = new XmlMapper();
            ManufacturingParameters parameterPage = xmlMapper.readValue(new String(xmlBytes, "UTF-8"),
                    ManufacturingParameters.class);
            manufacturingParameters.add(parameterPage);
        }
        return manufacturingParameters;
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.biokoframework.http.RequestWrapper.java

@Override
public ServletInputStream getInputStream() throws IOException {
    final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);

    ServletInputStream inputStream = new ServletInputStream() {
        public int read() throws IOException {
            return byteArrayInputStream.read();
        }/* ww  w . j  av a 2  s.  c o  m*/

        @Override
        public boolean isFinished() {
            return byteArrayInputStream.available() > 0;
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setReadListener(ReadListener readListener) {
            // TODO Auto-generated method stub

        }
    };

    return inputStream;
}