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:org.datanucleus.store.hbase.fieldmanager.FetchFieldManager.java

private double fetchDoubleInternal(AbstractMemberMetaData mmd, byte[] bytes) {
    double value;
    if (bytes == null) {
        // Handle missing field
        String dflt = HBaseUtils.getDefaultValueForMember(mmd);
        if (dflt != null) {
            return Double.valueOf(dflt).doubleValue();
        }//from  ww w .ja v  a2s . com
        return 0;
    }

    if (mmd.isSerialized()) {
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bis);
            value = ois.readDouble();
            ois.close();
            bis.close();
        } catch (IOException e) {
            throw new NucleusException(e.getMessage(), e);
        }
    } else {
        value = Bytes.toDouble(bytes);
    }
    return value;
}

From source file:com.reydentx.core.common.PhotoUtils.java

public static byte[] resizeImage(ByteArrayInputStream data, int img_width, int img_height, boolean isPNG) {
    BufferedImage originalImage;/*ww  w . ja  v a  2 s . c  om*/
    try {
        originalImage = ImageIO.read(data);
        Dimension origDimentsion = new Dimension(originalImage.getWidth(), originalImage.getHeight());
        Dimension fitDimentsion = new Dimension(img_width, img_height);

        // Dimension dimentsion = getScaledDimension(origDimentsion, fitDimentsion);
        Dimension dimentsion = fitDimentsion;
        if (origDimentsion.width != dimentsion.width || origDimentsion.height != dimentsion.height) {

            ByteArrayOutputStream outstream = new ByteArrayOutputStream();
            BufferedImage resizedImage = Scalr.resize(originalImage, Scalr.Method.QUALITY, Scalr.Mode.FIT_EXACT,
                    dimentsion.width, dimentsion.height, Scalr.OP_ANTIALIAS);

            if (isPNG) {
                ImageIO.write(resizedImage, "png", outstream);
            } else {
                ImageIO.write(resizedImage, "jpg", outstream);
            }

            return outstream.toByteArray();
        } else {
            data.reset();
            ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
            byte[] read = new byte[2048];
            int i = 0;
            while ((i = data.read(read)) > 0) {
                byteArray.write(read, 0, i);
            }
            data.close();
            return byteArray.toByteArray();
        }
    } catch (Exception ex) {
    }
    return null;
}

From source file:org.datanucleus.store.hbase.fieldmanager.FetchFieldManager.java

private boolean fetchBooleanInternal(AbstractMemberMetaData mmd, byte[] bytes) {
    boolean value;
    if (bytes == null) {
        // Handle missing field
        String dflt = HBaseUtils.getDefaultValueForMember(mmd);
        if (dflt != null) {
            return Boolean.valueOf(dflt).booleanValue();
        }//  w w w .  j a  v a  2 s .c  o m
        return false;
    }

    if (mmd.isSerialized()) {
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bis);
            value = ois.readBoolean();
            ois.close();
            bis.close();
        } catch (IOException e) {
            throw new NucleusException(e.getMessage(), e);
        }
    } else {
        value = Bytes.toBoolean(bytes);
    }
    return value;
}

From source file:org.datanucleus.store.hbase.fieldmanager.FetchFieldManager.java

public String fetchStringField(int fieldNumber) {
    String value;/*from   w  w  w  .j av  a  2 s. c  o  m*/
    String familyName = getFamilyName(fieldNumber);
    String columnName = getQualifierName(fieldNumber);
    byte[] bytes = result.getValue(familyName.getBytes(), columnName.getBytes());
    AbstractMemberMetaData mmd = getMemberMetaData(fieldNumber);
    if (bytes == null) {
        // Handle missing field
        return HBaseUtils.getDefaultValueForMember(mmd);
    }

    if (mmd.isSerialized()) {
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bis);
            value = (String) ois.readObject();
            ois.close();
            bis.close();
        } catch (IOException e) {
            throw new NucleusException(e.getMessage(), e);
        } catch (ClassNotFoundException e) {
            throw new NucleusException(e.getMessage(), e);
        }
    } else {
        value = new String(bytes, Charsets.UTF_8);
    }
    return value;
}

From source file:org.exist.webstart.JnlpWriter.java

