List of usage examples for java.io Reader close
public abstract void close() throws IOException;
From source file:com.suneee.core.util.XMLProperties.java
/** * Builds the document XML model up based the given reader of XML data. * @param in the input stream used to build the xml document * @throws java.io.IOException thrown when an error occurs reading the input stream. *//*from ww w. j a v a 2 s . co m*/ private void buildDoc(Reader in) throws IOException { try { SAXReader xmlReader = new SAXReader(); // xmlReader.setEncoding("GBK"); document = xmlReader.read(in); } catch (Exception e) { Log.error("Error reading XML properties", e); throw new IOException(e.getMessage()); } finally { if (in != null) { in.close(); } } }
From source file:com.aurel.track.lucene.index.associatedFields.textExctractor.HTMLExtractor.java
/** * Gets the text from file content // ww w . jav a 2 s . c o m * @param file * @param fileExtension * @return */ @Override public String getText(File file, String fileExtension) { FileInputStream fis = null; Reader reader = null; try { try { fis = new FileInputStream(file); } catch (FileNotFoundException e) { LOGGER.info("File " + file.getName() + " not found. " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); return null; } reader = new BufferedReader(new InputStreamReader(fis)); DefaultStyledDocument dsd = new DefaultStyledDocument(); HTMLEditorKit htmlEditorKit = new HTMLEditorKit(); htmlEditorKit.read(reader, dsd, 0); return dsd.getText(0, dsd.getLength()); } catch (Exception e) { LOGGER.debug("Extracting text from the .htm or .html file " + file.getName() + " failed with " + e.getMessage()); LOGGER.error(ExceptionUtils.getStackTrace(e)); } finally { try { if (reader != null) { reader.close(); } } catch (Exception e) { LOGGER.debug("Closing the reader for file " + file.getName() + " failed with " + e.getMessage()); } try { if (fis != null) { fis.close(); } } catch (Exception e) { LOGGER.debug("Closing the FileInputStream for file " + file.getName() + " failed with " + e.getMessage()); } } return null; }
From source file:mixi4j.internal.http.HttpResponse.java
/** * Returns the response body as twitter4j.internal.org.json.JSONObject.<br> * Disconnects the internal HttpURLConnection silently. * * @return response body as twitter4j.internal.org.json.JSONObject * @throws MixiException// w w w .j ava2 s .co m */ public JSONObject asJSONObject() throws MixiException { if (json == null) { Reader reader = null; try { if (responseAsString == null) { reader = asReader(); json = new JSONObject(new JSONTokener(reader)); } else { json = new JSONObject(responseAsString); } if (CONF.isPrettyDebugEnabled()) { // logger.debug(json.toString(1)); } } catch (JSONException jsone) { if (responseAsString == null) { throw new MixiException(jsone.getMessage(), jsone); } else { throw new MixiException(jsone.getMessage() + ":" + this.responseAsString, jsone); } } finally { if (reader != null) { try { reader.close(); } catch (IOException ignore) { } } disconnectForcibly(); } } return json; }
From source file:org.schedulesdirect.grabber.Grabber.java
private boolean parseArgs(String[] args) { List<String> finalArgs = new ArrayList<String>(); finalArgs.addAll(Arrays.asList(args)); try {//from w w w . j a v a2s .com String savedUser = null; String savedPwd = null; if (OPTS_FILE.exists()) { Properties props = new Properties(); Reader r = new FileReader(OPTS_FILE); props.load(r); r.close(); savedUser = props.getProperty("user"); savedPwd = props.getProperty("password"); } globalOpts = new GlobalOptions(savedUser, savedPwd); parser = new JCommander(globalOpts) { @Override public void usage() { JCommander.getConsole().println(String.format("sdjson-grabber v%s/sdjson-api v%s", GRABBER_VERSION, Config.API_VERSION)); super.usage(); } }; parser.setProgramName("sdjson-grabber"); grabOpts = new CommandGrab(); parser.addCommand("grab", grabOpts); listOpts = new CommandList(); parser.addCommand("list", listOpts); addOpts = new CommandAdd(); parser.addCommand("add", addOpts); delOpts = new CommandDelete(); parser.addCommand("delete", delOpts); searchOpts = new CommandSearch(); parser.addCommand("search", searchOpts); infoOpts = new CommandInfo(); parser.addCommand("info", infoOpts); auditOpts = new CommandAudit(); parser.addCommand("audit", auditOpts); listMsgsOpts = new CommandListMsgs(); parser.addCommand("listmsgs", listMsgsOpts); delMsgsOpts = new CommandDeleteMsgs(); parser.addCommand("delmsg", delMsgsOpts); availOpts = new CommandAvailable(); parser.addCommand("available", availOpts); parser.parse(finalArgs.toArray(new String[finalArgs.size()])); if (globalOpts.isHelp()) { parser.usage(); return false; } if (LOG == null) { Appender a = null; File logFile = globalOpts.getLogFile(); if (logFile != null) a = new FileAppender(new SimpleLayout(), logFile.getAbsolutePath(), false); else a = new ConsoleAppender(new SimpleLayout()); Logger.getRootLogger().addAppender(a); Logger.getRootLogger().setLevel(globalOpts.getGrabberLogLvl()); Logger.getLogger("org.apache.http").setLevel(globalOpts.getHttpLogLvl()); LOG = LogFactory.getLog(Grabber.class); Logger l = Logger.getLogger(LOGGER_APP_DISPLAY); l.setAdditivity(false); l.setLevel(Level.ALL); Layout layout = new PatternLayout("%m"); File consoleFile = globalOpts.getConsole(); if (consoleFile != null) a = new FileAppender(layout, consoleFile.getAbsolutePath(), false); else a = new ConsoleAppender(layout); l.addAppender(a); } } catch (ParameterException e) { System.out.println(e.getMessage()); String cmd = parser.getParsedCommand(); if (cmd != null && !globalOpts.isHelp()) parser.usage(cmd); else parser.usage(); return false; } catch (IOException e) { throw new RuntimeException(e); } return true; }
From source file:com.continuuity.loom.provisioner.mock.MockWorker.java
private JsonObject takeTask() { try {//from w w w . j a v a 2s . co m JsonObject body = new JsonObject(); body.addProperty("provisionerId", provisionerId); body.addProperty("workerId", provisionerId + "." + workerId); body.addProperty("tenantId", tenantId); takeRequest.setEntity(new StringEntity(body.toString())); Reader reader = null; CloseableHttpResponse response = httpClient.execute(takeRequest, httpContext); try { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode / 100 != 2) { LOG.error("Error taking task. Got status code {} with message:\n{}", statusCode, getResponseString(response)); return null; } else if (statusCode != 200) { return null; } reader = new InputStreamReader(response.getEntity().getContent(), Charsets.UTF_8); JsonObject task = GSON.fromJson(reader, JsonObject.class); LOG.debug("task details: {}", task.toString()); return task; } finally { if (reader != null) { reader.close(); } response.close(); } } catch (Exception e) { LOG.error("Exception making take request.", e); return null; } finally { takeRequest.reset(); } }
From source file:com.adobe.aem.demomachine.communities.SetupCommunities.java
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServerException, IOException { PrintWriter out = response.getWriter(); // Checking if we have a valid admin user ResourceResolver resourceResolver = request.getResourceResolver(); String userId = resourceResolver.getUserID(); if (userId == null || !userId.equals("admin")) { out.println("Permission denied: admin user requested to access this feature"); return;/*from ww w. jav a 2s.co m*/ } // Checking if we have valid configuration parameters String csvPath = (String) request.getParameter("contentPath"); if (csvPath == null) { csvPath = ""; } // Checking the version of GraniteUI to be loaded String coralVersion = "3"; Resource resCoral = resourceResolver.getResource("/etc/clientlibs/granite/coralui3.js"); if (resCoral == null) coralVersion = "2"; response.setContentType("text/html"); out.println("<html><head>"); out.println("<link rel=\"stylesheet\" href=\"/etc/clientlibs/granite/coralui" + coralVersion + ".css\" type=\"text/css\">"); out.println("<script type=\"text/javascript\" src=\"/etc/clientlibs/granite/typekit.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"/etc/clientlibs/granite/jquery.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"/etc/clientlibs/granite/utils.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"/etc/clientlibs/granite/moment.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"/etc/clientlibs/granite/coralui" + coralVersion + ".js\"></script>"); out.println("</head><body class=\"coral--light u-coral-clearFix\" style=\"margin:40px\">"); // Checking if the page is loaded in a frame (e.g. authoring environment) out.println( "<script language=\"JavaScript\">if(window.frameElement){window.top.location=window.location.href;}</script>"); out.println("<a name=\"top\"/>"); out.println("<div><h1>AEM Communities - Demo Setup</h1>"); out.println( "<form action=\"/bin/CreateCommunities\" method=\"GET\" class=\"coral-Form coral-Form--vertical\" style=\"width:700px\">"); out.println("<section class=\"coral-Form-fieldset\">"); out.println( "<span>All the fun takes place on the Publish instance with AEM - please ensure yours is available at the following coordinates</spanl>"); out.println("<label class=\"coral-Form-fieldlabel\">Path to configuration files</label>"); out.println("<input is=\"coral-textfield\" name=\"contentPath\" type=\"text\" value=\"" + csvPath + "\" class=\"coral-Form-field coral-Textfield\">"); out.println("<label class=\"coral-Form-fieldlabel\">Author instance</label>"); out.println("<div class=\"coral-Form--aligned\">"); // Checking if the default host and port are reachable for the author server String hostname_author = "localhost"; String port_author = "4502"; if (!Hostname.isReachable(hostname_author, port_author)) { hostname_author = ""; port_author = ""; } out.println("<input is=\"coral-textfield\" name=\"hostname_author\" type=\"text\" value=\"" + hostname_author + "\" class=\"coral-Textfield\">"); out.println("<input is=\"coral-textfield\" name=\"port_author\" type=\"text\" value=\"" + port_author + "\" class=\"coral-Textfield\">"); out.println("</div>"); out.println("<label class=\"coral-Form-fieldlabel\">Publish instance</label>"); // Checking if the default host and port are reachable for the publish server String hostname_publish = "localhost"; String port_publish = "4503"; if (!Hostname.isReachable(hostname_publish, port_publish)) { hostname_publish = ""; port_publish = ""; out.println("<coral-alert>"); out.println("<coral-alert-header>WARNING</coral-alert-header>"); out.println( "<coral-alert-content>Using an AEM Publish instance is strongly recommended. If not using a Publish instance, all UGC will be posted against the Author instance, which might fail if the demo members are not granted appropriate permissions on Author.</coral-alert-content>"); out.println("</coral-alert>"); } out.println("<div class=\"coral-Form--aligned\">"); out.println("<input is=\"coral-textfield\" name=\"hostname\" type=\"text\" value=\"" + hostname_publish + "\" class=\"coral-Textfield\">"); out.println("<input is=\"coral-textfield\" name=\"port\" type=\"text\" value=\"" + port_publish + "\" class=\"coral-Textfield\">"); out.println("</div>"); out.println("<label class=\"coral-Form-fieldlabel\">Admin password</label>"); out.println( "<input is=\"coral-textfield\" name=\"password\" type=\"text\" value=\"admin\" class=\"coral-Form-field coral-Textfield\">"); out.println("<label class=\"coral-Form-fieldlabel\">Please select from the following options</label>"); // Getting the list of .csv configuration files for this content path int intOptions = 0; Resource resConfigFiles = resourceResolver.getResource(csvPath); if (!csvPath.equals("") && resConfigFiles != null) { ArrayList<String[]> configOptions = new ArrayList<String[]>(); for (Resource resConfigFile : resConfigFiles.getChildren()) { if (resConfigFile != null && resConfigFile.getName().endsWith(".csv")) { String[] resConfigSettings = resConfigFile.getName().split("-"); configOptions.add(resConfigSettings); } } Collections.sort(configOptions, new Comparator<String[]>() { public int compare(String[] strings, String[] otherStrings) { return strings[0].compareTo(otherStrings[0]); } }); for (String[] configOption : configOptions) { // Loading title and description String title = configOption[2]; String description = configOption[0] + "-" + configOption[1] + "-" + configOption[2]; Resource resConfigFile = resourceResolver.getResource(csvPath + "/" + description + "/jcr:content"); if (resConfigFile != null) { InputStream stream = resConfigFile.adaptTo(InputStream.class); Reader inConfigFile = new InputStreamReader(stream); Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(inConfigFile); for (CSVRecord record : records) { String rDescription = "# Description: "; if (record.get(0).startsWith(rDescription)) description = record.get(0).replace(rDescription, "").trim() + " (" + description + ")"; String rTitle = "# Title: "; if (record.get(0).startsWith(rTitle)) title = record.get(0).replace(rTitle, "").trim(); } intOptions++; try { inConfigFile.close(); stream.close(); } catch (IOException ioex) { //omitted. } } printCheckbox(out, "setup-" + configOption[0], title, description); } } if (intOptions > 0) { out.println("<div class=\"coral-Form-fieldwrapper coral-Form-fieldwrapper--alignRight\">"); out.println("<button class=\"coral-Form-field coral-Button coral-Button--primary\">Submit</button>"); out.println("</div>"); } else { out.println("<p>No configuration file to process</p>"); } String returnURL = (String) request.getParameter("returnURL"); if (returnURL != null) { out.println("<input type=\"hidden\" name=\"returnURL\" value=\"" + returnURL + "\">"); } out.println("</section></form>"); out.println("</body></html>"); }
From source file:gov.nih.nci.ncicb.tcga.dcc.dam.processors.DataAccessMatrixQueriesMockImpl.java
public void addPathsToSelectedFiles(List<DataFile> selectedFiles) throws DAMQueriesException { //boolean ret = true; Reader in = null; Writer out = null;/*from w ww .ja v a2 s . c om*/ try { for (DataFile fileInfo : selectedFiles) { //noinspection IOResourceOpenedButNotSafelyClosed in = new BufferedReader(new FileReader(testDownloadFile)); String fname = dataFilePath + fileInfo.getFileId() + ".idat"; File f = new File(fname); if (f.exists()) { f.delete(); } //noinspection IOResourceOpenedButNotSafelyClosed out = new BufferedWriter(new FileWriter(fname)); int c; while ((c = in.read()) != -1) { out.write(c); } out.flush(); out.close(); in.close(); System.out.println("wrote file " + fname); fileInfo.setPath(fname); fname = fname.replace('\\', '/'); fname = fname.substring(fname.lastIndexOf('/') + 1); fileInfo.setFileName(fname); } } catch (Exception ex) { ex.printStackTrace(); //all or nothing for (DataFile fileInfo : selectedFiles) { fileInfo.setPath(null); } //ret = false; throw new DAMQueriesException(ex); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } //return ret; }
From source file:com.seajas.search.contender.service.modifier.FeedModifierService.java
/** * Retrieve a feed from the URL modified by the relevant modifiers. * /*from w w w.j a v a 2 s . co m*/ * @param uri * @param encodingOverride * @param userAgent * @param resultHeaders * @param suppressErrors * @return SyndFeed */ public SyndFeed getFeed(URI uri, String encodingOverride, String userAgent, Map<String, String> resultParameters, Map<String, String> resultHeaders, Boolean suppressErrors) { WebResolverSettings settings = new WebResolverSettings(); settings.setMaximumContentLength(maximumContentLength); settings.setUserAgent(userAgent); settings.setResultParameters(resultParameters); settings.setResultHeaders(resultHeaders); try { SyndFeed resultFeed = null; // We can only retrieve unmodified feeds using conditional gets List<Modifier> modifiers = modifierCache.getFeedModifiersByUrlMatch(uri.toString()); if (modifiers.size() == 0 && (uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https"))) { if (feedFetcher instanceof HttpClientFeedFetcher) resultFeed = ((HttpClientFeedFetcher) feedFetcher).retrieveFeed(userAgent, uri.toURL(), resultHeaders); else resultFeed = feedFetcher.retrieveFeed(userAgent, uri.toURL()); WebFeeds.validate(resultFeed, uri); } else { Reader reader = getContent(uri, encodingOverride, userAgent, resultHeaders); if (reader != null) { try { // Run it through the modifiers reader = executeModifiers(modifiers, reader, uri, settings); // Fill in the result feed SyndFeedInput feedInput = new SyndFeedInput(); resultFeed = feedInput.build(reader); } finally { reader.close(); } } else { logger.error("No content could be retrieved from the given URL. Skipping feed."); return null; } } return resultFeed; } catch (FetcherException e) { if (!suppressErrors) logger.error("Could not retrieve the given feed (" + uri + "): " + e.getMessage()); } catch (IllegalArgumentException e) { if (!suppressErrors) logger.error("Could not retrieve the given feed (" + uri + "): " + e.getMessage(), e); } catch (FeedException e) { if (!suppressErrors) logger.error("Could not retrieve the given feed (" + uri + "): " + e.getMessage(), e); } catch (ScriptException e) { if (!suppressErrors) logger.error("Could not retrieve the given feed (" + uri + "): " + e.getMessage(), e); } catch (IOException e) { if (!suppressErrors) logger.error("Could not retrieve the given feed (" + uri + "): " + e.getMessage(), e); } return null; }
From source file:de.uzk.hki.da.cli.Cli.java
/** * Copies the files listed in a SIP list to a single directory * /* ww w . j a va2 s.c o m*/ * @param fileListFile The SIP list file * @return The path to the directory containing the files */ private String copySipListContentToFolder(File sipListFile) { CliProgressManager progressManager = new CliProgressManager(); String tempFolderName = getTempFolderName(); XMLReader xmlReader = null; SAXParserFactory spf = SAXParserFactory.newInstance(); try { xmlReader = spf.newSAXParser().getXMLReader(); } catch (Exception e) { logger.error("Failed to create SAX parser", e); System.out.println("Fehler beim Einlesen der SIP-Liste: SAX-Parser konnte nicht erstellt werden."); return ""; } xmlReader.setErrorHandler(new ErrorHandler() { @Override public void error(SAXParseException e) throws SAXException { throw new SAXException("Beim Einlesen der SIP-Liste ist ein Fehler aufgetreten.", e); } @Override public void fatalError(SAXParseException e) throws SAXException { throw new SAXException("Beim Einlesen der SIP-Liste ist ein schwerer Fehler aufgetreten.", e); } @Override public void warning(SAXParseException e) throws SAXException { logger.warn("Warning while parsing siplist", e); System.out.println("\nWarnung:\n" + e.getMessage()); } }); InputStream inputStream; try { inputStream = new FileInputStream(sipListFile); Reader reader = new InputStreamReader(inputStream, "UTF-8"); Builder parser = new Builder(xmlReader); Document doc = parser.build(reader); reader.close(); Element root = doc.getRootElement(); Elements sipElements = root.getChildElements("sip"); long files = 0; for (int i = 0; i < sipElements.size(); i++) { Elements fileElements = sipElements.get(i).getChildElements("file"); if (fileElements != null) files += fileElements.size(); } progressManager.setTotalSize(files); for (int i = 0; i < sipElements.size(); i++) { Element sipElement = sipElements.get(i); String sipName = sipElement.getAttributeValue("name"); File tempDirectory = new File(tempFolderName + File.separator + sipName); if (tempDirectory.exists()) { FolderUtils.deleteQuietlySafe(new File(tempFolderName)); System.out.println("\nDie SIP-Liste enthlt mehrere SIPs mit dem Namen " + sipName + ". " + "Bitte vergeben Sie fr jedes SIP einen eigenen Namen."); return ""; } tempDirectory.mkdirs(); Elements fileElements = sipElement.getChildElements("file"); for (int j = 0; j < fileElements.size(); j++) { Element fileElement = fileElements.get(j); String filepath = fileElement.getValue(); File file = new File(filepath); if (!file.exists()) { logger.error("File " + file.getAbsolutePath() + " is referenced in siplist, " + "but does not exist"); System.out.println("\nDie in der SIP-Liste angegebene Datei " + file.getAbsolutePath() + " existiert nicht."); FolderUtils.deleteQuietlySafe(new File(tempFolderName)); return ""; } try { if (file.isDirectory()) FileUtils.copyDirectoryToDirectory(file, tempDirectory); else FileUtils.copyFileToDirectory(file, tempDirectory); progressManager.copyFilesFromListProgress(); } catch (IOException e) { logger.error("Failed to copy file " + file.getAbsolutePath() + " to folder " + tempDirectory.getAbsolutePath(), e); System.out.println("\nDie in der SIP-Liste angegebene Datei " + file.getAbsolutePath() + " konnte nicht kopiert werden."); FolderUtils.deleteQuietlySafe(new File(tempFolderName)); return ""; } } } } catch (Exception e) { logger.error("Failed to read siplist " + sipListFile.getAbsolutePath(), e); System.out.println("\nBeim Lesen der SIP-Liste ist ein Fehler aufgetreten. "); return ""; } return (new File(tempFolderName).getAbsolutePath()); }
From source file:architecture.common.xml.XmlProperties.java
/** * Creates a new XMLPropertiesTest object. * * @param file// w ww . jav a 2s.c o m * the file that properties should be read from and written to. * @throws IOException * if an error occurs loading the properties. */ public XmlProperties(File file) throws IOException { this.file = file; if (!file.exists()) { // Attempt to recover from this error case by seeing if the // tmp file exists. It's possible that the rename of the // tmp file failed the last time Jive was running, // but that it exists now. File tempFile; tempFile = new File(file.getParentFile(), file.getName() + ".tmp"); if (tempFile.exists()) { log.error(L10NUtils.format("002157", file.getName())); tempFile.renameTo(file); } // There isn't a possible way to recover from the file not // being there, so throw an error. else { throw new FileNotFoundException(L10NUtils.format("002151", file.getName())); } } // Check read and write privs. if (!file.canRead()) { throw new IOException(L10NUtils.format("002152", file.getName())); } if (!file.canWrite()) { throw new IOException(L10NUtils.format("002153", file.getName())); } Reader reader = null; try { reader = new InputStreamReader(new FileInputStream(file), ApplicationConstants.DEFAULT_CHAR_ENCODING); buildDoc(reader); } catch (Exception e) { log.error(L10NUtils.format("002154", file.getName(), e.getMessage())); throw new IOException(e.getMessage()); } finally { try { reader.close(); } catch (Exception e) { log.debug(e.getMessage(), e); } } // FileReader reader = new FileReader(file); // buildDoc(reader); }