List of usage examples for java.io InputStream close
public void close() throws IOException
From source file:editor.util.URLUtil.java
public static String readText(String uri) { String res = ""; try {//w w w . j a v a 2 s. c om java.net.URL url = new java.net.URL(uri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); InputStream in = connection.getInputStream(); byte buff[] = new byte[200]; int ch; while ((ch = in.read(buff)) != -1) res += new String(buff, 0, ch); in.close(); return res; } catch (Exception e) { return e.getLocalizedMessage(); } }
From source file:org.keycloak.example.AdminClient.java
public static List<RoleRepresentation> getRealmRoles(HttpServletRequest req) throws Failure { KeycloakSecurityContext session = (KeycloakSecurityContext) req .getAttribute(KeycloakSecurityContext.class.getName()); HttpClient client = new DefaultHttpClient(); try {//from ww w. j a v a 2 s .c o m HttpGet get = new HttpGet( UriUtils.getOrigin(req.getRequestURL().toString()) + "/auth/admin/realms/demo/roles"); get.addHeader("Authorization", "Bearer " + session.getTokenString()); try { HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() != 200) { throw new Failure(response.getStatusLine().getStatusCode()); } HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); try { return JsonSerialization.readValue(is, TypedList.class); } finally { is.close(); } } catch (IOException e) { throw new RuntimeException(e); } } finally { client.getConnectionManager().shutdown(); } }
From source file:com.hmsinc.epicenter.classifier.ClassifierFactory.java
/** * Creates the actual classifier./*from w w w .j a v a2 s .c o m*/ * * @param resource * @return classificationEngine * @throws Exception */ private static ClassificationEngine instantiateClassifier(final Resource resource) throws Exception { final Unmarshaller u = JAXBContext.newInstance("com.hmsinc.epicenter.classifier.config") .createUnmarshaller(); // Enable validation u.setSchema(schema); final InputStream is = resource.getInputStream(); final ClassifierConfig config = (ClassifierConfig) u.unmarshal(is); is.close(); Validate.notNull(config, "Configuration was null!"); Validate.notNull(config.getImplementation(), "No implementation was specified."); final Class<?> implementation = Class.forName(config.getImplementation()); Validate.isTrue(ClassificationEngine.class.isAssignableFrom(implementation), "Implementation must be an instance of ClassificationEngine (was: " + config.getImplementation() + ")"); final ClassificationEngine engine = (ClassificationEngine) implementation.newInstance(); engine.init(config); return engine; }
From source file:Main.java
public static void appendStreamToStream(InputStream is, OutputStream os) throws IOException { final byte[] buffer = new byte[256]; try {//from w ww .j a v a 2 s. c om int n; while ((n = is.read(buffer)) != -1) { os.write(buffer, 0, n); } } finally { is.close(); } }
From source file:controllers.FormsController.java
private static Properties getPropertyFile() { Properties properties = new Properties(); InputStream stream = Play.application().classloader().getResourceAsStream("forms_en.properties"); try {/*from ww w . j a v a 2 s. c o m*/ properties.load(stream); stream.close(); return properties; } catch (FileNotFoundException ex) { Logger.getLogger(FormsController.class.getName()).log(Level.SEVERE, null, ex); return null; } catch (IOException ex) { Logger.getLogger(FormsController.class.getName()).log(Level.SEVERE, null, ex); return null; } finally { try { stream.close(); } catch (IOException ex) { Logger.getLogger(FormsController.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:keel.Algorithms.Genetic_Rule_Learning.Falco_GP.Main.java
/** * <p>/* ww w .j ava 2 s .c o m*/ * Configure the execution of the algorithm. * * @param jobFilename Name of the KEEL file with properties of the * execution * </p> */ private static void configureJob(String jobFilename) { Properties props = new Properties(); try { InputStream paramsFile = new FileInputStream(jobFilename); props.load(paramsFile); paramsFile.close(); } catch (IOException ioe) { ioe.printStackTrace(); System.exit(0); } // Files training and test String trainFile; String testFile; StringTokenizer tokenizer = new StringTokenizer(props.getProperty("inputData")); tokenizer.nextToken(); trainFile = tokenizer.nextToken(); trainFile = trainFile.substring(1, trainFile.length() - 1); testFile = tokenizer.nextToken(); testFile = testFile.substring(1, testFile.length() - 1); tokenizer = new StringTokenizer(props.getProperty("outputData")); String reportTrainFile = tokenizer.nextToken(); reportTrainFile = reportTrainFile.substring(1, reportTrainFile.length() - 1); String reportTestFile = tokenizer.nextToken(); reportTestFile = reportTestFile.substring(1, reportTestFile.length() - 1); String reportRulesFile = tokenizer.nextToken(); reportRulesFile = reportRulesFile.substring(1, reportRulesFile.length() - 1); // Algorithm auxiliar configuration XMLConfiguration algConf = new XMLConfiguration(); algConf.setRootElementName("experiment"); algConf.addProperty("process[@algorithm-type]", "net.sourceforge.jclec.problem.classification.falco.FalcoAlgorithm"); algConf.addProperty("process.rand-gen-factory[@type]", "net.sourceforge.jclec.util.random.RanecuFactory"); algConf.addProperty("process.rand-gen-factory[@seed]", Integer.parseInt(props.getProperty("seed"))); algConf.addProperty("process.population-size", Integer.parseInt(props.getProperty("population-size"))); algConf.addProperty("process.max-of-generations", Integer.parseInt(props.getProperty("max-generations"))); algConf.addProperty("process.max-deriv-size", Integer.parseInt(props.getProperty("max-deriv-size"))); algConf.addProperty("process.dataset[@type]", "net.sourceforge.jclec.util.dataset.KeelDataSet"); algConf.addProperty("process.dataset.train-data.file-name", trainFile); algConf.addProperty("process.dataset.test-data.file-name", testFile); algConf.addProperty("process.species[@type]", "net.sourceforge.jclec.problem.classification.falco.FalcoSyntaxTreeSpecies"); algConf.addProperty("process.evaluator[@type]", "net.sourceforge.jclec.problem.classification.falco.FalcoEvaluator"); algConf.addProperty("process.evaluator.alpha", Double.parseDouble(props.getProperty("alpha"))); algConf.addProperty("process.provider[@type]", "net.sourceforge.jclec.syntaxtree.SyntaxTreeCreator"); algConf.addProperty("process.parents-selector[@type]", "net.sourceforge.jclec.selector.RouletteSelector"); algConf.addProperty("process.recombinator[@type]", "net.sourceforge.jclec.syntaxtree.SyntaxTreeRecombinator"); algConf.addProperty("process.recombinator[@rec-prob]", Double.parseDouble(props.getProperty("rec-prob"))); algConf.addProperty("process.recombinator.base-op[@type]", "net.sourceforge.jclec.problem.classification.falco.FalcoCrossover"); algConf.addProperty("process.mutator[@type]", "net.sourceforge.jclec.syntaxtree.SyntaxTreeMutator"); algConf.addProperty("process.mutator[@mut-prob]", Double.parseDouble(props.getProperty("mut-prob"))); algConf.addProperty("process.mutator.base-op[@type]", "net.sourceforge.jclec.problem.classification.falco.FalcoMutator"); algConf.addProperty("process.copy-prob", Double.parseDouble(props.getProperty("copy-prob"))); algConf.addProperty("process.listener[@type]", "net.sourceforge.jclec.problem.classification.falco.KeelFalcoPopulationReport"); algConf.addProperty("process.listener.report-dir-name", "./"); algConf.addProperty("process.listener.train-report-file", reportTrainFile); algConf.addProperty("process.listener.test-report-file", reportTestFile); algConf.addProperty("process.listener.rules-report-file", reportRulesFile); algConf.addProperty("process.listener.global-report-name", "resumen"); algConf.addProperty("process.listener.report-frequency", 50); try { algConf.save(new File("configure.txt")); } catch (ConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } net.sourceforge.jclec.RunExperiment.main(new String[] { "configure.txt" }); }
From source file:de.nx42.maps4cim.util.Compression.java
/** * Compresses the input file using the zip file format and stores the * resulting zip file in the desired location * @param input the file to compress/*from w w w. ja v a2 s .c om*/ * @param zipOutput the resulting zip file * @return the resulting zip file * @throws IOException if there is an error accessing the input file or * writing the output zip file */ public static File storeAsZip(File input, File zipOutput) throws IOException { // create new zip output stream ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipOutput)); ZipEntry ze = new ZipEntry(input.getName()); zos.putNextEntry(ze); // use file as input stream and copy bytes InputStream in = new FileInputStream(input); ByteStreams.copy(in, zos); // close current zip entry and all streams zos.closeEntry(); in.close(); zos.close(); return zipOutput; }
From source file:Main.java
public static void copyFile(File src, File desc) throws IOException { InputStream is = null; OutputStream os = null;//from w w w. j ava 2s. c o m try { is = new FileInputStream(src); os = new FileOutputStream(desc); copyStream(is, os); } finally { if (is != null) is.close(); if (os != null) os.close(); } }
From source file:com.momab.dstool.DSTool.java
static String getVersionString() { Properties prop = new Properties(); InputStream in = DSTool.class.getResourceAsStream("version.properties"); try {//w ww .j a v a 2s . c o m prop.load(in); in.close(); } catch (IOException e) { return "Could not read version.properties"; } return prop.getProperty("version"); }
From source file:ie.pars.bnc.preprocess.MainBNCProcess.java
private static void getZippedFile() throws IOException, ArchiveException, Exception { String taggerPath = "edu/stanford/nlp/models/pos-tagger/english-left3words/english-left3words-distsim.tagger"; String parseModel = LexicalizedParser.DEFAULT_PARSER_LOC; InputStream is = new FileInputStream(pathInput); TarArchiveInputStream tarStream = (TarArchiveInputStream) new ArchiveStreamFactory() .createArchiveInputStream("tar", is); TarArchiveEntry entry = null;/*from w ww . ja va2 s. c om*/ int countfiles = 0; while ((entry = (TarArchiveEntry) tarStream.getNextEntry()) != null) { // for(File lf: listFiles){ if (!entry.isDirectory()) { byte[] content = new byte[(int) entry.getSize()]; int offset = 0; tarStream.read(content, offset, content.length - offset); String id = entry.getName().split("/")[entry.getName().split("/").length - 1].split(".xml")[0]; if (!filesProcesed.contains(id) && id.startsWith(letter.toUpperCase())) { if (countfiles++ % 10 == 0) { tagger = new MaxentTagger(taggerPath); m = new Morphology(); parser = ParserGrammar.loadModel(parseModel); parser.loadTagger(); } System.out.print("Entry " + entry.getName()); InputStream bis = new ByteArrayInputStream(content); StringBuilder parseBNCXML = ProcessNLP.parseBNCXML(bis, m, tagger, parser); bis.close(); OutputStream out = new FileOutputStream(pathOutput + File.separatorChar + id + ".vert"); Writer writer = new OutputStreamWriter(out, "UTF-8"); writer.write("<text id=\"" + id + "\">\n"); writer.write(parseBNCXML.toString()); writer.write("</text>\n"); writer.close(); out.close(); } else { System.out.println(">> Bypass Entry " + entry.getName()); } //break; } } is.close(); System.out.println("There are " + countfiles); // tarStream.close(); }