void sendImage(JnlpHelper jh, JnlpJarFiles jf, String filename, HttpServletResponse response)
        throws IOException {
    logger.debug("Send image " + filename);

    String type = null;/*from  w w w  .  j  av  a 2  s .  co  m*/
    if (filename.endsWith(".gif")) {
        type = "image/gif";
    } else if (filename.endsWith(".png")) {
        type = "image/png";
    } else {
        type = "image/jpeg";
    }

    final InputStream is = this.getClass().getResourceAsStream("resources/" + filename);
    if (is == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "Image file '" + filename + "' not found.");
        return;
    }

    // Copy data
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOUtils.copy(is, baos);
    IOUtils.closeQuietly(is);

    // It is very improbable that a 64 bit jar is needed, but
    // it is better to be ready
    response.setContentType(type);
    response.setContentLength(baos.size());
    //response.setHeader("Content-Length", ""+baos.size());

    final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    final ServletOutputStream os = response.getOutputStream();

    try {
        IOUtils.copy(bais, os);
    } catch (final IllegalStateException ex) {
        logger.debug(ex.getMessage());
    } catch (final IOException ex) {
        logger.debug("Ignored IOException for '" + filename + "' " + ex.getMessage());
    }

    // Release resources
    os.flush();
    os.close();
    bais.close();
}

From source file:org.pgptool.gui.encryption.implpgp.EncryptionServicePgpImpl.java

@Override
public String encryptText(String sourceText, Collection<Key> recipients) {
    try {/*w  w  w  .j  a v  a  2 s.co  m*/
        PGPEncryptedDataGenerator dataGenerator = buildEncryptedDataGenerator(
                buildKeysListForEncryption(recipients));

        SourceInfo encryptionSourceInfo = new SourceInfo("text.asc", sourceText.length(),
                System.currentTimeMillis());
        ByteArrayOutputStream pOut = new ByteArrayOutputStream();
        ByteArrayInputStream pIn = new ByteArrayInputStream(sourceText.getBytes("UTF-8"));
        ArmoredOutputStream armoredOut = new ArmoredOutputStream(pOut);
        doEncryptFile(pIn, encryptionSourceInfo, armoredOut, dataGenerator, null, PGPLiteralData.BINARY);
        pIn.close();
        armoredOut.flush();
        armoredOut.close();
        return pOut.toString();
    } catch (Throwable t) {
        throw new RuntimeException("Encryption failed", t);
    }
}

From source file:com.ethanruffing.preferenceabstraction.AutoPreferences.java

/**
 * Reads the stored value for an Object preference.
 *
 * @param key The key that the preference is stored under.
 * @param def The default value to return if a setting is not found for the
 *            given key./*from w ww .ja v a 2  s .  co  m*/
 * @return The value stored for the preference, or the default value on
 * failure.
 */
@Override
public Object getObject(String key, Object def) {
    if (configType == ConfigurationType.SYSTEM) {
        byte[] inArr = prefs.getByteArray(key, null);
        if (inArr == null)
            return def;

        ByteArrayInputStream bis = new ByteArrayInputStream(inArr);
        ObjectInput in = null;
        try {
            in = new ObjectInputStream(bis);
            return in.readObject();
        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
            return def;
        } finally {
            try {
                bis.close();
            } catch (IOException ex) {
                // ignore close exception
            }
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                // ignore close exception
            }
        }
    } else {
        Object val = fileConfig.getProperty(key);
        if (val == null)
            return def;
        else
            return val;
    }
}

From source file:lvge.com.myapp.modules.shop_management.NotAuthenticationFragment.java

private String saveBitmap(String name, Bitmap bitmap) throws IOException {
    File sd = Environment.getExternalStorageDirectory();
    boolean can_write = sd.canWrite();

    // Bitmap bitm = convertViewToBitMap(sale_consultant_two_iamgeview);
    String strPath = Environment.getExternalStorageDirectory().toString() + "/save";

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);

    if (baos.toByteArray().length / 1024 > 500) {
        int option = 90;
        while (baos.toByteArray().length / 1024 > 500) {
            baos.reset();/* w w  w .ja  va2  s.c  o m*/
            bitmap.compress(Bitmap.CompressFormat.PNG, option, baos);
            option -= 10;
        }
        ByteArrayInputStream isbm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isbm, null, null);

        isbm.close();
    }
    baos.close();

    try {
        File desDir = new File(strPath);
        if (!desDir.exists()) {
            desDir.mkdir();
        }

        File imageFile = new File(strPath + "/" + name + ".PNG");
        if (imageFile.exists()) {
            imageFile.delete();
        }
        imageFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(imageFile);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return strPath + "/" + name + ".PNG";
}

From source file:com.github.dactiv.fear.service.service.account.AccountService.java

/**
 * ?/*from   w  w  w  .j a  va2  s . c o  m*/
 *
 * @param user  Map
 * @param bytes ? bytes
 */
