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:com.tremolosecurity.openunison.util.OpenUnisonUtils.java

public static void main(String[] args) throws Exception {

    logger = org.apache.logging.log4j.LogManager.getLogger(OpenUnisonUtils.class.getName());

    Options options = new Options();
    options.addOption("unisonXMLFile", true, "The full path to the Unison xml file");
    options.addOption("keystorePath", true, "The full path to the Unison keystore");
    options.addOption("chainName", true, "The name of the authentication chain");
    options.addOption("mechanismName", true, "The name of the authentication mechanism for SAML2");
    options.addOption("idpName", true, "The name of the identity provider application");
    options.addOption("pathToMetaData", true, "The full path to the saml2 metadata file");
    options.addOption("createDefault", false, "If set, add default parameters");
    options.addOption("action", true,
            "export-sp-metadata, import-sp-metadata, export-secretkey, print-secretkey, import-idp-metadata, export-idp-metadata, clear-dlq, import-secretkey, create-secretkey");
    options.addOption("urlBase", true, "Base URL, no URI; https://host:port");
    options.addOption("alias", true, "Key alias");
    options.addOption("newKeystorePath", true, "Path to the new keystore");
    options.addOption("newKeystorePassword", true, "Password for the new keystore");
    options.addOption("help", false, "Prints this message");
    options.addOption("signMetadataWithKey", true, "Signs the metadata with the specified key");
    options.addOption("dlqName", true, "The name of the dead letter queue");
    options.addOption("upgradeFrom106", false, "Updates workflows from 1.0.6");
    options.addOption("secretkey", true, "base64 encoded secret key");
    options.addOption("envFile", true, "Environment variables for parmaterized configs");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args, true);

    if (args.length == 0 || cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("OpenUnisonUtils", options);
    }//from www.ja  v a  2s  . co m

    logger.info("Loading Unison Configuration");
    String unisonXMLFile = loadOption(cmd, "unisonXMLFile", options);
    TremoloType ttRead = loadTremoloType(unisonXMLFile, cmd, options);

    String action = loadOption(cmd, "action", options);
    TremoloType ttWrite = null;
    if (action.equalsIgnoreCase("import-sp-metadata") || action.equalsIgnoreCase("import-idp-metadata")) {
        ttWrite = loadTremoloType(unisonXMLFile);
    }

    logger.info("Configuration loaded");

    logger.info("Loading the keystore...");
    String ksPath = loadOption(cmd, "keystorePath", options);

    KeyStore ks = loadKeyStore(ksPath, ttRead);

    logger.info("...loaded");

    if (action.equalsIgnoreCase("import-sp-metadata")) {

        importMetaData(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);
    } else if (action.equalsIgnoreCase("export-sp-metadata")) {
        exportSPMetaData(options, cmd, ttRead, ks);

    } else if (action.equalsIgnoreCase("print-secretkey")) {
        printSecreyKey(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("import-secretkey")) {
        importSecreyKey(options, cmd, ttRead, ks, ksPath);
    } else if (action.equalsIgnoreCase("create-secretkey")) {
        Security.addProvider(new BouncyCastleProvider());
        logger.info("Creating AES-256 secret key");
        String alias = loadOption(cmd, "alias", options);
        logger.info("Alias : '" + alias + "'");
        KeyGenerator kg = KeyGenerator.getInstance("AES", "BC");
        kg.init(256, new SecureRandom());
        SecretKey sk = kg.generateKey();
        ks.setKeyEntry(alias, sk, ttRead.getKeyStorePassword().toCharArray(), null);
        logger.info("Saving key");
        ks.store(new FileOutputStream(ksPath), ttRead.getKeyStorePassword().toCharArray());
        logger.info("Finished");
    } else if (action.equalsIgnoreCase("export-secretkey")) {
        logger.info("Export Secret Key");

        logger.info("Loading key");
        String alias = loadOption(cmd, "alias", options);
        SecretKey key = (SecretKey) ks.getKey(alias, ttRead.getKeyStorePassword().toCharArray());
        logger.info("Loading new keystore path");
        String pathToNewKeystore = loadOption(cmd, "newKeystorePath", options);
        logger.info("Loading new keystore password");
        String ksPassword = loadOption(cmd, "newKeystorePassword", options);

        KeyStore newKS = KeyStore.getInstance("PKCS12");
        newKS.load(null, ttRead.getKeyStorePassword().toCharArray());
        newKS.setKeyEntry(alias, key, ksPassword.toCharArray(), null);
        newKS.store(new FileOutputStream(pathToNewKeystore), ksPassword.toCharArray());
        logger.info("Exported");
    } else if (action.equalsIgnoreCase("import-idp-metadata")) {
        importIdpMetadata(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);

    } else if (action.equalsIgnoreCase("export-idp-metadata")) {
        exportIdPMetadata(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("clear-dlq")) {
        logger.info("Getting the DLQ Name...");
        String dlqName = loadOption(cmd, "dlqName", options);
        QueUtils.emptyDLQ(ttRead, dlqName);
    } else if (action.equalsIgnoreCase("upgradeFrom106")) {
        logger.info("Upgrading OpenUnison's configuration from 1.0.6");

        String backupFileName = unisonXMLFile + ".bak";

        logger.info("Backing up to '" + backupFileName + "'");

        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(unisonXMLFile)));
        PrintWriter out = new PrintWriter(new FileOutputStream(backupFileName));
        String line = null;
        while ((line = in.readLine()) != null) {
            out.println(line);
        }
        out.flush();
        out.close();
        in.close();

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        AddChoiceToTasks.convert(new FileInputStream(unisonXMLFile), bout);
        FileOutputStream fsout = new FileOutputStream(unisonXMLFile);
        fsout.write(bout.toByteArray());
        fsout.flush();
        fsout.close();

    }

}

