List of usage examples for java.io FileOutputStream close
public void close() throws IOException
From source file:CertificateSigner.java
public static void main(String[] args) { String ksname = null; // the keystore name String alias = null; // the private key alias String inname = null; // the input file name String outname = null; // the output file name for (int i = 0; i < args.length; i += 2) { if (args[i].equals("-keystore")) ksname = args[i + 1];/*www . j a v a 2 s .co m*/ else if (args[i].equals("-alias")) alias = args[i + 1]; else if (args[i].equals("-infile")) inname = args[i + 1]; else if (args[i].equals("-outfile")) outname = args[i + 1]; else usage(); } if (ksname == null || alias == null || inname == null || outname == null) usage(); try { Console console = System.console(); if (console == null) error("No console"); char[] password = console.readPassword("Keystore password: "); KeyStore store = KeyStore.getInstance("JKS", "SUN"); InputStream in = new FileInputStream(ksname); store.load(in, password); Arrays.fill(password, ' '); in.close(); char[] keyPassword = console.readPassword("Key password for %s: ", alias); PrivateKey issuerPrivateKey = (PrivateKey) store.getKey(alias, keyPassword); Arrays.fill(keyPassword, ' '); if (issuerPrivateKey == null) error("No such private key"); in = new FileInputStream(inname); CertificateFactory factory = CertificateFactory.getInstance("X.509"); X509Certificate inCert = (X509Certificate) factory.generateCertificate(in); in.close(); byte[] inCertBytes = inCert.getTBSCertificate(); X509Certificate issuerCert = (X509Certificate) store.getCertificate(alias); Principal issuer = issuerCert.getSubjectDN(); String issuerSigAlg = issuerCert.getSigAlgName(); FileOutputStream out = new FileOutputStream(outname); X509CertInfo info = new X509CertInfo(inCertBytes); info.set(X509CertInfo.ISSUER, new CertificateIssuerName((X500Name) issuer)); X509CertImpl outCert = new X509CertImpl(info); outCert.sign(issuerPrivateKey, issuerSigAlg); outCert.derEncode(out); out.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:Main.java
public static void main(String[] args) throws Exception { String destinationname = "d:\\"; byte[] buf = new byte[1024]; ZipInputStream zipinputstream = null; ZipEntry zipentry;//from ww w . j av a 2s .c om zipinputstream = new ZipInputStream(new FileInputStream("fileName")); zipentry = zipinputstream.getNextEntry(); while (zipentry != null) { String entryName = zipentry.getName(); FileOutputStream fileoutputstream; File newFile = new File(entryName); String directory = newFile.getParent(); if (directory == null) { if (newFile.isDirectory()) break; } fileoutputstream = new FileOutputStream(destinationname + entryName); int n; while ((n = zipinputstream.read(buf, 0, 1024)) > -1) { fileoutputstream.write(buf, 0, n); } fileoutputstream.close(); zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); }
From source file:PersistentEcho.java
public static void main(String[] args) { String argString = ""; boolean notProperty = true; // Are there arguments? // If so retrieve them. if (args.length > 0) { for (String arg : args) { argString += arg + " "; }/*from ww w . j a va 2 s . c o m*/ argString = argString.trim(); } // No arguments, is there // an environment variable? // If so, //retrieve it. else if ((argString = System.getenv("PERSISTENTECHO")) != null) { } // No environment variable // either. Retrieve property value. else { notProperty = false; // Set argString to null. // If it's still null after // we exit the try block, // we've failed to retrieve // the property value. argString = null; FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream("PersistentEcho.txt"); Properties inProperties = new Properties(); inProperties.load(fileInputStream); argString = inProperties.getProperty("argString"); } catch (IOException e) { System.err.println("Can't read property file."); System.exit(1); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { } ; } } } if (argString == null) { System.err.println("Couldn't find argString property"); System.exit(1); } // Somehow, we got the // value. Echo it already! System.out.println(argString); // If we didn't retrieve the // value from the property, // save it //in the property. if (notProperty) { Properties outProperties = new Properties(); outProperties.setProperty("argString", argString); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream("PersistentEcho.txt"); outProperties.store(fileOutputStream, "PersistentEcho properties"); } catch (IOException e) { } finally { if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { } ; } } } }
From source file:at.gv.egiz.pdfas.cli.test.SignaturProfileTest.java
public static void main(String[] args) { String user_home = System.getProperty("user.home"); String pdfas_dir = user_home + File.separator + ".pdfas"; PdfAs pdfas = PdfAsFactory.createPdfAs(new File(pdfas_dir)); try {/*from w w w . j ava 2 s. c o m*/ Configuration config = pdfas.getConfiguration(); ISettings settings = (ISettings) config; List<String> signatureProfiles = new ArrayList<String>(); List<String> signaturePDFAProfiles = new ArrayList<String>(); Iterator<String> itKeys = settings.getFirstLevelKeys("sig_obj.types.").iterator(); while (itKeys.hasNext()) { String key = itKeys.next(); String profile = key.substring("sig_obj.types.".length()); System.out.println("[" + profile + "]: " + settings.getValue(key)); if (settings.getValue(key).equals("on")) { signatureProfiles.add(profile); if (profile.contains("PDFA")) { signaturePDFAProfiles.add(profile); } } } byte[] input = IOUtils.toByteArray(new FileInputStream(sourcePDF)); IPlainSigner signer = new PAdESSignerKeystore(KS_FILE, KS_ALIAS, KS_PASS, KS_KEY_PASS, KS_TYPE); Iterator<String> itProfiles = signatureProfiles.iterator(); while (itProfiles.hasNext()) { String profile = itProfiles.next(); System.out.println("Testing " + profile); DataSource source = new ByteArrayDataSource(input); FileOutputStream fos = new FileOutputStream(targetFolder + profile + ".pdf"); SignParameter signParameter = PdfAsFactory.createSignParameter(config, source, fos); signParameter.setPlainSigner(signer); signParameter.setSignatureProfileId(profile); SignResult result = pdfas.sign(signParameter); fos.close(); } byte[] inputPDFA = IOUtils.toByteArray(new FileInputStream(sourcePDFA)); Iterator<String> itPDFAProfiles = signaturePDFAProfiles.iterator(); while (itPDFAProfiles.hasNext()) { String profile = itPDFAProfiles.next(); System.out.println("Testing " + profile); DataSource source = new ByteArrayDataSource(inputPDFA); FileOutputStream fos = new FileOutputStream(targetFolder + "PDFA_" + profile + ".pdf"); SignParameter signParameter = PdfAsFactory.createSignParameter(config, source, fos); signParameter.setPlainSigner(signer); signParameter.setSignatureProfileId(profile); SignResult result = pdfas.sign(signParameter); fos.close(); } } catch (Throwable e) { e.printStackTrace(); } }
From source file:net.sf.jsignpdf.InstallCert.java
/** * The main - whole logic of Install Cert Tool. * //www . j a v a 2 s . com * @param args * @throws Exception */ public static void main(String[] args) { String host; int port; char[] passphrase; System.out.println("InstallCert - Install CA certificate to Java Keystore"); System.out.println("====================================================="); final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { if ((args.length == 1) || (args.length == 2)) { String[] c = args[0].split(":"); host = c[0]; port = (c.length == 1) ? 443 : Integer.parseInt(c[1]); String p = (args.length == 1) ? "changeit" : args[1]; passphrase = p.toCharArray(); } else { String tmpStr; do { System.out.print("Enter hostname or IP address: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); } while (tmpStr == null); host = tmpStr; System.out.print("Enter port number [443]: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); port = tmpStr == null ? 443 : Integer.parseInt(tmpStr); System.out.print("Enter keystore password [changeit]: "); tmpStr = reader.readLine(); String p = "".equals(tmpStr) ? "changeit" : tmpStr; passphrase = p.toCharArray(); } char SEP = File.separatorChar; final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); final File file = new File(dir, "cacerts"); System.out.println("Loading KeyStore " + file + "..."); InputStream in = new FileInputStream(file); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] { tm }, null); SSLSocketFactory factory = context.getSocketFactory(); System.out.println("Opening connection to " + host + ":" + port + "..."); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); try { System.out.println("Starting SSL handshake..."); socket.startHandshake(); socket.close(); System.out.println(); System.out.println("No errors, certificate is already trusted"); } catch (SSLException e) { System.out.println(); System.out.println("Certificate is not yet trusted."); // e.printStackTrace(System.out); } X509Certificate[] chain = tm.chain; if (chain == null) { System.out.println("Could not obtain server certificate chain"); return; } System.out.println(); System.out.println("Server sent " + chain.length + " certificate(s):"); System.out.println(); MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN()); System.out.println(" Issuer " + cert.getIssuerDN()); sha1.update(cert.getEncoded()); System.out.println(" sha1 " + toHexString(sha1.digest())); md5.update(cert.getEncoded()); System.out.println(" md5 " + toHexString(md5.digest())); System.out.println(); } System.out.print("Enter certificate to add to trusted keystore or 'q' to quit [1]: "); String line = reader.readLine().trim(); int k = -1; try { k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; } catch (NumberFormatException e) { } if (k < 0 || k >= chain.length) { System.out.println("KeyStore not changed"); } else { try { System.out.println("Creating keystore backup"); final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); final File backupFile = new File(dir, CACERTS_KEYSTORE + "." + dateFormat.format(new java.util.Date())); final FileInputStream fis = new FileInputStream(file); final FileOutputStream fos = new FileOutputStream(backupFile); IOUtils.copy(fis, fos); fis.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Installing certificate..."); X509Certificate cert = chain[k]; String alias = host + "-" + (k + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream(file); ks.store(out, passphrase); out.close(); System.out.println(); System.out.println(cert); System.out.println(); System.out.println("Added certificate to keystore '" + file + "' using alias '" + alias + "'"); } } catch (Exception e) { System.out.println(); System.out.println("----------------------------------------------"); System.out.println("Problem occured during installing certificate:"); e.printStackTrace(); System.out.println("----------------------------------------------"); } System.out.println("Press Enter to finish..."); try { reader.readLine(); } catch (IOException e) { e.printStackTrace(); } }
From source file:Main.java
public static void main(String args[]) throws IOException, ClassNotFoundException { File file = new File("test.txt"); FileOutputStream outFile = new FileOutputStream(file); ObjectOutputStream outStream = new ObjectOutputStream(outFile); TestClass1 t1 = new TestClass1(true, 9, 'A', 0.0001, "java"); TestClass2 t2 = new TestClass2(); String t3 = "This is a test."; Date t4 = new Date(); outStream.writeObject(t1);/*from ww w. java 2s . c o m*/ outStream.writeObject(t2); outStream.writeObject(t3); outStream.writeObject(t4); outStream.close(); outFile.close(); FileInputStream inFile = new FileInputStream(file); ObjectInputStream inStream = new ObjectInputStream(inFile); System.out.println(inStream.readObject()); System.out.println(inStream.readObject()); System.out.println(inStream.readObject()); System.out.println(inStream.readObject()); inStream.close(); inFile.close(); file.delete(); }
From source file:com.bstek.dorado.idesupport.StandaloneRuleSetExporter.java
public static void main(String[] args) throws Exception { String ruleSetFile = null;// w ww .j a v a 2s. c o m String doradoHome = null; if (args.length >= 2) { ruleSetFile = args[0]; doradoHome = args[1]; } else { throw new IllegalArgumentException(); } if (StringUtils.isEmpty(doradoHome)) { doradoHome = System.getenv("DORADO_HOME"); } StandaloneRuleSetExporter instance = new StandaloneRuleSetExporter(doradoHome); FileOutputStream fos = new FileOutputStream(ruleSetFile); PrintWriter writer = new PrintWriter(new OutputStreamWriter(fos, Constants.DEFAULT_CHARSET)); try { instance.exportRuleSet(writer); } finally { writer.flush(); writer.close(); fos.close(); } }
From source file:MainClass.java
public static void main(String args[]) { FileInputStream fIn;/* w w w .j a va2s . c o m*/ FileOutputStream fOut; FileChannel fIChan, fOChan; long fSize; MappedByteBuffer mBuf; try { fIn = new FileInputStream(args[0]); fOut = new FileOutputStream(args[1]); fIChan = fIn.getChannel(); fOChan = fOut.getChannel(); fSize = fIChan.size(); mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize); fOChan.write(mBuf); // this copies the file fIChan.close(); fIn.close(); fOChan.close(); fOut.close(); } catch (IOException exc) { System.out.println(exc); System.exit(1); } catch (ArrayIndexOutOfBoundsException exc) { System.out.println("Usage: Copy from to"); System.exit(1); } }
From source file:ViewImageTest.java
/** * Test image(s) (default : JPEG_example_JPG_RIP_100.jpg) are parsed and * rendered to an output foler. Result can then be checked with program of * your choice./*ww w . j av a 2s.co m*/ * * @param args * may be empty or contain parameters to override defaults : * <ul> * <li>args[0] : input image file URL or folder containing image * files URL. Default : * viewImageTest/test/JPEG_example_JPG_RIP_100.jpg</li> * <li>args[1] : output format name (for example : "jpg") for * rendered image</li> * <li>args[2] : ouput folder URL</li> * <li>args[3] : max width (in pixels) for rendered image. * Default : no value.</li> * <li>args[4] : max height (in pixels) for rendered image. * Default : no value.</li> * </ul> * @throws IOException * when a read/write error occured */ public static void main(String args[]) throws IOException { File inURL = getInputURL(args); String ext = getEncodingExt(args); File outDir = getOuputDir(args); serverObjects post = makePostParams(args); outDir.mkdirs(); File[] inFiles; if (inURL.isFile()) { inFiles = new File[1]; inFiles[0] = inURL; System.out.println("Testing ViewImage rendering with input file : " + inURL.getAbsolutePath() + " encoded To : " + ext); } else if (inURL.isDirectory()) { FileFilter filter = FileFileFilter.FILE; inFiles = inURL.listFiles(filter); System.out.println("Testing ViewImage rendering with input files in folder : " + inURL.getAbsolutePath() + " encoded To : " + ext); } else { inFiles = new File[0]; } if (inFiles.length == 0) { throw new IllegalArgumentException(inURL.getAbsolutePath() + " is not a valid file or folder url."); } System.out.println("Rendered images will be written in dir : " + outDir.getAbsolutePath()); Map<String, Exception> failures = new HashMap<String, Exception>(); try { for (File inFile : inFiles) { /* Delete eventual previous result file */ File outFile = new File(outDir, inFile.getName() + "." + ext); if (outFile.exists()) { outFile.delete(); } byte[] resourceb = getBytes(inFile); String urlString = inFile.getAbsolutePath(); EncodedImage img = null; Exception error = null; try { img = ViewImage.parseAndScale(post, true, urlString, ext, false, resourceb); } catch (Exception e) { error = e; } if (img == null) { failures.put(urlString, error); } else { FileOutputStream outFileStream = null; try { outFileStream = new FileOutputStream(outFile); img.getImage().writeTo(outFileStream); } finally { if (outFileStream != null) { outFileStream.close(); } img.getImage().close(); } } } displayResults(inFiles, failures); } finally { ConcurrentLog.shutdown(); } }
From source file:com.cladonia.security.signature.SignatureGenerator.java
public static void main(String args[]) throws Exception { // use this if you want to configure logging, normally would put this in a static block, // but this is just for testing (see jre\lib\logging.properties) org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory .getLog(SignatureGenerator.class.getName()); //System.out.println("Using the logger: "+log.getClass().getName()); //log.debug("Debug is on"); //log.warn("Warning is on"); //log.error("Error is on"); log.info("**** Testing Signature Generator *****"); //All the parameters for the keystore String keystoreType = "JKS"; String keystoreFile = "data/keystore.jks"; String keystorePass = "xmlexchanger"; String privateKeyAlias = "exchanger"; String privateKeyPass = "xmlexchanger"; String certificateAlias = "exchanger"; // set the keystore and private key properties KeyBuilder.setParams(keystoreType, keystoreFile, keystorePass, privateKeyAlias, privateKeyPass, certificateAlias);// w w w . j a v a 2 s. c om // get the private key for signing. PrivateKey privateKey = KeyBuilder.getPrivateKey(); // get the cert X509Certificate cert = KeyBuilder.getCertificate(); // ************* create a sample to be signed ****************** javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); //XML Signature needs to be namespace aware dbf.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document document = db.newDocument(); //Build a sample document. It will look something like: //<!-- Comment before --> //<cladonia:Exchanger xmlns:cladonia="http://www.exchangerxml.com"> //</cladonia:Exchanger> document.appendChild(document.createComment(" Comment before ")); Element root = document.createElementNS("http://www.exchangerxml.com", "cladonia:Exchanger"); root.setAttributeNS(null, "attr1", "test1"); root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:foo", "http://www.exchangerxml.com/#foo"); root.setAttributeNS("http://example.org/#foo", "foo:attr1", "foo's test"); root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:cladonia", "http://www.exchangerxml.com"); document.appendChild(root); Element firstchild = document.createElementNS("http://www.exchangerxml.com", "cladonia:Editor"); firstchild.appendChild(document.createTextNode("simple text\n")); firstchild.setAttributeNS(null, "Id", "CladoniaId"); root.appendChild(firstchild); //******************** End of sample to be signed************************* // *************** Signature 1 // create SignatureGenerator using private key, cert and the dom (i.e an enveloped signature) SignatureGenerator gen = new SignatureGenerator(privateKey, cert, document); // set the c14n algorithm (Exclusive) gen.setC14nAlgorithm(SignatureGenerator.TRANSFORM_C14N_EXCL_WITH_COMMENTS); // set the xpath transform gen.setXpath("//cladonia:Editor"); // set the id gen.setId("CladoniaId"); // sign the document document = gen.sign(null); // output the enveloped signature FileOutputStream fos = new FileOutputStream("c:\\temp\\sigout.xml"); XMLUtils.outputDOMc14nWithComments(document, fos); fos.close(); System.out.println("Created Signature 1 - an enveloped signature"); // ************** Signature 2 // now sign the previous output as an example of a detached signature SignatureGenerator gen2 = new SignatureGenerator(privateKey, cert, "file:///c:/temp/sigout.xml"); // set the c14n algorithm gen2.setC14nAlgorithm(SignatureGenerator.TRANSFORM_C14N_WITH_COMMENTS); // sign the document Document document2 = gen2.sign(null); // output the detached signature FileOutputStream fos2 = new FileOutputStream("c:\\temp\\sigout2.xml"); XMLUtils.outputDOMc14nWithComments(document2, fos2); fos2.close(); System.out.println("Created Signature 2 - a detached signature"); System.out.println(""); }