List of usage examples for java.io InputStream close
public void close() throws IOException
From source file:test.TestJavaService.java
/** * Main. The cmdline arguments either do or don't contain the flag -remote: that's the only supported flag. If it is specified, * we test code on the AWS instance. If it is not, we test code running locally. * The first non-flag argument is the "verb", which (currently) should be one of the verbs set at the top of source file * org.qcert.javasrc.Main. Remaining non-flag arguments are file names. There must be at least one. The number of such * arguments and what they should contain depends on the verb. * @throws Exception/*from ww w .ja v a 2 s. c om*/ */ public static void main(String[] args) throws Exception { /* Parse command line */ List<String> files = new ArrayList<>(); String loc = "localhost", verb = null; for (String arg : args) { if (arg.equals("-remote")) loc = REMOTE_LOC; else if (arg.startsWith("-")) illegal(); else if (verb == null) verb = arg; else files.add(arg); } /* Simple consistency checks and verb-specific parsing */ if (files.size() == 0) illegal(); String file = files.remove(0); String schema = null; switch (verb) { case "parseSQL": case "serialRule2CAMP": case "sqlSchema2JSON": if (files.size() != 0) illegal(); break; case "techRule2CAMP": if (files.size() != 1) illegal(); schema = files.get(0); break; case "csv2JSON": if (files.size() < 1) illegal(); break; default: illegal(); } /* Assemble information from arguments */ String url = String.format("http://%s:9879?verb=%s", loc, verb); byte[] contents = Files.readAllBytes(Paths.get(file)); String toSend; if ("serialRule2CAMP".equals(verb)) toSend = Base64.getEncoder().encodeToString(contents); else toSend = new String(contents); if ("techRule2CAMP".equals(verb)) toSend = makeSpecialJson(toSend, schema); else if ("csv2JSON".equals(verb)) toSend = makeSpecialJson(toSend, files); HttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(url); StringEntity entity = new StringEntity(toSend); entity.setContentType("text/plain"); post.setEntity(entity); HttpResponse resp = client.execute(post); int code = resp.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { HttpEntity answer = resp.getEntity(); InputStream s = answer.getContent(); BufferedReader rdr = new BufferedReader(new InputStreamReader(s)); String line = rdr.readLine(); while (line != null) { System.out.println(line); line = rdr.readLine(); } rdr.close(); s.close(); } else System.out.println(resp.getStatusLine()); }
From source file:createSod.java
/** * @param args//from w ww . j a v a 2s. com * @throws CMSException */ public static void main(String[] args) throws Exception { try { CommandLine options = verifyArgs(args); String privateKeyLocation = options.getOptionValue("privatekey"); String keyPassword = options.getOptionValue("keypass"); String certificate = options.getOptionValue("certificate"); String sodContent = options.getOptionValue("content"); String sod = ""; if (options.hasOption("out")) { sod = options.getOptionValue("out"); } // CHARGEMENT DU FICHIER PKCS#12 KeyStore ks = null; char[] password = null; Security.addProvider(new BouncyCastleProvider()); try { ks = KeyStore.getInstance("PKCS12"); // Password pour le fichier personnal_nyal.p12 password = keyPassword.toCharArray(); ks.load(new FileInputStream(privateKeyLocation), password); } catch (Exception e) { System.out.println("Erreur: fichier " + privateKeyLocation + " n'est pas un fichier pkcs#12 valide ou passphrase incorrect"); return; } // RECUPERATION DU COUPLE CLE PRIVEE/PUBLIQUE ET DU CERTIFICAT PUBLIQUE X509Certificate cert = null; PrivateKey privatekey = null; PublicKey publickey = null; try { Enumeration en = ks.aliases(); String ALIAS = ""; Vector vectaliases = new Vector(); while (en.hasMoreElements()) vectaliases.add(en.nextElement()); String[] aliases = (String[]) (vectaliases.toArray(new String[0])); for (int i = 0; i < aliases.length; i++) if (ks.isKeyEntry(aliases[i])) { ALIAS = aliases[i]; break; } privatekey = (PrivateKey) ks.getKey(ALIAS, password); cert = (X509Certificate) ks.getCertificate(ALIAS); publickey = ks.getCertificate(ALIAS).getPublicKey(); } catch (Exception e) { e.printStackTrace(); return; } // Chargement du certificat partir du fichier InputStream inStream = new FileInputStream(certificate); CertificateFactory cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(inStream); inStream.close(); // Chargement du fichier qui va tre sign File file_to_sign = new File(sodContent); byte[] buffer = new byte[(int) file_to_sign.length()]; DataInputStream in = new DataInputStream(new FileInputStream(file_to_sign)); in.readFully(buffer); in.close(); // Chargement des certificats qui seront stocks dans le fichier .p7 // Ici, seulement le certificat personnal_nyal.cer sera associ. // Par contre, la chane des certificats non. ArrayList certList = new ArrayList(); certList.add(cert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); CMSSignedDataGenerator signGen = new CMSSignedDataGenerator(); // privatekey correspond notre cl prive rcupre du fichier PKCS#12 // cert correspond au certificat publique personnal_nyal.cer // Le dernier argument est l'algorithme de hachage qui sera utilis signGen.addSigner(privatekey, cert, CMSSignedDataGenerator.DIGEST_SHA1); signGen.addCertificatesAndCRLs(certs); CMSProcessable content = new CMSProcessableByteArray(buffer); // Generation du fichier CMS/PKCS#7 // L'argument deux permet de signifier si le document doit tre attach avec la signature // Valeur true: le fichier est attach (c'est le cas ici) // Valeur false: le fichier est dtach CMSSignedData signedData = signGen.generate(content, true, "BC"); byte[] signeddata = signedData.getEncoded(); // Ecriture du buffer dans un fichier. if (sod.equals("")) { System.out.print(signeddata.toString()); } else { FileOutputStream envfos = new FileOutputStream(sod); envfos.write(signeddata); envfos.close(); } } catch (OptionException oe) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(NAME, getOptions()); System.exit(-1); } catch (Exception e) { e.printStackTrace(); return; } }
From source file:com.shvet.poi.util.HexDump.java
public static void main(String[] args) throws Exception { File file = new File(args[0]); InputStream in = new BufferedInputStream(new FileInputStream(file)); byte[] b = new byte[(int) file.length()]; in.read(b);//from w w w .ja v a 2s.com System.out.println(HexDump.dump(b, 0, 0)); in.close(); }
From source file:com.vaadin.buildhelpers.FetchReleaseNotesTickets.java
public static void main(String[] args) throws IOException { String version = System.getProperty("vaadin.version"); if (version == null || version.equals("")) { usage();//from ww w. ja v a 2 s . co m } URL url = new URL(queryURL.replace("@version@", version)); URLConnection connection = url.openConnection(); InputStream urlStream = connection.getInputStream(); @SuppressWarnings("unchecked") List<String> tickets = IOUtils.readLines(urlStream); for (String ticket : tickets) { String[] fields = ticket.split("\t"); if ("id".equals(fields[0])) { // This is the header continue; } System.out.println(ticketTemplate.replace("@ticket@", fields[0]).replace("@description@", fields[1])); } urlStream.close(); }
From source file:net.sf.jsignpdf.verify.Verifier.java
/** * @param args//from w w w . jav a2s .c o m */ public static void main(String[] args) { // create the Options Option optHelp = new Option("h", "help", false, "print this message"); // Option optVersion = new Option("v", "version", false, // "print version info"); Option optCerts = new Option("c", "cert", true, "use external semicolon separated X.509 certificate files"); optCerts.setArgName("certificates"); Option optPasswd = new Option("p", "password", true, "set password for opening PDF"); optPasswd.setArgName("password"); Option optExtract = new Option("e", "extract", true, "extract signed PDF revisions to given folder"); optExtract.setArgName("folder"); Option optListKs = new Option("lk", "list-keystore-types", false, "list keystore types provided by java"); Option optListCert = new Option("lc", "list-certificates", false, "list certificate aliases in a KeyStore"); Option optKsType = new Option("kt", "keystore-type", true, "use keystore type with given name"); optKsType.setArgName("keystore_type"); Option optKsFile = new Option("kf", "keystore-file", true, "use given keystore file"); optKsFile.setArgName("file"); Option optKsPass = new Option("kp", "keystore-password", true, "password for keystore file (look on -kf option)"); optKsPass.setArgName("password"); Option optFailFast = new Option("ff", "fail-fast", false, "flag which sets the Verifier to exit with error code on the first validation failure"); final Options options = new Options(); options.addOption(optHelp); // options.addOption(optVersion); options.addOption(optCerts); options.addOption(optPasswd); options.addOption(optExtract); options.addOption(optListKs); options.addOption(optListCert); options.addOption(optKsType); options.addOption(optKsFile); options.addOption(optKsPass); options.addOption(optFailFast); CommandLine line = null; try { // create the command line parser CommandLineParser parser = new PosixParser(); // parse the command line arguments line = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Illegal command used: " + exp.getMessage()); System.exit(SignatureVerification.SIG_STAT_CODE_ERROR_UNEXPECTED_PROBLEM); } final boolean failFast = line.hasOption("ff"); final String[] tmpArgs = line.getArgs(); if (line.hasOption("h") || args == null || args.length == 0) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(70, "java -jar Verifier.jar [file1.pdf [file2.pdf ...]]", "JSignPdf Verifier is a command line tool for verifying signed PDF documents.", options, null, true); } else if (line.hasOption("lk")) { // list keystores for (String tmpKsType : KeyStoreUtils.getKeyStores()) { System.out.println(tmpKsType); } } else if (line.hasOption("lc")) { // list certificate aliases in the keystore for (String tmpCert : KeyStoreUtils.getCertAliases(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp"))) { System.out.println(tmpCert); } } else { final VerifierLogic tmpLogic = new VerifierLogic(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp")); tmpLogic.setFailFast(failFast); if (line.hasOption("c")) { String tmpCertFiles = line.getOptionValue("c"); for (String tmpCFile : tmpCertFiles.split(";")) { tmpLogic.addX509CertFile(tmpCFile); } } byte[] tmpPasswd = null; if (line.hasOption("p")) { tmpPasswd = line.getOptionValue("p").getBytes(); } String tmpExtractDir = null; if (line.hasOption("e")) { tmpExtractDir = new File(line.getOptionValue("e")).getPath(); } int exitCode = 0; for (String tmpFilePath : tmpArgs) { int exitCodeForFile = 0; System.out.println("Verifying " + tmpFilePath); final File tmpFile = new File(tmpFilePath); if (!tmpFile.canRead()) { exitCodeForFile = SignatureVerification.SIG_STAT_CODE_ERROR_FILE_NOT_READABLE; System.err.println("Couln't read the file. Check the path and permissions."); if (failFast) { System.exit(exitCodeForFile); } exitCode = Math.max(exitCode, exitCodeForFile); continue; } final VerificationResult tmpResult = tmpLogic.verify(tmpFilePath, tmpPasswd); if (tmpResult.getException() != null) { tmpResult.getException().printStackTrace(); exitCodeForFile = SignatureVerification.SIG_STAT_CODE_ERROR_UNEXPECTED_PROBLEM; if (failFast) { System.exit(exitCodeForFile); } exitCode = Math.max(exitCode, exitCodeForFile); continue; } else { System.out.println("Total revisions: " + tmpResult.getTotalRevisions()); for (SignatureVerification tmpSigVer : tmpResult.getVerifications()) { System.out.println(tmpSigVer.toString()); if (tmpExtractDir != null) { try { File tmpExFile = new File(tmpExtractDir + "/" + tmpFile.getName() + "_" + tmpSigVer.getRevision() + ".pdf"); System.out.println("Extracting to " + tmpExFile.getCanonicalPath()); FileOutputStream tmpFOS = new FileOutputStream(tmpExFile.getCanonicalPath()); InputStream tmpIS = tmpLogic.extractRevision(tmpFilePath, tmpPasswd, tmpSigVer.getName()); IOUtils.copy(tmpIS, tmpFOS); tmpIS.close(); tmpFOS.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } exitCodeForFile = tmpResult.getVerificationResultCode(); if (failFast && SignatureVerification.isError(exitCodeForFile)) { System.exit(exitCodeForFile); } } exitCode = Math.max(exitCode, exitCodeForFile); } if (exitCode != 0 && tmpArgs.length > 1) { System.exit(SignatureVerification.isError(exitCode) ? SignatureVerification.SIG_STAT_CODE_ERROR_ANY_ERROR : SignatureVerification.SIG_STAT_CODE_WARNING_ANY_WARNING); } else { System.exit(exitCode); } } }
From source file:net.sf.jsignpdf.InstallCert.java
/** * The main - whole logic of Install Cert Tool. * // w w w . ja va 2s . co m * @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:org.eclipse.swt.examples.browserexample.BrowserExample.java
public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); shell.setLayout(new FillLayout()); shell.setText(getResourceString("window.title")); InputStream stream = BrowserExample.class.getResourceAsStream(iconLocation); Image icon = new Image(display, stream); shell.setImage(icon);/*from w w w . jav a2 s . co m*/ try { stream.close(); } catch (IOException e) { e.printStackTrace(); } BrowserExample app = new BrowserExample(shell, true); app.setShellDecoration(icon, true); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } icon.dispose(); app.dispose(); display.dispose(); }
From source file:jfs.sync.meta.MetaFileStorageAccess.java
/** * * Extract one file from encrypted repository. * * TODO: list directories//from w w w . ja va 2s . c o m * */ public static void main(String[] args) throws Exception { final String password = args[0]; MetaFileStorageAccess storage = new MetaFileStorageAccess("Twofish", false) { protected String getPassword(String relativePath) { String result = ""; String pwd = password; int i = 0; int j = relativePath.length() - 1; while ((i < pwd.length()) || (j >= 0)) { if (i < pwd.length()) { result += pwd.charAt(i++); } // if if (j >= 0) { result += relativePath.charAt(j--); } // if } // while return result; } // getPassword() }; String encryptedPath = args[2]; String[] elements = encryptedPath.split("\\\\"); String path = ""; for (int i = 0; i < elements.length; i++) { String encryptedName = elements[i]; String plain = storage.getDecryptedFileName(path, encryptedName); path += storage.getSeparator(); path += plain; System.out.println(path); } // for String cipherSpec = storage.getCipherSpec(); byte[] credentials = storage.getFileCredentials(path); Cipher cipher = SecurityUtils.getCipher(cipherSpec, Cipher.DECRYPT_MODE, credentials); InputStream is = storage.getInputStream(args[1], path); is = JFSEncryptedStream.createInputStream(is, JFSEncryptedStream.DONT_CHECK_LENGTH, cipher); int b = 0; while (b >= 0) { b = is.read(); System.out.print((char) b); } // while is.close(); }
From source file:httpclient.UploadAction.java
public static void main(String[] args) throws FileNotFoundException { File targetFile1 = new File("F:\\2.jpg"); // File targetFile2 = new File("F:\\1.jpg"); FileInputStream fis1 = new FileInputStream(targetFile1); // FileInputStream fis2 = new FileInputStream(targetFile2); // String targetURL = // "http://static.fangbiandian.com.cn/round_server/upload/uploadFile.do"; String targetURL = "http://www.fangbiandian.com.cn/round_server/user/updateUserInfo.do"; HttpPost filePost = new HttpPost(targetURL); try {//from w ww .j a v a 2s . co m // ????? HttpClient client = new DefaultHttpClient(); // FormBodyPart fbp1 = new FormBodyPart("file1", new // FileBody(targetFile1)); // FormBodyPart fbp2 = new FormBodyPart("file2", new // FileBody(targetFile2)); // FormBodyPart fbp3 = new FormBodyPart("file3", new // FileBody(targetFile3)); // List<FormBodyPart> picList = new ArrayList<FormBodyPart>(); // picList.add(fbp1); // picList.add(fbp2); // picList.add(fbp3); Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("userId", "65478A5CD8D20C3807EE16CF22AF8A17"); Map<String, Object> map = new HashMap<String, Object>(); String jsonStr = JSON.toJSONString(paramMap); map.put("cid", 321); map.put("request", jsonStr); String jsonString = JSON.toJSONString(map); MultipartEntity multiEntity = new MultipartEntity(); Charset charset = Charset.forName("UTF-8"); multiEntity.addPart("request", new StringBody(jsonString, charset)); multiEntity.addPart("photo", new InputStreamBody(fis1, "2.jpg")); // multiEntity.addPart("licenseUrl", new InputStreamBody(fis2, // "1.jpg")); filePost.setEntity(multiEntity); HttpResponse response = client.execute(filePost); int code = response.getStatusLine().getStatusCode(); System.out.println(code); if (HttpStatus.SC_OK == code) { System.out.println("?"); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { // do something useful BufferedReader reader = new BufferedReader(new InputStreamReader(instream)); String str = null; while ((str = reader.readLine()) != null) { System.out.println(str); } } finally { instream.close(); } } } else { System.out.println(""); } } catch (Exception ex) { ex.printStackTrace(); } finally { filePost.releaseConnection(); } }
From source file:Main.java
public static void main(String[] argv) throws Exception { File file = new File("c:\\a.bat"); InputStream is = new FileInputStream(file); long length = file.length(); if (length > Integer.MAX_VALUE) { System.out.println("File is too large"); }//from w w w.java 2s. com byte[] bytes = new byte[(int) length]; int offset = 0; int numRead = 0; while (numRead >= 0) { numRead = is.read(bytes, offset, bytes.length - offset); offset += numRead; } if (offset < bytes.length) { throw new IOException("Could not completely read file " + file.getName()); } is.close(); System.out.println(new String(bytes)); }