List of usage examples for java.io BufferedReader read
public int read() throws IOException
From source file:net.krautchan.parser.KCPageParser.java
@Override public void run() { if (null == threadHandler) { throw new IllegalArgumentException("Cannot parse without a handler"); }/*from w ww.j a v a 2 s .c o m*/ if ((null == url) || (url.length() == 0)) { throw new IllegalArgumentException("Cannot parse a NULL or empty url"); } tParser.setHandler(threadHandler, token); final char[] filter = tParser.getFilterMarker(); client = new DefaultHttpClient(); HttpGet request; if (url.startsWith("/")) { request = new HttpGet(resolverPath + url.substring(1)); } else { request = new HttpGet(url); } client.getParams().setParameter("Range", "bytes=42000-"); try { HttpResponse response = client.execute(request); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); ThreadState state = new ThreadState(); int curChar; int pos = 0; curChar = reader.read(); while (-1 != curChar) { if ((state.curState == StateEnum.START) || (state.curState == StateEnum.READ_THREAD)) { if (curChar == filter[pos]) { pos++; if (pos == filter.length) { if (null != thread) { tParser.parse(reader, thread); } else { tParser.parse(reader); } state.curState = StateEnum.START; pos = 0; } } else { pos = 0; } } curChar = reader.read(); } reader.close(); if (response.getEntity() != null) { response.getEntity().consumeContent(); } tParser.notifyDone(); } catch (Exception e) { e.printStackTrace(); threadHandler.notifyError(e, token); } finally { client.getConnectionManager().shutdown(); // Close the instance here } }
From source file:com.appenginefan.toolkit.common.WebConnectionServer.java
/** * Dispatches an incoming request. This method can be called from a servlet * that wraps this object.//from ww w .j a va 2 s. co m * @throws IOException * @return true if the incoming body was valid and the message has been processed */ public final boolean dispatch(Receiver receiver, HttpServletRequest req, HttpServletResponse resp) throws IOException { // First, read the content of the request into a string BufferedReader reader = req.getReader(); String body = null; try { StringBuilder sb = new StringBuilder(); for (int c = reader.read(); c >= 0; c = reader.read()) { sb.append((char) c); } body = sb.toString(); } finally { reader.close(); } // Can we parse the body? String meta = null; List<String> messages = null; try { // Is it valid JSON? JSONObject payload = null; payload = new JSONObject(body); // Does it have a meta tag and an array of messages? if (payload.has(WebConnectionClient.META)) { meta = payload.getString(WebConnectionClient.META); } JSONArray array = payload.getJSONArray(PayloadBuilder.TAG); // Extract all the messages out of the array messages = new ArrayList<String>(); for (int i = 0; i < array.length(); i++) { messages.add(array.getString(i)); } } catch (JSONException e) { return false; } boolean success = false; try { // New or existing connection? ServerEndpoint bus = null; boolean newBus = false; if (meta != null) { bus = server.loadServerEndpoint(req, meta); } if (bus == null) { bus = server.newServerEndpoint(req); newBus = true; } if (newBus) { bus.open(); } // Process the payload if (!newBus) { if (messages.isEmpty()) { try { receiver.onEmptyPayload(this, bus, req); } catch (Throwable t) { LOG.log(Level.WARNING, "Error while processing empty message", t); } } else { for (String message : messages) { try { receiver.receive(this, bus, message, req); } catch (Throwable t) { LOG.log(Level.WARNING, "Error while processing: " + message, t); } } } } // Now, put some data into the response and return server.writeState(req, bus, resp); success = true; } finally { // Commit all changes to the store, or roll them back if (success) { server.commit(req); } else { server.rollback(req); } } // Done return true; }
From source file:com.dotmarketing.portlets.rules.actionlet.PersonaActionletFTest.java
/** * Test the creation of a persona in the backend and if the persona object * change in the $visitor variable for the preview as persona functionality card584 * @throws Exception// w w w .j a va2s. c om */ @Test public void addPersona() throws Exception { sysuser = userAPI.getSystemUser(); Host host = hostAPI.findDefaultHost(sysuser, false); Host systemHost = hostAPI.findSystemHost(); /* * Create personas for test */ //Create a Persona related to Single host Contentlet persona = new Contentlet(); persona.setStructureInode(PersonaAPI.DEFAULT_PERSONAS_STRUCTURE_INODE); persona.setHost(host.getIdentifier()); persona.setLanguageId(languageAPI.getDefaultLanguage().getId()); String name = "persona1" + UtilMethods.dateToHTMLDate(new Date(), "MMddyyyyHHmmss"); persona.setProperty(PersonaAPI.NAME_FIELD, name); persona.setProperty(PersonaAPI.KEY_TAG_FIELD, name); persona.setProperty(PersonaAPI.TAGS_FIELD, "persona"); persona.setProperty(PersonaAPI.DESCRIPTION_FIELD, "test to delete"); persona = contentletAPI.checkin(persona, sysuser, false); contentletAPI.publish(persona, sysuser, false); Persona personaA = new Persona(persona); boolean isPersonaAIndexed = contentletAPI.isInodeIndexed(persona.getInode(), 500); Assert.assertTrue(isPersonaAIndexed); //Create a Persona related to System Host Contentlet persona2 = new Contentlet(); persona2.setStructureInode(PersonaAPI.DEFAULT_PERSONAS_STRUCTURE_INODE); persona2.setHost(systemHost.getIdentifier()); persona2.setLanguageId(languageAPI.getDefaultLanguage().getId()); String name2 = "persona2" + UtilMethods.dateToHTMLDate(new Date(), "MMddyyyyHHmmss"); persona2.setProperty(PersonaAPI.NAME_FIELD, name2); persona2.setProperty(PersonaAPI.KEY_TAG_FIELD, name2); persona2.setProperty(PersonaAPI.TAGS_FIELD, "persona"); persona2.setProperty(PersonaAPI.DESCRIPTION_FIELD, "test to delete"); persona2 = contentletAPI.checkin(persona2, sysuser, false); contentletAPI.publish(persona2, sysuser, false); Persona personaB = new Persona(persona2); boolean isPersonaBIndexed = contentletAPI.isInodeIndexed(persona2.getInode(), 500); Assert.assertTrue(isPersonaBIndexed); Assert.assertTrue("PersonaA was not created succesfully", UtilMethods.isSet(personaAPI.find(personaA.getIdentifier(), sysuser, false))); Assert.assertTrue("PersonaB was not created succesfully", UtilMethods.isSet(personaAPI.find(personaB.getIdentifier(), sysuser, false))); /* * Test 1: * Create a test page to see if the personas object * in the $visitor variable change */ Folder ftest = folderAPI.createFolders("/personafoldertest" + System.currentTimeMillis(), host, sysuser, false); //adding page String pageStr = "persona-test-page" + UtilMethods.dateToHTMLDate(new Date(), "MMddyyyyHHmmss"); List<Template> templates = templateAPI.findTemplatesAssignedTo(host); Template template = null; for (Template temp : templates) { if (temp.getTitle().equals("Blank")) { template = temp; break; } } Contentlet contentAsset = new Contentlet(); contentAsset.setStructureInode(HTMLPageAssetAPIImpl.DEFAULT_HTMLPAGE_ASSET_STRUCTURE_INODE); contentAsset.setHost(host.getIdentifier()); contentAsset.setProperty(HTMLPageAssetAPIImpl.FRIENDLY_NAME_FIELD, pageStr); contentAsset.setProperty(HTMLPageAssetAPIImpl.URL_FIELD, pageStr); contentAsset.setProperty(HTMLPageAssetAPIImpl.TITLE_FIELD, pageStr); contentAsset.setProperty(HTMLPageAssetAPIImpl.CACHE_TTL_FIELD, "0"); contentAsset.setProperty(HTMLPageAssetAPIImpl.TEMPLATE_FIELD, template.getIdentifier()); contentAsset.setLanguageId(languageAPI.getDefaultLanguage().getId()); contentAsset.setFolder(ftest.getInode()); contentAsset = contentletAPI.checkin(contentAsset, sysuser, false); contentletAPI.publish(contentAsset, sysuser, false); /*Adding simple widget to show the current persona keytag*/ String title = "personawidget" + UtilMethods.dateToHTMLDate(new Date(), "MMddyyyyHHmmss"); String body = "<p>#if(\"$visitor.persona.keyTag\" == \"" + personaA.getKeyTag() + "\")<h1>showing " + personaA.getKeyTag() + "</h1> #elseif(\"$visitor.persona.keyTag\" == \"" + personaB.getKeyTag() + "\") <h1>showing " + personaB.getKeyTag() + "</h1> #else showing default persona #end</p>"; Contentlet contentAsset2 = new Contentlet(); Structure contentst = StructureFactory.getStructureByVelocityVarName("webPageContent"); Structure widgetst = StructureFactory.getStructureByVelocityVarName("SimpleWidget"); contentAsset2.setStructureInode(widgetst.getInode()); contentAsset2.setHost(host.getIdentifier()); contentAsset2.setProperty("widgetTitle", title); contentAsset2.setLanguageId(languageAPI.getDefaultLanguage().getId()); contentAsset2.setProperty("code", body); contentAsset2.setFolder(ftest.getInode()); contentAsset2 = contentletAPI.checkin(contentAsset2, sysuser, false); contentletAPI.publish(contentAsset2, sysuser, false); Container container = null; List<Container> containers = containerAPI.findContainersForStructure(contentst.getInode()); for (Container c : containers) { if (c.getTitle().equals("Blank Container")) { container = c; break; } } /*Relate widget to page*/ MultiTree m = new MultiTree(contentAsset.getIdentifier(), container.getIdentifier(), contentAsset2.getIdentifier()); MultiTreeFactory.saveMultiTree(m); //Call page to see if the persona functionality is working CookieHandler.setDefault(new CookieManager()); URL testUrl = new URL(baseUrl + "/c/portal_public/login?my_account_cmd=auth&my_account_login=admin@dotcms.com&password=admin&my_account_r_m=true"); IOUtils.toString(testUrl.openStream(), "UTF-8"); String urlpersonaA = baseUrl + ftest.getPath() + pageStr + "?mainFrame=true&livePage=0com.dotmarketing.htmlpage.language=1&host_id=" + host.getIdentifier() + "&com.dotmarketing.persona.id=" + personaA.getIdentifier() + "&previewPage=2"; testUrl = new URL(urlpersonaA); StringBuilder result = new StringBuilder(); InputStreamReader isr = new InputStreamReader(testUrl.openStream()); BufferedReader br = new BufferedReader(isr); int byteRead; while ((byteRead = br.read()) != -1) { result.append((char) byteRead); } br.close(); Assert.assertTrue("Error the page is not showing the Persona expected", result.toString().contains("showing " + personaA.getKeyTag())); String urlpersonaB = baseUrl + ftest.getPath() + pageStr + "?mainFrame=true&livePage=0com.dotmarketing.htmlpage.language=1&host_id=" + host.getIdentifier() + "&com.dotmarketing.persona.id=" + personaB.getIdentifier() + "&previewPage=2"; testUrl = new URL(urlpersonaB); result = new StringBuilder(); isr = new InputStreamReader(testUrl.openStream()); br = new BufferedReader(isr); while ((byteRead = br.read()) != -1) { result.append((char) byteRead); } br.close(); Assert.assertTrue("Error the page is not showing the Persona expected", result.toString().contains("showing " + personaB.getKeyTag())); //remove personas, content, page and folder created for this test contentletAPI.unpublish(persona, sysuser, false); contentletAPI.unpublish(persona2, sysuser, false); contentletAPI.unpublish(contentAsset2, sysuser, false); contentletAPI.unpublish(contentAsset, sysuser, false); contentletAPI.archive(persona, sysuser, false); contentletAPI.archive(persona2, sysuser, false); contentletAPI.archive(contentAsset2, sysuser, false); contentletAPI.archive(contentAsset, sysuser, false); contentletAPI.delete(persona, sysuser, false); contentletAPI.delete(persona2, sysuser, false); contentletAPI.delete(contentAsset2, sysuser, false); contentletAPI.delete(contentAsset, sysuser, false); folderAPI.delete(ftest, sysuser, false); }
From source file:com.geoservicesapi.services.LocationServices.java
/** * Get the geo-location of an address using its components. * * @param street/*from w w w . jav a 2 s. c o m*/ * Street in an address of a location. * @param city * City in an address of a location. * @param state * State in an address of a location. * @param postalCode * Postal Code in an address of a location. * @return The JSONObject associated with geo-coordinates. */ public JSONObject getCoordinatesUsingComponents(String street, String city, String state, String postalCode) { JSONObject result = new JSONObject(); String apiUrl = "http://www.mapquestapi.com/geocoding/v1/address?&key=" + mapQuestApiKey + "&street=" + street + "&city=" + city + "&state=" + state + "&postalCode=" + postalCode; apiUrl = apiUrl.replaceAll(" ", "%20"); try { InputStream is = new URL(apiUrl).openStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } String jsonText = sb.toString(); JSONObject res = new JSONObject(jsonText); JSONObject info = res.getJSONObject("info"); int statusCode = info.getInt("statuscode"); if (statusCode == 0) { JSONArray results = res.getJSONArray("results"); JSONObject resultObject = results.getJSONObject(0); JSONArray locations = resultObject.getJSONArray("locations"); JSONObject location = locations.getJSONObject(0); JSONObject latLng = location.getJSONObject("latLng"); double lat = latLng.getDouble("lat"); double lng = latLng.getDouble("lng"); JSONObject coordinates = new JSONObject(); coordinates.put("lat", lat); coordinates.put("lng", lng); result.put("location", coordinates); } } catch (Exception e) { JSONObject error = new JSONObject(); error.put("message", "Error processing request. Try again after some time"); result.put("error", error); } return result; }
From source file:com.geoservicesapi.services.LocationServices.java
/** * Get the geo-location of an address./*from w w w . j a v a 2s . c o m*/ * * @param address * Address of a location. * @return The JSONObject associated with geo-coordinates. */ public JSONObject getCoordinatesUsingAddress(String address) { JSONObject result = new JSONObject(); String apiUrl = "http://open.mapquestapi.com/geocoding/v1/address?key=" + mapQuestApiKey + "&location=" + address; apiUrl = apiUrl.replaceAll(" ", "%20"); try { InputStream is = new URL(apiUrl).openStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } String jsonText = sb.toString(); JSONObject res = new JSONObject(jsonText); JSONObject info = res.getJSONObject("info"); int statusCode = info.getInt("statuscode"); if (statusCode == 0) { JSONArray results = res.getJSONArray("results"); JSONObject resultObject = results.getJSONObject(0); JSONArray locations = resultObject.getJSONArray("locations"); JSONObject location = locations.getJSONObject(0); JSONObject latLng = location.getJSONObject("latLng"); double lat = latLng.getDouble("lat"); double lng = latLng.getDouble("lng"); JSONObject coordinates = new JSONObject(); coordinates.put("lat", lat); coordinates.put("lng", lng); result.put("location", coordinates); } } catch (Exception e) { JSONObject error = new JSONObject(); error.put("message", "Error processing request. Try again after some time"); result.put("error", error); } return result; }
From source file:com.mirth.connect.plugins.datatypes.hl7v2.ER7Reader.java
private String getMessageFromSource(InputSource source) throws IOException { BufferedReader reader = new BufferedReader(source.getCharacterStream()); StringBuilder builder = new StringBuilder(); int c;//w ww.ja va 2 s.c o m while ((c = reader.read()) != -1) { builder.append((char) c); } return builder.toString().trim(); }
From source file:org.owasp.jbrofuzz.graph.canvas.StatusCodeChart.java
private String calculateValue(final File inputFile) { if (inputFile.isDirectory()) { // return -1; return ERROR; }/*from www.j a v a 2 s. c o m*/ String status = ERROR; BufferedReader inbuffReader = null; try { inbuffReader = new BufferedReader(new FileReader(inputFile)); final StringBuffer one = new StringBuffer(MAX_CHARS); int counter = 0; int got; while (((got = inbuffReader.read()) > 0) && (counter < MAX_CHARS)) { one.append((char) got); counter++; } inbuffReader.close(); one.delete(0, one.indexOf("\n--\n") + 4); one.delete(one.indexOf("\n--"), one.length()); // status = Integer.parseInt(one.toString()); status = one.toString(); } catch (final IOException e1) { // return -2; return ERROR; } catch (final StringIndexOutOfBoundsException e2) { // return -3; return ERROR; } catch (final NumberFormatException e3) { // return 0; return ERROR; } finally { IOUtils.closeQuietly(inbuffReader); } return status; }
From source file:org.hibernatespatial.test.DataSourceUtils.java
/** * Parses the content of a file into an executable SQL statement. * * @param fileName name of a file containing SQL-statements * @return/*from www .j a v a2 s. c om*/ * @throws IOException */ public String parseSqlIn(String fileName) throws IOException { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); if (is == null) { throw new RuntimeException("File " + fileName + " not found on Classpath."); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringWriter sw = new StringWriter(); BufferedWriter writer = new BufferedWriter(sw); for (int c = reader.read(); c != -1; c = reader.read()) { writer.write(c); } writer.flush(); return sw.toString(); } finally { if (is != null) { is.close(); } } }
From source file:functionalTests.vfsprovider.TestProActiveProviderAutoclosing.java
@Test public void testInputStreamOpenReadAutocloseRead() throws Exception { final FileObject fo = openFileObject(TEST_FILENAME); final BufferedReader reader = openBufferedReader(fo); try {/* w ww. ja va 2 s. c o m*/ for (int i = 0; i < TEST_FILE_A_CHARS_NUMBER; i++) { assertTrue('a' == reader.read()); } Thread.sleep(SLEEP_TIME); for (int i = 0; i < TEST_FILE_B_CHARS_NUMBER; i++) { assertTrue('b' == reader.read()); } } finally { reader.close(); } fo.close(); }
From source file:edu.gmu.csiss.automation.pacs.utils.BaseTool.java
/** * Parse string from input stream//from w w w . j a v a 2 s . co m * @param in * @return */ public String parseStringFromInputStream(InputStream in) { String output = null; try { // WORKAROUND cut the parameter name "request" of the stream BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8")); StringWriter sw = new StringWriter(); int k; while ((k = br.read()) != -1) { sw.write(k); } output = sw.toString(); } catch (Exception e) { e.printStackTrace(); } finally { try { in.close(); } catch (Exception e1) { e1.printStackTrace(); } } return output; }