List of usage examples for java.io Reader close
public abstract void close() throws IOException;
From source file:gdv.xport.DatenpaketTest.java
/** * Tested einen Import von 2 Datenpaketen. * * @throws IOException Signals that an I/O exception has occurred. *//*www .j a v a2 s. com*/ @IntegrationTest @Test @SkipTestOn(property = "SKIP_IMPORT_TEST") public void testImport2DatenpaketeWithReader() throws IOException { Reader reader = new FileReader(new File("src/test/resources/zwei_datenpakete.txt")); try { checkImport(datenpaket, reader); Datenpaket zwei = new Datenpaket(); checkImport(zwei, reader); LOG.info(datenpaket + " / " + zwei + " imported."); assertFalse(datenpaket.equals(zwei)); } finally { reader.close(); } }
From source file:edu.harvard.mcz.imagecapture.loader.JobVerbatimFieldLoad.java
/** * Attempt to read file with a given CSV format, and if successful, return * the number of rows in the file./*from w ww. jav a 2s.c o m*/ * * @param file to check for csv rows. * @param formatToTry the CSV format to try to read the file with. * @return number of rows in the file. * @throws IOException on a problem reading the header. * @throws FileNotFoundException on not finding the file. */ protected int readRows(File file, CSVFormat formatToTry) throws IOException, FileNotFoundException { int rows = 0; Reader reader = new FileReader(file); CSVParser csvParser = new CSVParser(reader, formatToTry); Iterator<CSVRecord> iterator = csvParser.iterator(); while (iterator.hasNext()) { iterator.next(); rows++; } csvParser.close(); reader.close(); return rows; }
From source file:com.netflix.hollow.jsonadapter.AbstractHollowJsonAdaptorTask.java
protected void processFile(Reader r, int maxSample) throws Exception { JsonArrayChunker chunker = new JsonArrayChunker(r, executor); chunker.initialize();//from w w w.j av a 2 s . co m int counter = 0; Reader jsonObj = chunker.nextChunk(); while (jsonObj != null && counter < maxSample) { final Reader currentObject = jsonObj; executor.execute(new Runnable() { public void run() { try { JsonFactory factory = new JsonFactory(); JsonParser parser = factory.createParser(currentObject); processRecord(parser); } catch (Exception e) { throw new RuntimeException(e); } } }); while (executor.getQueue().size() > maxWorkQueue) { Thread.sleep(5); } counter++; jsonObj.close(); jsonObj = chunker.nextChunk(); } executor.awaitSuccessfulCompletion(); }
From source file:com.axelor.apps.crm.service.CalendarService.java
@Transactional public void loadCRM(Calendar calendar, File file) throws IOException, ParserException { Preconditions.checkNotNull(calendar, "calendar can't be null"); Preconditions.checkNotNull(file, "input file can't be null"); Preconditions.checkArgument(file.exists(), "no such file: " + file); final Reader reader = new FileReader(file); try {/*w ww.j ava 2s. co m*/ loadCRM(calendar, reader); } finally { reader.close(); } }
From source file:it.greenvulcano.gvesb.datahandling.dbo.utils.StandardRowSetBuilder.java
public int build(Document doc, String id, ResultSet rs, Set<Integer> keyField, Map<String, FieldFormatter> fieldNameToFormatter, Map<String, FieldFormatter> fieldIdToFormatter) throws Exception { if (rs == null) { return 0; }/*w ww. j a va 2s. com*/ int rowCounter = 0; Element docRoot = doc.getDocumentElement(); ResultSetMetaData metadata = rs.getMetaData(); FieldFormatter[] fFormatters = buildFormatterArray(metadata, fieldNameToFormatter, fieldIdToFormatter); boolean noKey = ((keyField == null) || keyField.isEmpty()); //boolean isNull = false; Element data = null; Element row = null; Element col = null; Text text = null; String textVal = null; String precKey = null; String colKey = null; Map<String, String> keyAttr = new HashMap<String, String>(); while (rs.next()) { if (rowCounter % 10 == 0) { ThreadUtils.checkInterrupted(getClass().getSimpleName(), name, logger); } row = parser.createElement(doc, AbstractDBO.ROW_NAME); parser.setAttribute(row, AbstractDBO.ID_NAME, id); for (int j = 1; j <= metadata.getColumnCount(); j++) { FieldFormatter fF = fFormatters[j]; //isNull = false; col = parser.createElement(doc, AbstractDBO.COL_NAME); switch (metadata.getColumnType(j)) { case Types.DATE: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DATE_TYPE); java.sql.Date dateVal = rs.getDate(j); textVal = processDateTime(col, fF, dateVal, AbstractDBO.DEFAULT_DATE_FORMAT); } break; case Types.TIME: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.TIME_TYPE); java.sql.Time dateVal = rs.getTime(j); textVal = processDateTime(col, fF, dateVal, AbstractDBO.DEFAULT_TIME_FORMAT); } break; case Types.TIMESTAMP: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.TIMESTAMP_TYPE); Timestamp dateVal = rs.getTimestamp(j); textVal = processDateTime(col, fF, dateVal, AbstractDBO.DEFAULT_DATE_FORMAT); } break; case Types.DOUBLE: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE); double numVal = rs.getDouble(j); textVal = processDouble(col, fF, numVal); } break; case Types.FLOAT: case Types.REAL: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE); float numVal = rs.getFloat(j); textVal = processDouble(col, fF, numVal); } break; case Types.BIGINT: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.BIGINT_TYPE); long numVal = rs.getLong(j); parser.setAttribute(col, AbstractDBO.NULL_NAME, "false"); textVal = String.valueOf(numVal); } break; case Types.INTEGER: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.INTEGER_TYPE); int numVal = rs.getInt(j); parser.setAttribute(col, AbstractDBO.NULL_NAME, "false"); textVal = String.valueOf(numVal); } break; case Types.SMALLINT: case Types.TINYINT: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.SMALLINT_TYPE); short numVal = rs.getShort(j); parser.setAttribute(col, AbstractDBO.NULL_NAME, "false"); textVal = String.valueOf(numVal); } break; case Types.NUMERIC: case Types.DECIMAL: { BigDecimal bigdecimal = rs.getBigDecimal(j); boolean isNull = bigdecimal == null; parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull)); if (isNull) { if (metadata.getScale(j) > 0) { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DECIMAL_TYPE); } else { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NUMERIC_TYPE); } textVal = ""; } else { if (fF != null) { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DECIMAL_TYPE); parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getNumberFormat()); parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, fF.getGroupSeparator()); parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, fF.getDecSeparator()); textVal = fF.formatNumber(bigdecimal); } else if (metadata.getScale(j) > 0) { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DECIMAL_TYPE); parser.setAttribute(col, AbstractDBO.FORMAT_NAME, numberFormat); parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, groupSeparator); parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, decSeparator); textVal = numberFormatter.format(bigdecimal); } else { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NUMERIC_TYPE); textVal = bigdecimal.toString(); } } } break; case Types.BOOLEAN: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.BOOLEAN_TYPE); boolean bVal = rs.getBoolean(j); parser.setAttribute(col, AbstractDBO.NULL_NAME, "false"); textVal = String.valueOf(bVal); } break; case Types.SQLXML: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.XML_TYPE); SQLXML xml = rs.getSQLXML(j); boolean isNull = xml == null; parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull)); if (isNull) { textVal = ""; } else { textVal = xml.getString(); } } break; case Types.NCHAR: case Types.NVARCHAR: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NSTRING_TYPE); textVal = rs.getNString(j); if (textVal == null) { textVal = ""; } } break; case Types.CHAR: case Types.VARCHAR: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.STRING_TYPE); textVal = rs.getString(j); boolean isNull = textVal == null; parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull)); if (isNull) { textVal = ""; } } break; case Types.NCLOB: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.LONG_NSTRING_TYPE); NClob clob = rs.getNClob(j); if (clob != null) { Reader is = clob.getCharacterStream(); StringWriter str = new StringWriter(); IOUtils.copy(is, str); is.close(); textVal = str.toString(); } else { textVal = ""; } } break; case Types.CLOB: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.LONG_STRING_TYPE); Clob clob = rs.getClob(j); if (clob != null) { Reader is = clob.getCharacterStream(); StringWriter str = new StringWriter(); IOUtils.copy(is, str); is.close(); textVal = str.toString(); } else { textVal = ""; } } break; case Types.BLOB: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.BASE64_TYPE); Blob blob = rs.getBlob(j); boolean isNull = blob == null; parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull)); if (isNull) { textVal = ""; } else { InputStream is = blob.getBinaryStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); is.close(); try { byte[] buffer = Arrays.copyOf(baos.toByteArray(), (int) blob.length()); textVal = Base64.getEncoder().encodeToString(buffer); } catch (SQLFeatureNotSupportedException exc) { textVal = Base64.getEncoder().encodeToString(baos.toByteArray()); } } } break; default: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DEFAULT_TYPE); textVal = rs.getString(j); boolean isNull = textVal == null; parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull)); if (isNull) { textVal = ""; } } } if (textVal != null) { text = doc.createTextNode(textVal); col.appendChild(text); } if (!noKey && keyField.contains(new Integer(j))) { if (textVal != null) { if (colKey == null) { colKey = textVal; } else { colKey += "##" + textVal; } keyAttr.put("key_" + j, textVal); } } else { row.appendChild(col); } } if (noKey) { if (data == null) { data = parser.createElement(doc, AbstractDBO.DATA_NAME); parser.setAttribute(data, AbstractDBO.ID_NAME, id); } } else if ((colKey != null) && !colKey.equals(precKey)) { if (data != null) { docRoot.appendChild(data); } data = parser.createElement(doc, AbstractDBO.DATA_NAME); parser.setAttribute(data, AbstractDBO.ID_NAME, id); for (Entry<String, String> keyAttrEntry : keyAttr.entrySet()) { parser.setAttribute(data, keyAttrEntry.getKey(), keyAttrEntry.getValue()); } keyAttr.clear(); precKey = colKey; } colKey = null; data.appendChild(row); rowCounter++; } if (data != null) { docRoot.appendChild(data); } return rowCounter; }
From source file:org.osiam.client.connector.OsiamConnectorTest.java
private User get_expected_user() throws Exception { Reader reader = null; StringBuilder jsonUser = null; User expectedUser;//www .j a v a 2s. c om try { reader = new FileReader("src/test/resources/__files/user_" + userIdString + ".json"); jsonUser = new StringBuilder(); for (int c; (c = reader.read()) != -1;) jsonUser.append((char) c); } finally { try { reader.close(); } catch (Exception e) { } } expectedUser = new ObjectMapper().readValue(jsonUser.toString(), User.class); return expectedUser; }
From source file:de.schildbach.wallet.goldcoin.ExchangeRatesProvider.java
private static Double getGoldCoinValueLTC() { Date date = new Date(); long now = date.getTime(); if ((now < (lastLitecoinValueCheck + 10 * 60)) && lastLitecoinValue > 0.0) return lastLitecoinValue; //final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); // Keep the LTC rate around for a bit Double ltcRate = 0.0;//from ww w . j a va 2 s . com String currencyCryptsy = "LTC"; String urlCryptsy = "http://pubapi.cryptsy.com/api.php?method=marketdata"; try { // final String currencyCode = currencies[i]; final URL URLCryptsy = new URL(urlCryptsy); final URLConnection connectionCryptsy = URLCryptsy.openConnection(); connectionCryptsy.setConnectTimeout(TIMEOUT_MS); connectionCryptsy.setReadTimeout(TIMEOUT_MS); connectionCryptsy.connect(); final StringBuilder contentCryptsy = new StringBuilder(); Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connectionCryptsy.getInputStream(), 1024)); IOUtils.copy(reader, contentCryptsy); final JSONObject head = new JSONObject(contentCryptsy.toString()); JSONObject returnObject = head.getJSONObject("return"); JSONObject markets = returnObject.getJSONObject("markets"); JSONObject GLD = markets.getJSONObject("GLD"); Double lastTrade = GLD.getDouble("lasttradeprice"); //String euros = String.format("%.7f", lastTrade); // Fix things like 3,1250 //euros = euros.replace(",", "."); //rates.put(currencyCryptsy, new ExchangeRate(currencyCryptsy, Utils.toNanoCoins(euros), URLCryptsy.getHost())); if (currencyCryptsy.equalsIgnoreCase("LTC")) ltcRate = lastTrade; lastLitecoinValue = ltcRate; lastLitecoinValueCheck = now; } finally { if (reader != null) reader.close(); } return ltcRate; } catch (final IOException x) { x.printStackTrace(); } catch (final JSONException x) { x.printStackTrace(); } return null; }
From source file:com.weibo.wesync.notify.xml.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. *//* w w w . ja v a 2 s. c o m*/ private void buildDoc(Reader in) throws IOException { try { SAXReader xmlReader = new SAXReader(); xmlReader.setEncoding("UTF-8"); document = xmlReader.read(in); } catch (Exception e) { throw new IOException(e.getMessage()); } finally { if (in != null) { in.close(); } } }
From source file:eu.delving.sip.FileStoreImpl.java
@Override public AppConfig getAppConfig() throws FileStoreException { File appConfigFile = new File(home, APP_CONFIG_FILE_NAME); AppConfig config = null;// w w w . j a v a 2s . c o m if (appConfigFile.exists()) { try { Reader reader = new InputStreamReader(new FileInputStream(appConfigFile)); config = (AppConfig) getAppConfigStream().fromXML(reader); reader.close(); } catch (Exception e) { throw new FileStoreException(String.format("Unable to read application configuration from %s", appConfigFile.getAbsolutePath())); } } if (config == null) { config = new AppConfig(); } return config; }
From source file:com.cloudbees.eclipse.core.ClickStartService.java
public ClickStartTemplateDetailsResponse loadTemplateDetails(String templateId) throws CloudBeesException { StringBuffer errMsg = new StringBuffer(); String url = CS_API_URL + "template?template=" + templateId; HttpClient httpclient = Utils.getAPIClient(url); HttpGet get = Utils.jsonGetRequest(url); applyAuth(get);/*from w w w. j ava 2 s.co m*/ HttpResponse resp = null; Reader reader = null; try { resp = httpclient.execute(get); reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent(), "UTF-8")); } catch (Exception e) { errMsg = new StringBuffer(e.getMessage()); throw new CloudBeesException( "Failed to invoke ClickStart!" + (errMsg.length() > 0 ? " (" + errMsg + ")" : ""), e); } try { ClickStartResponseBase r = Utils.createGson().fromJson(reader, ClickStartTemplateDetailsResponse.class); checkForErrors(resp, r); return (ClickStartTemplateDetailsResponse) r; } finally { try { reader.close(); } catch (IOException e) { e.printStackTrace(); // safe to fail. } } }