List of usage examples for java.io InputStream close
public void close() throws IOException
From source file:ImportKey.java
/** * <p>//w ww. j a v a 2 s . c o m * Takes two file names for a key and the certificate for the key, and * imports those into a keystore. Optionally it takes an alias for the key. * <p> * The first argument is the filename for the key. The key should be in * PKCS8-format. * <p> * The second argument is the filename for the certificate for the key. * <p> * If a third argument is given it is used as the alias. If missing, the key * is imported with the alias importkey * <p> * The name of the keystore file can be controlled by setting the keystore * property (java -Dkeystore=mykeystore). If no name is given, the file is * named <code>keystore.ImportKey</code> and placed in your home directory. * * @param args * [0] Name of the key file, [1] Name of the certificate file [2] * Alias for the key. **/ public static void main(String args[]) { // change this if you want another password by default String keypass = "password"; // change this if you want another alias by default String defaultalias = "tomcat"; // change this if you want another keystorefile by default String keystorename = null; // parsing command line input String keyfile = ""; String certfile = ""; if (args.length < 3 || args.length > 4) { System.out.println("Usage: java comu.ImportKey keystore keyfile certfile [alias]"); System.exit(0); } else { keystorename = args[0]; keyfile = args[1]; certfile = args[2]; if (args.length > 3) defaultalias = args[3]; } try { // initializing and clearing keystore KeyStore ks = KeyStore.getInstance("JKS", "SUN"); ks.load(null, keypass.toCharArray()); System.out.println("Using keystore-file : " + keystorename); ks.store(new FileOutputStream(keystorename), keypass.toCharArray()); ks.load(new FileInputStream(keystorename), keypass.toCharArray()); // loading Key InputStream fl = fullStream(keyfile); byte[] key = new byte[fl.available()]; KeyFactory kf = KeyFactory.getInstance("RSA"); fl.read(key, 0, fl.available()); fl.close(); PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(key); PrivateKey ff = kf.generatePrivate(keysp); // loading CertificateChain CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream certstream = fullStream(certfile); Collection c = cf.generateCertificates(certstream); Certificate[] certs = new Certificate[c.toArray().length]; if (c.size() == 1) { certstream = fullStream(certfile); System.out.println("One certificate, no chain."); Certificate cert = cf.generateCertificate(certstream); certs[0] = cert; } else { System.out.println("Certificate chain length: " + c.size()); certs = (Certificate[]) c.toArray(new Certificate[c.size()]); } // storing keystore ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), certs); System.out.println("Key and certificate stored."); System.out.println("Alias:" + defaultalias + " Password:" + keypass); ks.store(new FileOutputStream(keystorename), keypass.toCharArray()); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:de.cwclan.cwsa.serverendpoint.main.ServerEndpoint.java
/** * @param args the command line arguments *///from w w w .j a v a2 s . c om public static void main(String[] args) { Options options = new Options(); options.addOption(OptionBuilder.withArgName("file").hasArg().withDescription( "Used to enter path of configfile. Default file is endpoint.properties. NOTE: If the file is empty or does not exsist, a default config is created.") .create("config")); options.addOption("h", "help", false, "displays this page"); CommandLineParser parser = new PosixParser(); Properties properties = new Properties(); try { /* * parse default config shipped with jar */ CommandLine cmd = parser.parse(options, args); /* * load default configuration */ InputStream in = ServerEndpoint.class.getResourceAsStream("/endpoint.properties"); if (in == null) { throw new IOException("Unable to load default config from JAR. This should not happen."); } properties.load(in); in.close(); log.debug("Loaded default config base: {}", properties.toString()); if (cmd.hasOption("help")) { printHelp(options); System.exit(0); } /* * parse cutom config if exists, otherwise create default cfg */ if (cmd.hasOption("config")) { File file = new File(cmd.getOptionValue("config", "endpoint.properties")); if (file.exists() && file.canRead() && file.isFile()) { in = new FileInputStream(file); properties.load(in); log.debug("Loaded custom config from {}: {}", file.getAbsoluteFile(), properties); } else { log.warn("Config file does not exsist. A default file will be created."); } FileWriter out = new FileWriter(file); properties.store(out, "Warning, this file is recreated on every startup to merge missing parameters."); } /* * create and start endpoint */ log.info("Config read successfull. Values are: {}", properties); ServerEndpoint endpoint = new ServerEndpoint(properties); Runtime.getRuntime().addShutdownHook(endpoint.getShutdownHook()); endpoint.start(); } catch (IOException ex) { log.error("Error while reading config.", ex); } catch (ParseException ex) { log.error("Error while parsing commandline options: {}", ex.getMessage()); printHelp(options); System.exit(1); } }
From source file:WriteIndex.java
/** * @param args/*from w w w . j a v a2 s . co m*/ */ public static void main(String[] args) throws IOException { File docs = new File("documents"); File indexDir = new File(INDEX_DIRECTORY); Directory directory = FSDirectory.open(indexDir); Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_35); IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_35, analyzer); IndexWriter writer = new IndexWriter(directory, conf); writer.deleteAll(); for (File file : docs.listFiles()) { Metadata metadata = new Metadata(); ContentHandler handler = new BodyContentHandler(); ParseContext context = new ParseContext(); Parser parser = new AutoDetectParser(); InputStream stream = new FileInputStream(file); try { parser.parse(stream, handler, metadata, context); } catch (TikaException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } finally { stream.close(); } String text = handler.toString(); String fileName = file.getName(); Document doc = new Document(); doc.add(new Field("file", fileName, Store.YES, Index.NO)); for (String key : metadata.names()) { String name = key.toLowerCase(); String value = metadata.get(key); if (StringUtils.isBlank(value)) { continue; } if ("keywords".equalsIgnoreCase(key)) { for (String keyword : value.split(",?(\\s+)")) { doc.add(new Field(name, keyword, Store.YES, Index.NOT_ANALYZED)); } } else if ("title".equalsIgnoreCase(key)) { doc.add(new Field(name, value, Store.YES, Index.ANALYZED)); } else { doc.add(new Field(name, fileName, Store.YES, Index.NOT_ANALYZED)); } } doc.add(new Field("text", text, Store.NO, Index.ANALYZED)); writer.addDocument(doc); } writer.commit(); writer.deleteUnusedFiles(); System.out.println(writer.maxDoc() + " documents written"); }
From source file:mitm.common.security.ca.handlers.ejbca.ws.EjbcaWSClient.java
public static void main(String args[]) throws Exception { BasicConfigurator.configure();//ww w . jav a2 s.c o m JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.setServiceClass(EjbcaWS.class); factory.setAddress("https://192.168.178.113:8443/ejbca/ejbcaws/ejbcaws"); factory.setServiceName(SERVICE_NAME); EjbcaWS client = (EjbcaWS) factory.create(); Client proxy = ClientProxy.getClient(client); HTTPConduit conduit = (HTTPConduit) proxy.getConduit(); TLSClientParameters tlsClientParameters = new TLSClientParameters(); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); java.security.KeyStore keyStore = java.security.KeyStore.getInstance("PKCS12"); InputStream keyInput = new FileInputStream("/home/martijn/temp/superadmin.p12"); String password = "ejbca"; keyStore.load(keyInput, password.toCharArray()); keyInput.close(); keyManagerFactory.init(keyStore, password.toCharArray()); KeyManager[] keyManagers = keyManagerFactory.getKeyManagers(); tlsClientParameters.setDisableCNCheck(true); tlsClientParameters.setKeyManagers(keyManagers); X509TrustManager trustAll = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(new KeyStoreLoader().loadKeyStore(new File("/home/martijn/temp/truststore.jks"), "changeit".toCharArray())); tlsClientParameters.setTrustManagers(new TrustManager[] { trustAll }); //tlsClientParameters.setTrustManagers(trustManagerFactory.getTrustManagers()); conduit.setTlsClientParameters(tlsClientParameters); System.out.println(client.getEjbcaVersion()); UserDataVOWS userData = new UserDataVOWS(); userData.setEmail("test@example.com"); userData.setUsername("test@example.com"); //userData.setPassword("test@example.com"); userData.setSubjectDN("CN=test@example.com"); userData.setSubjectAltName("rfc822Name=test@example.com"); userData.setEndEntityProfileName("test"); userData.setCaName("AdminCA1"); userData.setCertificateProfileName("ENDUSER"); userData.setStatus(EJBCAConst.STATUS_NEW); userData.setTokenType(EJBCAConst.TOKEN_TYPE_USERGENERATED); try { //client.editUser(userData); SecurityFactory securityFactory = SecurityFactoryFactory.getSecurityFactory(); SecureRandom randomSource = securityFactory.createSecureRandom(); KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA"); keyPairGenerator.initialize(2048, randomSource); KeyPair keyPair = keyPairGenerator.generateKeyPair(); X500PrincipalBuilder builder = new X500PrincipalBuilder(); builder.setCommonName("john doe"); builder.setEmail("test@example.com"); PKCS10CertificationRequestBuilder requestBuilder = new PKCS10CertificationRequestBuilder( X500PrincipalUtils.toX500Name(builder.buildPrincipal()), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())); PKCS10CertificationRequest pkcs10 = requestBuilder .build(getContentSigner("SHA1WithRSA", keyPair.getPrivate())); String base64PKCS10 = Base64Utils.encode(pkcs10.getEncoded()); CertificateResponse certificateResponse = client.certificateRequest(userData, base64PKCS10, EJBCAConst.CERT_REQ_TYPE_PKCS10, null, EJBCAConst.RESPONSETYPE_CERTIFICATE); if (certificateResponse != null && certificateResponse.getData() != null) { /* * The result is a base64 encoded certificate */ Collection<X509Certificate> certificates = CertificateUtils.readX509Certificates( new ByteArrayInputStream(Base64.decode(certificateResponse.getData()))); if (CollectionUtils.isNotEmpty(certificates)) { for (X509Certificate certificate : certificates) { System.out.println(certificate); } } else { System.out.println("No certificates found"); } } else { System.out.println("certificateResponse is empty"); } } catch (Exception e) { e.printStackTrace(); } }
From source file:Main.java
public static void main(String[] args) throws Exception { InputStream is = new BufferedInputStream(new FileInputStream("filename.gif")); DocFlavor flavor = DocFlavor.INPUT_STREAM.GIF; PrintService service = PrintServiceLookup.lookupDefaultPrintService(); DocPrintJob job = service.createPrintJob(); Doc doc = new SimpleDoc(is, flavor, null); PrintJobWatcher pjDone = new PrintJobWatcher(job); job.print(doc, null);// ww w . j a va 2 s . c o m pjDone.waitForDone(); is.close(); }
From source file:Main.java
public static void main(String[] args) throws Exception { byte[] buffer = new byte[5]; InputStream is = new FileInputStream("C://test.txt"); System.out.println("Characters printed:"); // read stream data into buffer is.read(buffer, 2, 3);/*from www. j ava 2 s. c o m*/ // for each byte in the buffer for (byte b : buffer) { char c = ' '; // convert byte to character if (b == 0)// if b is empty c = '-'; else c = (char) b;// if b is read System.out.print(c); } is.close(); }
From source file:cz.lidinsky.editor.Editor.java
/** * Entry point of the editor.//from w ww .j a va 2 s.c o m */ public static void main(String[] args) throws Exception { // create an instance of the editor instance = new Editor(); // load settings file java.io.InputStream settingsIS = instance.getClass().getResourceAsStream(settingsFilename); instance.settings.load(settingsIS); settingsIS.close(); // create and show gui instance.createMainFrame(); // load file from the command line if (args.length > 0) instance.filename = args[0]; javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { if (instance.filename != null) { try { java.io.File file = new java.io.File(instance.filename); instance.file.load(file); } catch (Exception e) { throw new CommonException().setCause(e) .set("message", "Exception while loading a file with gui!") .set("file name", instance.filename); } } else { instance.file.fileNew(); } } }); // show the window instance.show(); }
From source file:com.anteam.demo.httpclient.PostDemo.java
public static void main(String[] args) { StringEntity stringEntity = new StringEntity("this is the log2.", ContentType.create("text/plain", "UTF-8")); HttpPost post = new HttpPost("http://127.0.0.1:9000"); post.setEntity(stringEntity);//from w ww .ja va 2 s.c om HttpClient httpclient = new DefaultHttpClient(); // Execute the request HttpResponse response = null; try { response = httpclient.execute(post); } catch (ClientProtocolException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } // Examine the response status System.out.println(response.getStatusLine()); // Get hold of the response entity HttpEntity entity = response.getEntity(); // If the response does not enclose an entity, there is no need // to worry about connection release if (entity != null) { InputStream instream = null; try { instream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(instream)); // do something useful with the response System.out.println(reader.readLine()); } catch (Exception ex) { post.abort(); } finally { try { instream.close(); } catch (IOException e) { e.printStackTrace(); } } httpclient.getConnectionManager().shutdown(); } }
From source file:com.anteam.demo.logback.PostDemo.java
public static void main(String[] args) { StringEntity stringEntity = new StringEntity("this is the log2.", ContentType.create("text/plain", "UTF-8")); HttpPost post = new HttpPost("http://10.16.0.207:9000"); post.setEntity(stringEntity);/*from w ww .j av a 2 s.c o m*/ HttpClient httpclient = new DefaultHttpClient(); // Execute the request HttpResponse response = null; try { response = httpclient.execute(post); } catch (ClientProtocolException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } // Examine the response status System.out.println(response.getStatusLine()); // Get hold of the response entity HttpEntity entity = response.getEntity(); // If the response does not enclose an entity, there is no need // to worry about connection release if (entity != null) { InputStream instream = null; try { instream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(instream)); // do something useful with the response System.out.println(reader.readLine()); } catch (Exception ex) { post.abort(); } finally { try { instream.close(); } catch (IOException e) { e.printStackTrace(); } } httpclient.getConnectionManager().shutdown(); } }
From source file:com.lightboxtechnologies.nsrl.OCSVTest.java
public static void main(String[] args) throws IOException { final String mfg_filename = args[0]; final String os_filename = args[1]; final String prod_filename = args[2]; final String hash_filename = args[3]; final LineTokenizer tok = new OpenCSVLineTokenizer(); final RecordLoader loader = new RecordLoader(); final ErrorConsumer err = new ErrorConsumer() { public void consume(BadDataException e, long linenum) { System.err.println("malformed record, line " + linenum); e.printStackTrace();//from w w w . j a v a2 s . c o m } }; // read manufacturer, OS, product data final Map<String, MfgData> mfg = new HashMap<String, MfgData>(); final Map<String, OSData> os = new HashMap<String, OSData>(); final Map<Integer, List<ProdData>> prod = new HashMap<Integer, List<ProdData>>(); SmallTableLoader.load(mfg_filename, mfg, os_filename, os, prod_filename, prod, tok, err); // read hash data final RecordConsumer<HashData> hcon = new RecordConsumer<HashData>() { public void consume(HashData hd) { /* System.out.print(hd); for (ProdData pd : prod.get(hd.prod_code)) { System.out.print(pd); final MfgData pmd = mfg.get(pd.mfg_code); System.out.print(pmd); } final OSData osd = os.get(hd.os_code); System.out.print(osd); final MfgData osmd = mfg.get(osd.mfg_code); System.out.print(osmd); System.out.println(""); */ /* final Hex hex = new Hex(); String sha1 = null; String md5 = null; String crc32 = null; try { sha1 = (String) hex.encode((Object) hd.sha1); md5 = (String) hex.encode((Object) hd.md5); crc32 = (String) hex.encode((Object) hd.crc32); } catch (EncoderException e) { throw new RuntimeException(e); } */ final ObjectMapper mapper = new ObjectMapper(); final String sha1 = Hex.encodeHexString(hd.sha1); final String md5 = Hex.encodeHexString(hd.md5); final String crc32 = Hex.encodeHexString(hd.crc32); final Map<String, Object> hd_m = new HashMap<String, Object>(); hd_m.put("sha1", sha1); hd_m.put("md5", md5); hd_m.put("crc32", crc32); hd_m.put("name", hd.name); hd_m.put("size", hd.size); hd_m.put("special_code", hd.special_code); final OSData osd = os.get(hd.os_code); final MfgData osmfgd = mfg.get(osd.mfg_code); final Map<String, Object> os_m = new HashMap<String, Object>(); os_m.put("name", osd.name); os_m.put("version", osd.version); os_m.put("manufacturer", osmfgd.name); hd_m.put("os", os_m); final List<Map<String, Object>> pl_l = new ArrayList<Map<String, Object>>(); for (ProdData pd : prod.get(hd.prod_code)) { if (!osd.code.equals(pd.os_code)) { // os code mismatch /* System.err.println( "Hash record OS code == " + osd.code + " != " + pd.os_code + " == product record OS code" ); */ continue; } final Map<String, Object> prod_m = new HashMap<String, Object>(); prod_m.put("name", pd.name); prod_m.put("version", pd.version); prod_m.put("language", pd.language); prod_m.put("app_type", pd.app_type); prod_m.put("os_code", pd.os_code); final MfgData md = mfg.get(pd.mfg_code); prod_m.put("manufacturer", md.name); pl_l.add(prod_m); } if (pl_l.size() > 1) { System.err.println(hd.prod_code); } hd_m.put("products", pl_l); try { mapper.writeValue(System.out, hd_m); } catch (IOException e) { // should be impossible throw new IllegalStateException(e); } } }; final RecordProcessor<HashData> hproc = new HashRecordProcessor(); final LineHandler hlh = new DefaultLineHandler<HashData>(tok, hproc, hcon, err); InputStream zin = null; try { // zin = new GZIPInputStream(new FileInputStream(hash_filename)); zin = new FileInputStream(hash_filename); loader.load(zin, hlh); zin.close(); } finally { IOUtils.closeQuietly(zin); } System.out.println(); /* for (Map.Entry<String,String> e : mfg.entrySet()) { System.out.println(e.getKey() + " = " + e.getValue()); } for (Map.Entry<String,OSData> e : os.entrySet()) { System.out.println(e.getKey() + " = " + e.getValue()); } for (Map.Entry<Integer,List<ProdData>> e : prod.entrySet()) { System.out.println(e.getKey() + " = " + e.getValue()); } */ }