public void updateUserPortrait(Map<String, Object> user, byte[] bytes) throws IOException {
    File uploadPortrait = new File(principalPortraitPath);

    if (!uploadPortrait.exists() && !uploadPortrait.mkdirs()) {
        throw new ServiceException(uploadPortrait.getAbsolutePath() + "?");
    }

    File file = new File(principalPortraitPath + user.get("id") + File.separator);

    if ((!file.exists() && !file.mkdirs()) || !file.isDirectory()) {
        throw new ServiceException(file.getAbsolutePath() + "??");
    }

    String portraitPath = file.getAbsolutePath() + File.separator;
    String sourcePath = portraitPath + PORTRAIT_PIC_SOURCE_NAME;

    // ?
    FileOutputStream os = new FileOutputStream(sourcePath);
    ByteArrayInputStream is = new ByteArrayInputStream(bytes);

    IOUtils.copy(is, os);

    is.close();
    os.close();

    // ???
    for (PortraitSize portraitSize : PortraitSize.values()) {
        scaleImage(sourcePath, portraitPath, portraitSize);
    }
}

From source file:org.apache.cloudstack.saml.SAML2AuthManagerImpl.java

protected boolean initSP() {
    KeystoreVO keyStoreVO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_KEYPAIR);
    if (keyStoreVO == null) {
        try {//from   w ww .j  av a  2s  .  co  m
            KeyPair keyPair = SAMLUtils.generateRandomKeyPair();
            _ksDao.save(SAMLPluginConstants.SAMLSP_KEYPAIR, SAMLUtils.savePrivateKey(keyPair.getPrivate()),
                    SAMLUtils.savePublicKey(keyPair.getPublic()), "samlsp-keypair");
            keyStoreVO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_KEYPAIR);
            s_logger.info("No SAML keystore found, created and saved a new Service Provider keypair");
        } catch (NoSuchProviderException | NoSuchAlgorithmException e) {
            s_logger.error("Unable to create and save SAML keypair: " + e.toString());
        }
    }

    String spId = SAMLServiceProviderID.value();
    String spSsoUrl = SAMLServiceProviderSingleSignOnURL.value();
    String spSloUrl = SAMLServiceProviderSingleLogOutURL.value();
    String spOrgName = SAMLServiceProviderOrgName.value();
    String spOrgUrl = SAMLServiceProviderOrgUrl.value();
    String spContactPersonName = SAMLServiceProviderContactPersonName.value();
    String spContactPersonEmail = SAMLServiceProviderContactEmail.value();
    KeyPair spKeyPair = null;
    X509Certificate spX509Key = null;
    if (keyStoreVO != null) {
        PrivateKey privateKey = SAMLUtils.loadPrivateKey(keyStoreVO.getCertificate());
        PublicKey publicKey = SAMLUtils.loadPublicKey(keyStoreVO.getKey());
        if (privateKey != null && publicKey != null) {
            spKeyPair = new KeyPair(publicKey, privateKey);
            KeystoreVO x509VO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_X509CERT);
            if (x509VO == null) {
                try {
                    spX509Key = SAMLUtils.generateRandomX509Certificate(spKeyPair);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    ObjectOutput out = new ObjectOutputStream(bos);
                    out.writeObject(spX509Key);
                    out.flush();
                    _ksDao.save(SAMLPluginConstants.SAMLSP_X509CERT,
                            Base64.encodeBase64String(bos.toByteArray()), "", "samlsp-x509cert");
                    bos.close();
                } catch (NoSuchAlgorithmException | NoSuchProviderException | CertificateEncodingException
                        | SignatureException | InvalidKeyException | IOException e) {
                    s_logger.error("SAML Plugin won't be able to use X509 signed authentication");
                }
            } else {
                try {
                    ByteArrayInputStream bi = new ByteArrayInputStream(
                            Base64.decodeBase64(x509VO.getCertificate()));
                    ObjectInputStream si = new ObjectInputStream(bi);
                    spX509Key = (X509Certificate) si.readObject();
                    bi.close();
                } catch (IOException | ClassNotFoundException ignored) {
                    s_logger.error(
                            "SAML Plugin won't be able to use X509 signed authentication. Failed to load X509 Certificate from Database.");
                }
            }
        }
    }
    if (spKeyPair != null && spX509Key != null && spId != null && spSsoUrl != null && spSloUrl != null
            && spOrgName != null && spOrgUrl != null && spContactPersonName != null
            && spContactPersonEmail != null) {
        _spMetadata.setEntityId(spId);
        _spMetadata.setOrganizationName(spOrgName);
        _spMetadata.setOrganizationUrl(spOrgUrl);
        _spMetadata.setContactPersonName(spContactPersonName);
        _spMetadata.setContactPersonEmail(spContactPersonEmail);
        _spMetadata.setSsoUrl(spSsoUrl);
        _spMetadata.setSloUrl(spSloUrl);
        _spMetadata.setKeyPair(spKeyPair);
        _spMetadata.setSigningCertificate(spX509Key);
        _spMetadata.setEncryptionCertificate(spX509Key);
        return true;
    }
    return false;
}