List of usage examples for java.io InputStreamReader close
public void close() throws IOException
From source file:com.amalto.workbench.utils.Util.java
public static String getResponseFromURL(String url, TreeObject treeObj) throws Exception { InputStreamReader doc = null; try {/*w w w. j ava2 s.co m*/ Encoder encoder = Base64.getEncoder(); StringBuffer buffer = new StringBuffer(); String credentials = encoder.encodeToString((new String(treeObj.getServerRoot().getUsername() + ":"//$NON-NLS-1$ + treeObj.getServerRoot().getPassword()).getBytes())); URL urlCn = new URL(url); URLConnection conn = urlCn.openConnection(); conn.setAllowUserInteraction(true); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Authorization", "Basic " + credentials);//$NON-NLS-1$//$NON-NLS-2$ conn.setRequestProperty("Expect", "100-continue");//$NON-NLS-1$//$NON-NLS-2$ doc = new InputStreamReader(conn.getInputStream()); BufferedReader reader = new BufferedReader(doc); String line = reader.readLine(); while (line != null) { buffer.append(line); line = reader.readLine(); } return buffer.toString(); } finally { if (doc != null) { doc.close(); } } }
From source file:com.util.httpAccount.java
public Account getAccountObject(String tel) { String telefono = tel.replace("-", ""); System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON"); //String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/50241109321.json"; String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/" + telefono + ".json"; System.out.println("Requested URL:" + myURL); StringBuilder sb = new StringBuilder(); URLConnection urlConn = null; InputStreamReader in = null; Account account = new Account(); try {// w w w .j a v a 2 s . c o m URL url = new URL(myURL); urlConn = url.openConnection(); if (urlConn != null) { urlConn.setReadTimeout(60 * 1000); if (urlConn != null && urlConn.getInputStream() != null) { in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); if (bufferedReader != null) { int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } } String jsonResult = sb.toString(); // System.out.println(sb.toString()); //System.out.println("\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n"); JSONObject objJason = new JSONObject(jsonResult); JSONArray dataJson = new JSONArray(); dataJson = objJason.getJSONArray("data"); //System.out.println("objeto normal 1 "+dataJson.toString()); // // // System.out.println("\n\n--------------------CREAMOS UN STRING JSON2 REEMPLAZANDO LOS CORCHETES QUE DAN ERROR---------------------------\n\n"); String jsonString2 = dataJson.toString(); String temp = dataJson.toString(); temp = jsonString2.replace("[", ""); jsonString2 = temp.replace("]", ""); // System.out.println("new json string"+jsonString2); JSONObject objJson2 = new JSONObject(jsonString2); // System.out.println("el objeto simple json es " + objJson2.toString()); // System.out.println("\n\n--------------------CREAMOS UN OBJETO JSON CON EL ARRAR ACCOUN---------------------------\n\n"); String account1 = objJson2.optString("account"); // System.out.println(account1); JSONObject objJson3 = new JSONObject(account1); // System.out.println("el ULTIMO OBJETO SIMPLE ES " + objJson3.toString()); // System.out.println("\n\n--------------------EMPEZAMOS A RECIBIR LOS PARAMETROS QUE HAY EN EL OBJETO JSON---------------------------\n\n"); String firstName = objJson3.getString("first_name"); System.out.println(firstName); System.out.println(objJson3.get("language_id")); // System.out.println("\n\n--------------------TRATAMOS DE PASAR TODO EL ACCOUNT A OBJETO JAVA---------------------------\n\n"); Gson gson = new Gson(); account = gson.fromJson(objJson3.toString(), Account.class); //System.out.println(account.getFirst_name()); // System.out.println(account.getCreation()); account.setLanguaje_id(objJson3.get("language_id").toString()); account.setId(objJson3.get("id").toString()); account.setBalance(objJson3.get("balance").toString()); System.out.println("el id del account es " + account.getId()); } else { System.out.print("no se pudo conectar con el servidor"); account = null; } in.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Exception while calling URL:" + myURL, e); } return account; }
From source file:de.intranda.goobi.plugins.CSICMixedImport.java
private List<Record> retrieveOriginalRecordsFromFile() { List<Record> recordList = new ArrayList<Record>(); HashMap<String, String> filteredRecordStrings = new HashMap<String, String>(); int count = 0; if (importFile.getName().endsWith("zip")) { logger.info("Extracting zip archive"); HashMap<String, byte[]> recordStrings = unzipFile(importFile); // Check all records first to see what's inside for (String key : recordStrings.keySet()) { byte[] bytes = recordStrings.get(key); InputStream bais = null; if (key.endsWith(".zip")) { // Another zip-archive logger.debug("Extracting inner archive " + key + "; size = " + bytes.length + " bytes"); try { bais = new ByteArrayInputStream(bytes); // FileOutputStream fout = new FileOutputStream(new File(importFolder, "temp.zip")); // fout.write(bytes); // fout.close(); HashMap<String, String> tempRecords = unzipStream(bais); filteredRecordStrings.putAll(tempRecords); } catch (Exception e) { logger.error("Unable to read inner zip file"); } finally { if (bais != null) { try { bais.close(); } catch (IOException e) { logger.error(e); }/*from ww w . j av a2 s . c o m*/ } } } else if (key.endsWith(".xml")) { BufferedReader br = null; // ByteArrayInputStream bais = null; InputStreamReader isr = null; try { bais = new ByteArrayInputStream(bytes); isr = new InputStreamReader(bais); br = new BufferedReader(isr); StringBuffer sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } filteredRecordStrings.put(key, sb.toString()); } catch (IOException e) { logger.error("Unable to read METS file from zip-Archive"); } finally { try { if (bais != null) { bais.close(); } if (isr != null) { isr.close(); } if (br != null) { br.close(); } } catch (IOException e) { logger.error("Error closing String reader"); } } } } for (String key : filteredRecordStrings.keySet()) { if (!key.endsWith(".xml")) { continue; } String importFileName = key; String importData = filteredRecordStrings.get(key); logger.debug("Extracting record " + ++count); Record rec = new Record(); // System.out.println("Data from Zip-File:\n " + importData); rec.setData(importData); logger.debug("Getting record " + importFileName); rec.setId(importFileName.substring(0, importFileName.indexOf("."))); recordList.add(rec); } } else { logger.info("Importing single record file"); InputStream input = null; StringWriter writer = null; try { logger.debug("loaded file: " + importFile.getAbsolutePath()); String importFileName = importFile.getName(); input = new FileInputStream(importFile); Record rec = new Record(); writer = new StringWriter(); IOUtils.copy(input, writer, encoding); rec.setData(writer.toString()); rec.setId(importFileName.substring(0, importFileName.indexOf("."))); recordList.add(rec); } catch (FileNotFoundException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); } finally { if (input != null) { try { if (writer != null) writer.close(); input.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } } } return recordList; }
From source file:org.activiti.designer.eclipse.bpmnimport.BpmnFileReader.java
public void readBpmn() { try {// ww w .ja v a2s . co m XMLInputFactory xif = XMLInputFactory.newInstance(); InputStreamReader in = new InputStreamReader(fileStream, "UTF-8"); XMLStreamReader xtr = xif.createXMLStreamReader(in); bpmnParser.parseBpmn(xtr); if (bpmnParser.bpmnList.size() == 0) return; org.eclipse.bpmn2.Process process = Bpmn2Factory.eINSTANCE.createProcess(); String processId = processName.replace(" ", ""); process.setId(processId); if (bpmnParser.process != null && StringUtils.isNotEmpty(bpmnParser.process.getName())) { process.setName(bpmnParser.process.getName()); } else { process.setName(processName); } if (bpmnParser.process != null && StringUtils.isNotEmpty(bpmnParser.process.getNamespace())) { process.setNamespace(bpmnParser.process.getNamespace()); } Documentation documentation = null; if (bpmnParser.process == null || bpmnParser.process.getDocumentation().size() == 0) { documentation = Bpmn2Factory.eINSTANCE.createDocumentation(); documentation.setId("documentation_process"); documentation.setText(""); } else { documentation = bpmnParser.process.getDocumentation().get(0); } process.getDocumentation().add(documentation); if (bpmnParser.process != null && bpmnParser.process.getExecutionListeners().size() > 0) { process.getExecutionListeners().addAll(bpmnParser.process.getExecutionListeners()); } diagram.eResource().getContents().add(process); if (PreferencesUtil.getBooleanPreference(Preferences.IMPORT_USE_BPMNDI) && bpmnParser.bpmdiInfoFound == true) { useBPMNDI = true; drawDiagramWithBPMNDI(diagram, featureProvider, bpmnParser.bpmnList, bpmnParser.sequenceFlowList, bpmnParser.locationMap); } else { List<FlowElement> wrongOrderList = createDiagramElements(bpmnParser.bpmnList); if (wrongOrderList.size() > 0) { int counter = 0; while (wrongOrderList.size() > 0 && counter < 10) { int sizeBefore = wrongOrderList.size(); wrongOrderList = createDiagramElements(wrongOrderList); if (sizeBefore <= wrongOrderList.size()) { counter++; } else { counter = 0; } } } drawSequenceFlows(); } setFriendlyIds(); xtr.close(); in.close(); fileStream.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.moviejukebox.scanner.MediaInfoScanner.java
protected void parseMediaInfo(MediaInfoStream stream, Map<String, String> infosGeneral, List<Map<String, String>> infosVideo, List<Map<String, String>> infosAudio, List<Map<String, String>> infosText) throws Exception { InputStreamReader isr = null; @SuppressWarnings("resource") BufferedReader bufReader = null; try {/*from w w w. j a v a 2 s . c o m*/ isr = new InputStreamReader(stream.getInputStream()); bufReader = new BufferedReader(isr); // Improvement, less code line, each cat have same code, so use the same for all. Map<String, List<Map<String, String>>> matches = new HashMap<>(); // Create a fake one for General, we got only one, but to use the same algo we must create this one. String[] generalKey = { "General", "Gneral", "* Gnral" }; matches.put(generalKey[0], new ArrayList<Map<String, String>>()); matches.put(generalKey[1], matches.get(generalKey[0])); // Issue 1311 - Create a "link" between General and Gnral matches.put(generalKey[2], matches.get(generalKey[0])); // Issue 1311 - Create a "link" between General and * Gnral matches.put("Video", infosVideo); matches.put("Vido", matches.get("Video")); // Issue 1311 - Create a "link" between Vido and Video matches.put("Audio", infosAudio); matches.put("Text", infosText); String line = localInputReadLine(bufReader); String label; while (line != null) { // In case of new format : Text #1, Audio #1 if (line.indexOf('#') >= 0) { line = line.substring(0, line.indexOf('#')).trim(); } // Get cat ArrayList from cat name. List<Map<String, String>> currentCat = matches.get(line); if (currentCat != null) { Map<String, String> currentData = new HashMap<>(); int indexSeparator = -1; while (((line = localInputReadLine(bufReader)) != null) && ((indexSeparator = line.indexOf(" : ")) != -1)) { label = line.substring(0, indexSeparator).trim(); if (currentData.get(label) == null) { currentData.put(label, line.substring(indexSeparator + 3)); } } currentCat.add(currentData); } else { line = localInputReadLine(bufReader); } } // Setting General Info - Beware of lose data if infosGeneral already have some ... try { for (String singleKey : generalKey) { List<Map<String, String>> arrayList = matches.get(singleKey); if (!arrayList.isEmpty()) { Map<String, String> datas = arrayList.get(0); if (!datas.isEmpty()) { infosGeneral.putAll(datas); break; } } } } catch (Exception ignore) { // We don't care about this exception } } finally { if (isr != null) { isr.close(); } if (bufReader != null) { bufReader.close(); } } }
From source file:cgeo.geocaching.cgBase.java
public static void postTweet(cgeoapplication app, cgSettings settings, String status, final Geopoint coords) { if (app == null) { return;/*from w w w . j a v a2 s . c om*/ } if (settings == null || StringUtils.isBlank(settings.tokenPublic) || StringUtils.isBlank(settings.tokenSecret)) { return; } try { Map<String, String> parameters = new HashMap<String, String>(); parameters.put("status", status); if (coords != null) { parameters.put("lat", String.format("%.6f", coords.getLatitude())); parameters.put("long", String.format("%.6f", coords.getLongitude())); parameters.put("display_coordinates", "true"); } final String paramsDone = cgOAuth.signOAuth("api.twitter.com", "/1/statuses/update.json", "POST", false, parameters, settings.tokenPublic, settings.tokenSecret); HttpURLConnection connection = null; try { final StringBuffer buffer = new StringBuffer(); final URL u = new URL("http://api.twitter.com/1/statuses/update.json"); final URLConnection uc = u.openConnection(); uc.setRequestProperty("Host", "api.twitter.com"); connection = (HttpURLConnection) uc; connection.setReadTimeout(30000); connection.setRequestMethod("POST"); HttpURLConnection.setFollowRedirects(true); connection.setDoInput(true); connection.setDoOutput(true); final OutputStream out = connection.getOutputStream(); final OutputStreamWriter wr = new OutputStreamWriter(out); wr.write(paramsDone); wr.flush(); wr.close(); Log.i(cgSettings.tag, "Twitter.com: " + connection.getResponseCode() + " " + connection.getResponseMessage()); InputStream ins; final String encoding = connection.getContentEncoding(); if (encoding != null && encoding.equalsIgnoreCase("gzip")) { ins = new GZIPInputStream(connection.getInputStream()); } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) { ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true)); } else { ins = connection.getInputStream(); } final InputStreamReader inr = new InputStreamReader(ins); final BufferedReader br = new BufferedReader(inr); readIntoBuffer(br, buffer); br.close(); ins.close(); inr.close(); connection.disconnect(); } catch (IOException e) { Log.e(cgSettings.tag, "cgBase.postTweet.IO: " + connection.getResponseCode() + ": " + connection.getResponseMessage() + " ~ " + e.toString()); final InputStream ins = connection.getErrorStream(); final StringBuffer buffer = new StringBuffer(); final InputStreamReader inr = new InputStreamReader(ins); final BufferedReader br = new BufferedReader(inr); readIntoBuffer(br, buffer); br.close(); ins.close(); inr.close(); } catch (Exception e) { Log.e(cgSettings.tag, "cgBase.postTweet.inner: " + e.toString()); } connection.disconnect(); } catch (Exception e) { Log.e(cgSettings.tag, "cgBase.postTweet: " + e.toString()); } }
From source file:org.cesecore.certificates.util.DnComponents.java
/** * Reads properties from a properties file. Fails nicely if file wasn't found. * /*w w w . j a v a 2 s . c om*/ * @param propertiesFile */ private static void loadProfileMappingsFromFile(String propertiesFile) { // Read the file to an array of lines String line; BufferedReader in = null; InputStreamReader inf = null; try { InputStream is = obj.getClass().getResourceAsStream(propertiesFile); if (is != null) { inf = new InputStreamReader(is); in = new BufferedReader(inf); if (!in.ready()) { throw new IOException("Couldn't read " + propertiesFile); } String[] splits = null; int lines = 0; ArrayList<Integer> dnids = new ArrayList<Integer>(); ArrayList<Integer> profileids = new ArrayList<Integer>(); while ((line = in.readLine()) != null) { if (!line.startsWith("#")) { // # is a comment line splits = StringUtils.split(line, ';'); if ((splits != null) && (splits.length > 5)) { String type = splits[0]; String dnname = splits[1]; Integer dnid = Integer.valueOf(splits[2]); String profilename = splits[3]; Integer profileid = Integer.valueOf(splits[4]); String errstr = splits[5]; String langstr = splits[6]; if (dnids.contains(dnid)) { log.error("Duplicated DN Id " + dnid + " detected in mapping file."); } else { dnids.add(dnid); } if (profileids.contains(profileid)) { log.error("Duplicated Profile Id " + profileid + " detected in mapping file."); } else { profileids.add(profileid); } // Fill maps dnNameIdMap.put(dnname, dnid); profileNameIdMap.put(profilename, profileid); dnIdToProfileNameMap.put(dnid, profilename); dnIdToProfileIdMap.put(dnid, profileid); dnIdErrorMap.put(dnid, errstr); profileIdToDnIdMap.put(profileid, dnid); dnErrorTextMap.put(dnid, errstr); profileNameLanguageMap.put(profilename, langstr); profileIdLanguageMap.put(profileid, langstr); if (type.equals("DN")) { dnProfileFields.add(profilename); dnProfileFieldsHashSet.add(profilename); dnLanguageTexts.add(langstr); dnDnIds.add(dnid); dnExtractorFields.add(dnname + "="); dnIdToExtractorFieldMap.put(dnid, dnname + "="); } if (type.equals("ALTNAME")) { altNameFields.add(dnname); altNameFieldsHashSet.add(dnname); altNameLanguageTexts.add(langstr); altNameDnIds.add(dnid); altNameExtractorFields.add(dnname + "="); altNameIdToExtractorFieldMap.put(dnid, dnname + "="); } if (type.equals("DIRATTR")) { dirAttrFields.add(dnname); dirAttrFieldsHashSet.add(dnname); dirAttrLanguageTexts.add(langstr); dirAttrDnIds.add(dnid); dirAttrExtractorFields.add(dnname + "="); dirAttrIdToExtractorFieldMap.put(dnid, dnname + "="); } lines++; } } } in.close(); if (log.isDebugEnabled()) { log.debug("Read profile maps with " + lines + " lines."); } } else { if (log.isDebugEnabled()) { log.debug("Properties file " + propertiesFile + " was not found."); } } } catch (IOException e) { log.error("Can not load profile mappings: ", e); } finally { try { if (inf != null) { inf.close(); } if (in != null) { in.close(); } } catch (IOException e) { } } }
From source file:br.com.carlosrafaelgn.fplay.ActivityBrowserRadio.java
private void addPlaySelectedItem(final boolean play) { if (radioStationList.getSelection() < 0) return;// ww w .j av a 2s. c o m try { final RadioStation radioStation = radioStationList.getItemT(radioStationList.getSelection()); if (radioStation.m3uUri == null || radioStation.m3uUri.length() < 0) { UI.toast(getApplication(), R.string.error_file_not_found); return; } Player.songs.addingStarted(); SongAddingMonitor.start(getHostActivity()); (new Thread("Checked Radio Station Adder Thread") { @Override public void run() { AndroidHttpClient client = null; HttpResponse response = null; InputStream is = null; InputStreamReader isr = null; BufferedReader br = null; try { if (Player.getState() == Player.STATE_TERMINATED || Player.getState() == Player.STATE_TERMINATING) { Player.songs.addingEnded(); return; } client = AndroidHttpClient.newInstance( "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36 Debian"); response = client.execute(new HttpGet(radioStation.m3uUri)); final StatusLine statusLine = response.getStatusLine(); final int s = statusLine.getStatusCode(); if (s == HttpStatus.SC_OK) { is = response.getEntity().getContent(); isr = new InputStreamReader(is, "UTF-8"); br = new BufferedReader(isr, 1024); ArrayList<String> lines = new ArrayList<String>(8); String line; while ((line = br.readLine()) != null) { line = line.trim(); if (line.length() > 0 && line.charAt(0) != '#' && (line.regionMatches(true, 0, "http://", 0, 7) || line.regionMatches(true, 0, "https://", 0, 8))) lines.add(line); } if (Player.getState() == Player.STATE_TERMINATED || Player.getState() == Player.STATE_TERMINATING) { Player.songs.addingEnded(); return; } if (lines.size() == 0) { Player.songs.addingEnded(); MainHandler.toast(R.string.error_gen); } else { //instead of just using the first available address, let's use //one from the middle ;) Player.songs.addFiles(new FileSt[] { new FileSt(lines.get(lines.size() >> 1), radioStation.title, null, 0) }, null, 1, play, false, true); } } else { Player.songs.addingEnded(); MainHandler.toast( (s >= 400 && s < 500) ? R.string.error_file_not_found : R.string.error_gen); } } catch (Throwable ex) { Player.songs.addingEnded(); MainHandler.toast(ex); } finally { try { if (client != null) client.close(); } catch (Throwable ex) { } try { if (is != null) is.close(); } catch (Throwable ex) { } try { if (isr != null) isr.close(); } catch (Throwable ex) { } try { if (br != null) br.close(); } catch (Throwable ex) { } br = null; isr = null; is = null; client = null; response = null; System.gc(); } } }).start(); } catch (Throwable ex) { Player.songs.addingEnded(); UI.toast(getApplication(), ex.getMessage()); } }
From source file:edu.mit.viral.shen.DroidFish.java
private final Dialog networkEngineDialog() { String[] fileNames = findFilesInDirectory(engineDir, new FileNameFilter() { @Override/*from ww w. ja v a 2 s . co m*/ public boolean accept(String filename) { if (internalEngine(filename)) return false; try { InputStream inStream = new FileInputStream(filename); InputStreamReader inFile = new InputStreamReader(inStream); char[] buf = new char[4]; boolean ret = (inFile.read(buf) == 4) && "NETE".equals(new String(buf)); inFile.close(); return ret; } catch (IOException e) { return false; } } }); final int numFiles = fileNames.length; final int numItems = numFiles + 1; final String[] items = new String[numItems]; final String[] ids = new String[numItems]; int idx = 0; String sep = File.separator; String base = Environment.getExternalStorageDirectory() + sep + engineDir + sep; for (int i = 0; i < numFiles; i++) { ids[idx] = base + fileNames[i]; items[idx] = fileNames[i]; idx++; } ids[idx] = ""; items[idx] = getString(R.string.new_engine); idx++; String currEngine = ctrl.getEngine(); int defaultItem = 0; for (int i = 0; i < numItems; i++) if (ids[i].equals(currEngine)) { defaultItem = i; break; } AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.configure_network_engine); builder.setSingleChoiceItems(items, defaultItem, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if ((item < 0) || (item >= numItems)) return; dialog.dismiss(); if (item == numItems - 1) { showDialog(NEW_NETWORK_ENGINE_DIALOG); } else { networkEngineToConfig = ids[item]; removeDialog(NETWORK_ENGINE_CONFIG_DIALOG); showDialog(NETWORK_ENGINE_CONFIG_DIALOG); } } }); builder.setOnCancelListener(new Dialog.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { removeDialog(MANAGE_ENGINES_DIALOG); showDialog(MANAGE_ENGINES_DIALOG); } }); AlertDialog alert = builder.create(); return alert; }