Example usage for java.io ByteArrayInputStream close

List of usage examples for java.io ByteArrayInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closing a ByteArrayInputStream has no effect.

Usage

From source file:hk.hku.cecid.ebms.admin.listener.PartnershipPageletAdaptor.java

private void getCertificateForPartnership(byte[] cert, PropertyTree dom, String prefix) {
    if (cert != null) {
        try {//w w  w  . j a va 2  s  .c o  m
            ByteArrayInputStream bais = new ByteArrayInputStream(cert);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate verifyCert = (X509Certificate) cf.generateCertificate(bais);
            bais.close();
            dom.setProperty(prefix + "issuer", verifyCert.getIssuerDN().getName());
            dom.setProperty(prefix + "subject", verifyCert.getSubjectDN().getName());
            dom.setProperty(prefix + "thumbprint", getCertFingerPrint(verifyCert));
            dom.setProperty(prefix + "valid-from", StringUtilities.toGMTString(verifyCert.getNotBefore()));
            dom.setProperty(prefix + "valid-to", StringUtilities.toGMTString(verifyCert.getNotAfter()));
        } catch (Exception e) {
            dom.setProperty(prefix + "Error", e.toString());
        }
    } else {
        dom.setProperty(prefix, "");
    }
}

From source file:org.apache.jmeter.junit.JMeterTest.java

public void GUIComponents2() throws Exception {
    String name = guiItem.getClass().getName();

    // TODO these assertions should be separate tests

    TestElement el = guiItem.createTestElement();
    assertNotNull(name + ".createTestElement should be non-null ", el);
    assertEquals("GUI-CLASS: Failed on " + name, name, el.getPropertyAsString(TestElement.GUI_CLASS));

    assertEquals("NAME: Failed on " + name, guiItem.getName(), el.getName());
    assertEquals("TEST-CLASS: Failed on " + name, el.getClass().getName(),
            el.getPropertyAsString(TestElement.TEST_CLASS));
    TestElement el2 = guiItem.createTestElement();
    el.setName("hey, new name!:");
    el.setProperty("NOT", "Shouldn't be here");
    if (!(guiItem instanceof UnsharedComponent)) {
        assertEquals("SHARED: Failed on " + name, "", el2.getPropertyAsString("NOT"));
    }/*from w ww.ja v a  2 s .c o  m*/
    log.debug("Saving element: " + el.getClass());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    SaveService.saveElement(el, bos);
    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    bos.close();
    el = (TestElement) SaveService.loadElement(bis);
    bis.close();
    assertNotNull("Load element failed on: " + name, el);
    guiItem.configure(el);
    assertEquals("CONFIGURE-TEST: Failed on " + name, el.getName(), guiItem.getName());
    guiItem.modifyTestElement(el2);
    assertEquals("Modify Test: Failed on " + name, "hey, new name!:", el2.getName());
}