From source file:gov.nasa.ensemble.dictionary.nddl.ParseInterpreter.java

public static void main(String[] args) throws Exception {
    try {//from  w  w  w  .  j  a v a  2s  .c  o m
        CommandLineArguments cmd = new CommandLineArguments(args);

        // Create a resource set to hold the resources.
        //
        ResourceSet resourceSet = new ResourceSetImpl();

        // Register the package to ensure it is available during loading.
        //
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
                .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());
        resourceSet.getPackageRegistry().put(DictionaryPackage.eNS_URI, DictionaryPackage.eINSTANCE);

        // Construct the URI for the instance file.
        // The argument is treated as a file path only if it denotes an
        // existing file.
        // Otherwise, it's directly treated as a URL.
        //

        File file = new File(cmd.getValue(Option.ACTIVITY_DICTIONARY_FILE));
        URI uri = file.isFile() ? URI.createFileURI(file.getAbsolutePath())
                : URI.createURI(cmd.getValue(Option.ACTIVITY_DICTIONARY_FILE));

        try {
            // Demand load resource for this file.
            //
            Resource resource = resourceSet.getResource(uri, true);
            EActivityDictionary eActivityDictionary = (EActivityDictionary) resource.getContents().get(0);

            ParseInterpreter parseInterpreter = new ParseInterpreter(eActivityDictionary,
                    cmd.getValue(Option.CPU_STATE), cmd.getValue(Option.CPU_VALUE),
                    cmd.getIntValue(Option.BOOT), cmd.getIntValue(Option.SHUTDOWN),
                    cmd.getIntValue(Option.GAP));
            parseInterpreter.interpretAD(false);

            String path = cmd.getValue(Option.OUTPUT_DIRECTORY_PATH);
            path = path + uri.trimFileExtension().lastSegment();

            FileOutputStream objStream = new FileOutputStream(path + "-objects.nddl");
            FileOutputStream modelStream = new FileOutputStream(path + "-model.nddl");
            FileOutputStream initStateStream = new FileOutputStream(path + "-initial-state.nddl");
            objStream.flush();
            modelStream.flush();
            initStateStream.flush();

            parseInterpreter.writeObjects(objStream);
            objStream.close();
            parseInterpreter.writeCompats(modelStream, path + "-objects.nddl");
            modelStream.close();
            parseInterpreter.writeInitialState(initStateStream, path + "-model.nddl");

        } catch (RuntimeException exception) {
            System.out.println("Problem loading " + uri);
            exception.printStackTrace();
        }
    } catch (Exception e) {
        System.out.println(getManPageText());
    }
}

