Example usage for java.io FileOutputStream flush

List of usage examples for java.io FileOutputStream flush

Introduction

In this page you can find the example usage for java.io FileOutputStream flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:Main.java

public static void takeScreenshot(String fileName, String directory, View view, int quality) {
    Bitmap bitmap = null;/*w w w.j  a va  2s  . c o m*/
    FileOutputStream fos = null;
    view.buildDrawingCache(false);
    bitmap = view.getDrawingCache();
    try {
        fos = new FileOutputStream(directory + File.separator + fileName);
        if (fileName.endsWith(".png")) {
            bitmap.compress(Bitmap.CompressFormat.PNG, quality, fos);
        } else if (fileName.endsWith(".jpg")) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fos);
        }
        fos.flush();
        fos.close();
    } catch (Exception e) {
        Log.e(TAG,
                "Can't save the screenshot! Requires write permission (android.permission.WRITE_EXTERNAL_STORAGE) in AndroidManifest.xml of the application under test.");
        e.printStackTrace();
    }
}

From source file:it.cnr.icar.eric.client.xml.registry.util.CertificateUtil.java

/**
 * Generate a self signed certificate and store it in the keystore.
 * // w  w w .  java  2s  .  c om
 * @param userRegInfo
 * @throws JAXRException
 */
public static void generateRegistryIssuedCertificate(UserRegistrationInfo userRegInfo) throws JAXRException {
    User user = userRegInfo.getUser();
    LifeCycleManager lcm = user.getLifeCycleManager();
    String dname = getDNameFromUser(userRegInfo);
    File keystoreFile = KeystoreUtil.getKeystoreFile();
    KeystoreUtil.createKeystoreDirectory(keystoreFile);
    String keystoreType = ProviderProperties.getInstance().getProperty("jaxr-ebxml.security.storetype", "JKS");
    String storePassStr = new String(userRegInfo.getStorePassword());
    String keyPassStr = new String(userRegInfo.getKeyPassword());
    String alias = userRegInfo.getAlias();
    String keyAlg = "RSA"; // XWSS does not support DSA which is default is
    // KeyTool. Hmm. Weird.

    String[] args = { "-genkey", "-keyAlg", keyAlg, "-alias", alias, "-keypass", keyPassStr, "-keystore",
            keystoreFile.getAbsolutePath(), "-storepass", storePassStr, "-storetype", keystoreType, "-dname",
            dname };

    try {
        KeyTool keytool = new KeyTool();
        keytool.run(args, System.out);

        // Now load the KeyStore and get the cert
        FileInputStream fis = new FileInputStream(keystoreFile);

        KeyStore keyStore = KeyStore.getInstance(keystoreType);
        keyStore.load(fis, storePassStr.toCharArray());
        fis.close();

        X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
        Certificate[] certChain = getCertificateSignedByRegistry(lcm, cert);
        Key key = keyStore.getKey(alias, userRegInfo.getKeyPassword());

        // Now overwrite original cert with signed cert
        keyStore.deleteEntry(alias);

        // keyStore.setCertificateEntry(alias, cert);
        keyStore.setKeyEntry(alias, key, userRegInfo.getKeyPassword(), certChain);
        FileOutputStream fos = new java.io.FileOutputStream(keystoreFile);
        keyStore.store(fos, storePassStr.toCharArray());
        fos.flush();
        fos.close();
    } catch (Exception e) {
        throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CertGenFailed"), e);
    }

    log.debug(JAXRResourceBundle.getInstance().getString("message.StoredUserInKeyStore",
            new Object[] { alias, keystoreFile.getAbsolutePath() }));

    try {
        // Export registry issued cert to certFile so it can be available
        // for import into a web browser for SSL access to registry
        exportRegistryIssuedCert(userRegInfo);
    } catch (Exception e) {
        String msg = JAXRResourceBundle.getInstance().getString(
                "message.UnableToExportCertificateSeeNextExceptionNoteThatThisFeatureRequiresUseOfJDK5");
        log.warn(msg, e);
        // Do not throw exception as user reg can be done despite not
        // exporting the p12 file for the web browser.
    }
}

From source file:Main.java