From source file:J2MEWriteReadMixedDataTypesExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);/*w w w . j  av a  2 s.  c  om*/
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
            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();
            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);
            recordstore.closeRecordStore();
            if (RecordStore.listRecordStores() != null) {
                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.hygenics.imaging.ImageCleanup.java

public byte[] writeMetaData(String data, byte[] ibytes) {
    // write metadata based on the metadata columns list
    TiffOutputSet outset = null;/*from  w  w w  .  j  a  va  2 s . com*/
    BufferedImage bi;
    ImageMetadata metadata;
    ByteArrayOutputStream bos = null;
    try {

        // get the buffered image to write to
        bi = Imaging.getBufferedImage(ibytes);
        metadata = Imaging.getMetadata(ibytes);
        JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;

        if (null != jpegMetadata) {
            // get the image exif data
            TiffImageMetadata exif = jpegMetadata.getExif();
            outset = exif.getOutputSet();
        }

        if (outset == null) {
            // get a new set (directory structured to write to)
            outset = new TiffOutputSet();
        }

        TiffOutputDirectory exdir = outset.getOrCreateExifDirectory();
        exdir.removeField(ExifTagConstants.EXIF_TAG_USER_COMMENT);

        exdir.add(ExifTagConstants.EXIF_TAG_USER_COMMENT, data.trim());

        bos = new ByteArrayOutputStream();
        ByteArrayInputStream bis = new ByteArrayInputStream(ibytes);

        ExifRewriter exrw = new ExifRewriter();

        // read to a byte stream
        exrw.updateExifMetadataLossy(bis, bos, outset);

        // read the input from the byte buffer
        ibytes = bos.toByteArray();
        bis.close();
        bos.close();

    } catch (ImageReadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ImageWriteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (bos != null) {
            try {
                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return ibytes;
}

From source file:de.rallye.images.ImageRepository.java

private void scalePicture(File src, String pictureHash, PictureSize size) throws IOException {
    lock.writeLock().lock();/*from   www  . j a  v a 2s. com*/
    try {
        Dimension d = size.getDimension();

        BufferedImage base = ImageIO.read(src);

        BufferedImage out = ImageScaler.scaleImage(base, d);

        File f = getFile(pictureHash, size);

        if (size == PictureSize.Mini || size == PictureSize.Thumbnail) {
            ByteArrayOutputStream bStream = new ByteArrayOutputStream();
            ImageIO.write(out, "jpg", bStream);

            if (size == PictureSize.Thumbnail) {
                thumbCache.put(pictureHash, bStream.toByteArray());
            } else if (size == PictureSize.Mini) {
                miniCache.put(pictureHash, bStream.toByteArray());
            }

            ByteArrayInputStream iStream = new ByteArrayInputStream(bStream.toByteArray());
            BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(f));
            copy(iStream, outStream);
            iStream.close();
            outStream.close();

            bStream.close();
        } else {
            ImageIO.write(out, "jpg", f);
        }

        logger.info("Scaled {} to {} from ({}x{})", pictureHash, size, base.getWidth(), base.getHeight());
    } finally {
        lock.writeLock().unlock();
    }
}

From source file:org.apache.camel.component.shiro.security.ShiroSecurityPolicy.java

public Processor wrap(RouteContext routeContext, final Processor processor) {
    return new AsyncProcessor() {
        public boolean process(Exchange exchange, final AsyncCallback callback) {
            boolean sync;
            try {
                applySecurityPolicy(exchange);
            } catch (Exception e) {
                // exception occurred so break out
                exchange.setException(e);
                callback.done(true);/*from   w ww  .ja v a  2s.  c o  m*/
                return true;
            }

            // If here, then user is authenticated and authorized
            // Now let the original processor continue routing supporting the async routing engine
            AsyncProcessor ap = AsyncProcessorTypeConverter.convert(processor);
            sync = AsyncProcessorHelper.process(ap, exchange, new AsyncCallback() {
                public void done(boolean doneSync) {
                    // we only have to handle async completion of this policy
                    if (doneSync) {
                        return;
                    }
                    callback.done(false);
                }
            });

            if (!sync) {
                // if async, continue routing async
                return false;
            }

            // we are done synchronously, so do our after work and invoke the callback
            callback.done(true);
            return true;
        }

        public void process(Exchange exchange) throws Exception {
            applySecurityPolicy(exchange);
            processor.process(exchange);
        }

        private void applySecurityPolicy(Exchange exchange) throws Exception {
            ByteSource encryptedToken = (ByteSource) exchange.getIn().getHeader("SHIRO_SECURITY_TOKEN");
            ByteSource decryptedToken = getCipherService().decrypt(encryptedToken.getBytes(), getPassPhrase());

            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decryptedToken.getBytes());
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            ShiroSecurityToken securityToken = (ShiroSecurityToken) objectInputStream.readObject();
            objectInputStream.close();
            byteArrayInputStream.close();

            Subject currentUser = SecurityUtils.getSubject();

            // Authenticate user if not authenticated
            try {
                authenticateUser(currentUser, securityToken);

                // Test whether user's role is authorized to perform functions in the permissions list  
                authorizeUser(currentUser, exchange);
            } finally {
                if (alwaysReauthenticate) {
                    currentUser.logout();
                    currentUser = null;
                }
            }

        }
    };
}

From source file:org.guanxi.idp.service.SSOBase.java

/**
 * Extracts the X509 cenrtificate from a KeyDescriptor
 *
 * @param keyDescriptor the KeyDescriptor containing the X509 certificate
 * @return X509Certificate/*from  www.  j  av  a2  s .co m*/
 * @throws GuanxiException if an error occurs
 */
private X509Certificate getCertFromKeyDescriptor(KeyDescriptorType keyDescriptor) throws GuanxiException {
    try {
        byte[] spCertBytes = keyDescriptor.getKeyInfo().getX509DataArray(0).getX509CertificateArray(0);
        CertificateFactory certFactory = CertificateFactory.getInstance("x.509");
        ByteArrayInputStream certByteStream = new ByteArrayInputStream(spCertBytes);
        X509Certificate metadataCert = (X509Certificate) certFactory.generateCertificate(certByteStream);
        certByteStream.close();
        return metadataCert;
    } catch (CertificateException ce) {
        logger.error("can't get x509 from KeyDescriptor");
        throw new GuanxiException(ce);
    } catch (IOException ioe) {
        logger.error("can't close cert byte stream");
        throw new GuanxiException(ioe);
    }
}

From source file:com.sap.dirigible.ide.workspace.wizard.project.create.ProjectTemplateType.java

public static ProjectTemplateType createTemplateType(IRepository repository, String location)
        throws IOException {
    ICollection projectTemplateRoot = repository.getCollection(location);
    if (!projectTemplateRoot.exists()) {
        throw new IOException(String.format(PROJECT_TEMPLATE_LOCATION_S_IS_NOT_VALID, location));
    }//from   w  w w  .  j  a  v a 2  s.c o m
    IResource projectMetadataResource = projectTemplateRoot.getResource("project.properties"); //$NON-NLS-1$
    if (!projectMetadataResource.exists()) {
        throw new IOException(String.format(PROJECT_TEMPLATE_METADATA_DOES_NOT_EXIST_AT_S, location));
    }

    Properties projectMetadata = new Properties();
    ByteArrayInputStream byteArrayInputStream = null;
    try {
        byteArrayInputStream = new ByteArrayInputStream(projectMetadataResource.getContent());
        projectMetadata.load(byteArrayInputStream);

        String name = (String) projectMetadata.get(PARAM_NAME); //$NON-NLS-1$
        String description = (String) projectMetadata.get(PARAM_DESCRIPTION); //$NON-NLS-1$
        String imageName = (String) projectMetadata.get(PARAM_IMAGE); //$NON-NLS-1$
        String imagePreviewName = (String) projectMetadata.get(PARAM_IMAGE_PREVIEW); //$NON-NLS-1$
        String contentName = (String) projectMetadata.get(PARAM_CONTENT); //$NON-NLS-1$

        Image image = createImageFromResource(projectTemplateRoot, imageName);
        Image imagePreview = createImageFromResource(projectTemplateRoot, imagePreviewName);

        IResource contentResource = projectTemplateRoot.getResource(contentName);
        if (!contentResource.exists()) {
            throw new IOException(String.format(PROJECT_TEMPLATE_CONTENT_DOES_NOT_EXIST_AT_S, contentName));
        }

        ProjectTemplateType templateType = new ProjectTemplateType(name, description, location, image,
                imagePreview, contentResource.getPath(), "template");
        return templateType;
    } finally {
        if (byteArrayInputStream != null) {
            byteArrayInputStream.close();
        }
    }
}

From source file:org.apache.axis2.context.externalize.SafeObjectInputStream.java

/**
 * Read hte input stream and place objects in the specified List
 * @param list List/* w w w.ja v  a  2s . c o  m*/
 * @return List or null
 * @throws IOException
 * @see SafeObjectInputStream.writeList()
 */
public List readList(List list) throws IOException {
    boolean isActive = in.readBoolean();
    if (!isActive) {
        return null;
    }

    while (in.readBoolean()) {
        Object value;
        boolean isObjectForm = in.readBoolean();
        try {
            if (isObjectForm) {
                if (isDebug) {
                    log.debug(" reading using object form");
                }
                // Read the value directly
                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);
                value = tempOIS.readObject();
                tempOIS.close();
                bais.close();
            }
            // Put the key and value in the list
            if (isDebug) {
                log.debug("Read value=" + valueName(value));
            }
            list.add(value);
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
            throw AxisFault.makeFault(e);
        }
    }
    return list;
}

From source file:org.eclipse.thym.core.internal.util.BundleHttpCacheStorage.java

@Override
public HttpCacheEntry getEntry(String key) throws IOException {
    File f = getCacheFile(key);/*from   ww  w . ja  v  a  2  s  . c o  m*/
    if (f.exists()) {
        ByteArrayInputStream bais = null;
        ObjectInputStream ois = null;
        HttpCacheEntry entry = null;

        try {
            byte[] bytes = FileUtils.readFileToByteArray(f);
            bais = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(bais);
            entry = (HttpCacheEntry) ois.readObject();
        } catch (ClassNotFoundException e) {
            HybridCore.log(IStatus.ERROR, "Missing bundle", e);
        } finally {
            if (ois != null)
                ois.close();
            if (bais != null)
                bais.close();
        }
        return entry;
    }
    return null;
}