From source file:Main.java

public static void saveImage(File file, byte[] bytes) throws Exception {
    file.delete();//from   ww  w.  ja v  a  2  s.  c o  m
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(bytes);
    fos.flush();
    fos.close();
}

From source file:Main.java

public static void writeFile(byte[] bytes) throws IOException {
    String apkDir = Environment.getExternalStorageDirectory() + "/download/" + "app.apk";
    java.io.File file = new java.io.File(apkDir);
    FileOutputStream fop = new FileOutputStream(file);
    fop.write(bytes);//  w  ww. j  a  va2 s  .c o  m
    fop.flush();
    fop.close();
}

From source file:Main.java

public static void writeFile(File f, byte[] bS) throws Exception {

    if (f.isFile() && f.exists()) {
        f.delete();//from   w  w w. j a  v  a 2s.c  om
    }

    FileOutputStream fos = new FileOutputStream(f);
    fos.write(bS, 0, bS.length);
    fos.flush();
    fos.close();
}

From source file:Main.java

public static void writeBitmapToFile(Bitmap bitmap, File file) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
    byte[] bitmapData = bos.toByteArray();

    //write the bytes in file
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(bitmapData);//from www.  j  ava2 s .  c om
    fos.flush();
    fos.close();
}

From source file:Main.java

public static void saveEncodedFile(String encoded, File file) throws Exception {
    byte[] decodedAsBytes = Base64.decode(encoded, Base64.DEFAULT);

    FileOutputStream os = new FileOutputStream(file, true);
    os.write(decodedAsBytes);//from  ww  w.j a v  a  2  s .c o  m
    os.flush();
    os.close();
}

From source file:Main.java

public static void bitmap2file(Bitmap bitmap, String path) {
    try {//from   w  ww  . j ava2 s  .c  o m
        // create a file to write bitmap data
        File f = new File(path);
        if (f.exists()) {
            f.delete();
            f.createNewFile();
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.JPEG, 30 /* ignored for PNG */, bos);
        byte[] bitmapdata = bos.toByteArray();
        // write the bytes in file
        FileOutputStream fos = new FileOutputStream(f);
        fos.write(bitmapdata);
        fos.flush();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static void compressWithQuality(Bitmap image, String outPath, int maxSize) throws IOException {

    ByteArrayOutputStream os = new ByteArrayOutputStream();

    image.compress(Bitmap.CompressFormat.JPEG, 20, os);

    while (os.toByteArray().length / 1024 > 1024) {
        os.reset();/*from  w w w  . j  a  v  a2  s . c o m*/
        image.compress(Bitmap.CompressFormat.JPEG, 20, os);
    }

    ByteArrayInputStream bi = new ByteArrayInputStream(os.toByteArray());
    BitmapFactory.decodeStream(bi);
    FileOutputStream fi = new FileOutputStream(outPath);
    fi.write(os.toByteArray());
    fi.flush();
    fi.close();

}

From source file:com.aqnote.shared.cryptology.cert.util.PrivateKeyFileUtil.java

public static void writeKeyFile(String b64Key, String keyfile) throws IOException {

    if (StringUtils.isBlank(b64Key) || StringUtils.isBlank(keyfile)) {
        return;//from  w  ww .  j av a 2 s  .  c o m
    }
    FileOutputStream fos2 = new FileOutputStream(keyfile);
    fos2.write(b64Key.getBytes());
    fos2.flush();
    fos2.close();
}