public static boolean saveBitmap(Bitmap aBmp, String aPath) {
    if (aBmp == null || aPath == null) {
        return false;
    }//from w  w w  .  jav a2s  . c  o  m
    FileOutputStream fos = null;
    ByteArrayOutputStream baos = null;
    boolean result;
    try {
        File file = new File(aPath);
        if (!file.exists()) {
            file.createNewFile();
        }
        fos = new FileOutputStream(file);
        baos = new ByteArrayOutputStream();
        aBmp.compress(Bitmap.CompressFormat.PNG, 100, baos); //SUPPRESS CHECKSTYLE
        fos.write(baos.toByteArray());
        baos.flush();
        fos.flush();

        result = true;
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        result = false;
    } catch (Exception e) {
        e.printStackTrace();
        result = false;
    } finally {
        try {
            if (baos != null) {
                baos.close();
            }
            if (fos != null) {
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return result;
}

From source file:com.enderville.enderinstaller.util.InstallScript.java

/**
 * Unpacks all the contents of the old minecraft.jar to the temp directory.
 *
 * @param tmpdir The temp directory to unpack to.
 * @param mcjar The location of the old minecraft.jar
 * @throws IOException//from   ww w . j a va 2  s .  com
 */
public static void unpackMCJar(File tmpdir, File mcjar) throws IOException {
    byte[] dat = new byte[4 * 1024];
    JarFile jar = new JarFile(mcjar);
    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String name = entry.getName();
        //This gets rid of META-INF if it exists.
        if (name.startsWith("META-INF")) {
            continue;
        }
        InputStream in = jar.getInputStream(entry);
        File dest = new File(FilenameUtils.concat(tmpdir.getPath(), name));
        if (entry.isDirectory()) {
            //I don't think this actually happens
            LOGGER.warn("Found a directory while iterating over jar.");
            dest.mkdirs();
        } else if (!dest.getParentFile().exists()) {
            if (!dest.getParentFile().mkdirs()) {
                throw new IOException("Couldn't create directory for " + name);
            }
        }
        FileOutputStream out = new FileOutputStream(dest);
        int len = -1;
        while ((len = in.read(dat)) > 0) {
            out.write(dat, 0, len);
        }
        out.flush();
        out.close();
        in.close();
    }
}

From source file:Main.java

public static boolean saveJPEGBitmap(Bitmap aBmp, String aPath) {
    if (aBmp == null || aPath == null) {
        return false;
    }/*from  w w w  .  j  av  a2 s.c o  m*/

    FileOutputStream fos = null;
    ByteArrayOutputStream baos = null;
    boolean result = false;
    try {
        File file = new File(aPath);
        if (!file.exists()) {
            file.createNewFile();
        }
        fos = new FileOutputStream(file);
        baos = new ByteArrayOutputStream();
        aBmp.compress(Bitmap.CompressFormat.JPEG, 100, baos); //SUPPRESS CHECKSTYLE
        fos.write(baos.toByteArray());
        baos.flush();
        fos.flush();

        result = true;
    } catch (Error e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
        result = false;
    } finally {
        try {
            if (baos != null) {
                baos.close();
            }
            if (fos != null) {
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return result;
}

From source file:it.cnr.icar.eric.client.xml.registry.util.CertificateUtil.java

@SuppressWarnings("static-access")
private static Certificate[] getCertificateSignedByRegistry(LifeCycleManager lcm, X509Certificate inCert)
        throws JAXRException {
    Certificate[] certChain = new Certificate[2];

    try {/*from   w w w  .ja v a 2 s.c o m*/
        // Save cert in a temporary keystore file which is sent as
        // repository item to server so it can be signed
        KeyStore tmpKeystore = KeyStore.getInstance("JKS");
        tmpKeystore.load(null, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray());

        tmpKeystore.setCertificateEntry(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_REQ, inCert);
        File repositoryItemFile = File.createTempFile(".eric-ca-req", ".jks");
        repositoryItemFile.deleteOnExit();
        FileOutputStream fos = new java.io.FileOutputStream(repositoryItemFile);
        tmpKeystore.store(fos, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray());
        fos.flush();
        fos.close();

        // Now have server sign the cert using extensionRequest
        javax.activation.DataHandler repositoryItem = new DataHandler(new FileDataSource(repositoryItemFile));
        String id = it.cnr.icar.eric.common.Utility.getInstance().createId();
        HashMap<String, Object> idToRepositoryItemsMap = new HashMap<String, Object>();
        idToRepositoryItemsMap.put(id, repositoryItem);

        HashMap<String, String> slotsMap = new HashMap<String, String>();
        slotsMap.put(BindingUtility.FREEBXML_REGISTRY_PROTOCOL_SIGNCERT, "true");

        RegistryRequestType req = bu.rsFac.createRegistryRequestType();
        bu.addSlotsToRequest(req, slotsMap);

        RegistryResponseHolder respHolder = ((LifeCycleManagerImpl) lcm).extensionRequest(req,
                idToRepositoryItemsMap);
        DataHandler responseRepositoryItem = (DataHandler) respHolder.getAttachmentsMap().get(id);

        InputStream is = responseRepositoryItem.getInputStream();
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(is, bu.FREEBXML_REGISTRY_KS_PASS_RESP.toCharArray());
        is.close();

        certChain[0] = keyStore.getCertificate(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_RESP);
        if (certChain[0] == null) {
            throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CannotFindUserCert"));
        }
        certChain[1] = keyStore.getCertificate(bu.FREEBXML_REGISTRY_CACERT_ALIAS);
        if (certChain[1] == null) {
            throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CannotFindCARootCert"));
        }
    } catch (Exception e) {
        throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CertSignFailed"), e);
    }

    return certChain;
}

From source file:com.ibuildapp.romanblack.CataloguePlugin.imageloader.Utils.java

public static String downloadFile(Context context, String url, String md5) {
    final int BYTE_ARRAY_SIZE = 8024;
    final int CONNECTION_TIMEOUT = 30000;
    final int READ_TIMEOUT = 30000;

    try {//from w  ww .  ja v a 2  s.c  om
        for (int i = 0; i < 3; i++) {
            URL fileUrl = new URL(URLDecoder.decode(url));
            HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection();
            connection.setConnectTimeout(CONNECTION_TIMEOUT);
            connection.setReadTimeout(READ_TIMEOUT);
            connection.connect();

            int status = connection.getResponseCode();

            if (status >= HttpStatus.SC_BAD_REQUEST) {
                connection.disconnect();

                continue;
            }

            BufferedInputStream bufferedInputStream = new BufferedInputStream(connection.getInputStream());
            File file = new File(StaticData.getCachePath(context) + md5);

            if (!file.exists()) {
                new File(StaticData.getCachePath(context)).mkdirs();
                file.createNewFile();
            }

            FileOutputStream fileOutputStream = new FileOutputStream(file, false);
            int byteCount;
            byte[] buffer = new byte[BYTE_ARRAY_SIZE];

            while ((byteCount = bufferedInputStream.read(buffer, 0, BYTE_ARRAY_SIZE)) != -1)
                fileOutputStream.write(buffer, 0, byteCount);

            bufferedInputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();

            return file.getAbsolutePath();
        }
    } catch (Exception e) {
        e.printStackTrace();

        return null;
    }

    return null;
}

From source file:org.webinos.android.util.ModuleUtils.java

public static File downloadResource(URI httpUri, String filename) throws IOException {
    /* download */
    HttpClient http = new DefaultHttpClient();
    HttpGet request = new HttpGet();
    request.setURI(httpUri);/*from   w w  w  .j  a va  2s. c o m*/
    HttpEntity entity = http.execute(request).getEntity();
    InputStream in = entity.getContent();
    File destination = new File(resourceDir, filename);
    FileOutputStream out = new FileOutputStream(destination);
    byte[] buf = new byte[1024];
    int read;
    while ((read = in.read(buf)) != -1) {
        out.write(buf, 0, read);
    }
    in.close();
    out.flush();
    out.close();
    return destination;
}

From source file:com.easysoft.build.utils.PatchUtil.java

/**
 * /*from w w  w  . j a v a2s .  c o m*/
 * @param content 
 * @param dest 
 * @throws java.io.IOException
 */
public static void write2File(String content, File dest) throws IOException {
    byte[] bs = content.getBytes("GBK");
    FileOutputStream out = new FileOutputStream(dest);
    out.write(bs);
    out.flush();
    out.close();
}

From source file:com.pclinuxos.rpm.util.FileUtils.java

/**
 * The method copies a file to an other location. 
 * /*from  ww w.java 2  s .co  m*/
 * @param source file/folder to copy
 * @param dest destination file/folder
 * @return 0 if copying was successfully, 1 if the source file/folder does not exist, 2 if a IOException
 * occurred while copying.
 */
public static byte cp(File source, File dest) {

    byte returnCode = 0;

    try {

        FileInputStream sourceIn = new FileInputStream(source);
        FileOutputStream destOut = new FileOutputStream(dest);

        if (!source.exists()) {

            returnCode = 1;
        }

        // 64kb buffer
        byte[] buffer = new byte[0xFFFF];

        while (sourceIn.read(buffer) != -1) {

            destOut.write(buffer);
        }

        sourceIn.close();
        destOut.flush();
        destOut.close();

    } catch (FileNotFoundException e) {

        returnCode = 1;

    } catch (IOException e) {

        returnCode = 2;
    }

    return returnCode;
}