List of usage examples for java.net URL getContent
public final Object getContent() throws java.io.IOException
From source file:org.languagetool.server.HTTPServerTest.java
void runTestsV2() throws IOException, SAXException, ParserConfigurationException { // no error:/*w ww. j a va 2s . c o m*/ String emptyResultPattern = ".*\"matches\":\\[\\].*"; German german = new GermanyGerman(); String result1 = checkV2(german, ""); assertTrue("Got " + result1 + ", expected " + emptyResultPattern, result1.matches(emptyResultPattern)); String result2 = checkV2(german, "Ein kleiner Test"); assertTrue("Got " + result2 + ", expected " + emptyResultPattern, result2.matches(emptyResultPattern)); // one error: assertTrue(checkV2(german, "ein kleiner test.").contains("UPPERCASE_SENTENCE_START")); // two errors: String result = checkV2(german, "ein kleiner test. Und wieder Erwarten noch was: \u00f6\u00e4\u00fc\u00df."); assertTrue("Got result without 'UPPERCASE_SENTENCE_START': " + result, result.contains("UPPERCASE_SENTENCE_START")); assertTrue("Got result without 'WIEDER_WILLEN': " + result, result.contains("WIEDER_WILLEN")); assertTrue("Expected special chars, got: '" + result + "'", result.contains("\u00f6\u00e4\u00fc\u00df")); // special chars are intact assertTrue(checkV2(german, "bla <script>").contains("<script>")); // no escaping of '<' and '>' needed, unlike in XML // other tests for special characters String germanSpecialChars = checkV2(german, "ein kleiner test. Und wieder Erwarten noch was: + ."); assertTrue("Expected special chars, got: '" + germanSpecialChars + "'", germanSpecialChars.contains("+")); String romanianSpecialChars = checkV2(new Romanian(), "bla bla i cteva caractere speciale"); assertTrue("Expected special chars, got: '" + romanianSpecialChars + "'", romanianSpecialChars.contains("")); Polish polish = new Polish(); String polishSpecialChars = checkV2(polish, "Mwia dugo, eby tylko mwi mwi dugo."); assertTrue("Expected special chars, got: '" + polishSpecialChars + "'", polishSpecialChars.contains("mwi")); // test http POST assertTrue(checkByPOST(new Romanian(), "greit greit").contains("greit")); // test supported language listing URL url = new URL("http://localhost:" + HTTPTools.getDefaultPort() + "/v2/languages"); String languagesJson = StringTools.streamToString((InputStream) url.getContent(), "UTF-8"); if (!languagesJson.contains("Romanian") || !languagesJson.contains("English")) { fail("Error getting supported languages: " + languagesJson); } if (!languagesJson.contains("\"de\"") || !languagesJson.contains("\"de-DE\"")) { fail("Error getting supported languages: " + languagesJson); } // tests for "&" character English english = new English(); assertTrue(checkV2(english, "Me & you you").contains("&")); // tests for mother tongue (copy from link {@link FalseFriendRuleTest}) //assertTrue(checkV2(english, german, "My handy is broken.").contains("EN_FOR_DE_SPEAKERS_FALSE_FRIENDS")); // only works with ngrams assertFalse(checkV2(english, german, "We will berate you").contains("BERATE")); // not active anymore now that we have EN_FOR_DE_SPEAKERS_FALSE_FRIENDS assertTrue(checkV2(german, english, "Man sollte ihn nicht so beraten.").contains("BERATE")); assertTrue(checkV2(polish, english, "To jest frywolne.").contains("FRIVOLOUS")); //test for no changed if no options set String[] nothing = {}; assertEquals(checkV2(english, german, "We will berate you"), checkWithOptionsV2(english, german, "We will berate you", nothing, nothing, false)); //disabling String[] disableAvsAn = { "EN_A_VS_AN" }; assertTrue(!checkWithOptionsV2(english, german, "This is an test", nothing, disableAvsAn, false) .contains("an test")); //enabling assertTrue(checkWithOptionsV2(english, german, "This is an test", disableAvsAn, nothing, false) .contains("an test")); //should also mean _NOT_ disabling all other rules... assertTrue(checkWithOptionsV2(english, german, "We will will do so", disableAvsAn, nothing, false) .contains("ENGLISH_WORD_REPEAT_RULE")); //..unless explicitly stated. assertTrue(!checkWithOptionsV2(english, german, "We will berate you", disableAvsAn, nothing, true) .contains("BERATE")); //test if two rules get enabled as well String[] twoRules = { "EN_A_VS_AN", "ENGLISH_WORD_REPEAT_RULE" }; String resultEn = checkWithOptionsV2(english, german, "This is an test. We will will do so.", twoRules, nothing, false); assertTrue("Result: " + resultEn, resultEn.contains("EN_A_VS_AN")); assertTrue("Result: " + resultEn, resultEn.contains("ENGLISH_WORD_REPEAT_RULE")); //check two disabled options String result3 = checkWithOptionsV2(english, german, "This is an test. We will will do so.", nothing, twoRules, false); assertFalse("Result: " + result3, result3.contains("EN_A_VS_AN")); assertFalse("Result: " + result3, result3.contains("ENGLISH_WORD_REPEAT_RULE")); //two disabled, one enabled, so enabled wins String result4 = checkWithOptionsV2(english, german, "This is an test. We will will do so.", disableAvsAn, twoRules, false); assertTrue("Result: " + result4, result4.contains("EN_A_VS_AN")); assertFalse("Result: " + result4, result4.contains("ENGLISH_WORD_REPEAT_RULE")); String result5 = checkV2(null, "This is a test of the language detection."); assertTrue("Result: " + result5, result5.contains("\"en-US\"")); String result6 = checkV2(null, "This is a test of the language detection.", "&preferredVariants=de-DE,en-GB"); assertTrue("Result: " + result6, result6.contains("\"en-GB\"")); // fallback not working anymore, now giving confidence rating; tested in TextCheckerTest //String result7 = checkV2(null, "x"); // too short for auto-fallback, will use fallback //assertTrue("Result: " + result7, result7.contains("\"en-US\"")); String res = check("text", "/v2/check", english, null, "A text.", "&sourceLanguage=de-DE&sourceText=Text"); assertTrue(res.contains("DIFFERENT_PUNCTUATION")); // bitext rule actually active }
From source file:org.eclipse.birt.chart.ui.swt.composites.MarkerIconDialog.java
/** * Preview the image when it is a local image file. * //w w w .j a va 2 s. c om * @param uri * Image absolute path without "file:///" */ private ImageStatus preview(String uri) { hasUriImagePreviewed = true; try { URL url = new URL(uri); // there's no need to enable the ok button when processing url.getContent(); if (previewCanvas.loadImage(url) != null) { emptyExceptionText(); } return ImageStatus.IMAGE_CAN_DISPLAY; } catch (MalformedURLException malEx) { showMessage(Messages.getString("MarkerIconDialog.Exception.InvalidURL"));//$NON-NLS-1$ return ImageStatus.IMAGE_URL_INVALID; } catch (Exception ex) { showMessage(Messages.getString("MarkerIconDialog.Exception.ImageNotAvailable")); //$NON-NLS-1$ return ImageStatus.IMAGE_CANNOT_DISPLAY; } }
From source file:org.kuali.coeus.propdev.impl.s2s.S2sSubmissionServiceImpl.java
private String getOpportunityContent(String schemaUrl) throws S2sCommunicationException { String opportunity = ""; InputStream is = null;// w w w . j a v a2 s. c om BufferedInputStream br = null; try { URL url = new URL(schemaUrl); is = (InputStream) url.getContent(); br = new BufferedInputStream(is); byte bufContent[] = new byte[is.available()]; br.read(bufContent); opportunity = new String(bufContent); } catch (Exception e) { LOG.error(ERROR_MESSAGE, e); throw new S2sCommunicationException(KeyConstants.ERROR_GRANTSGOV_FORM_SCHEMA_NOT_FOUND, e.getMessage(), schemaUrl); } finally { try { if (is != null) is.close(); if (br != null) br.close(); } catch (IOException e) { LOG.error("Cannot close stream after fetching the content of opportinity schema", e); } } return opportunity; }
From source file:com.adflake.AdFlakeManager.java
/** * Fetch image with the specified url.//from w w w . j av a 2s .com * * @param urlString * the url string * @return the drawable */ private Drawable fetchImageWithURL(String urlString) { try { URL url = new URL(urlString); InputStream is = (InputStream) url.getContent(); Drawable d = Drawable.createFromStream(is, "src"); return d; } catch (Exception e) { Log.e(AdFlakeUtil.ADFLAKE, "Unable to fetchImage(): ", e); return null; } }
From source file:org.jets3t.gui.GuiUtils.java
/** * Loads an icon image from the classpath and sets the icon of the component. * * @param component/*from ww w . j ava 2s. c o m*/ * the component to apply the icon to, supported components are: JMenuItem, JButton, JLabel, Frame. * @param iconResourcePath * the path to an icon image in the classpath. * * @return * true if the icon was found and applied to the component */ public boolean applyIcon(Object component, String iconResourcePath) { ImageIcon icon = (ImageIcon) cachedImageIcons.get(iconResourcePath); if (icon == null) { // Icon is not yet cached, load it as a resource. URL iconUrl = this.getClass().getResource(iconResourcePath); if (iconUrl == null) { // Try loading icon using an encoded URL, which can help if the path uses characters // that should be URL-encoded (eg '+') try { int firstSlashIndex = iconResourcePath.indexOf('/', 1); String firstPathComponent = iconResourcePath.substring(0, firstSlashIndex); String pathRemainder = iconResourcePath.substring(firstSlashIndex); URL baseUrl = this.getClass().getResource(firstPathComponent); iconUrl = new URL(baseUrl.toString() + RestUtils.encodeUrlPath(pathRemainder, "/")); iconUrl.getContent(); // Check whether there is data availabel at the built path. } catch (Exception e) { log.warn("Unable to load icon with resource path: " + iconResourcePath); return false; } } if (iconUrl != null) { icon = new ImageIcon(iconUrl); cachedImageIcons.put(iconResourcePath, icon); } } if (icon != null) { if (component instanceof JMenuItem) { ((JMenuItem) component).setIcon(icon); } else if (component instanceof JButton) { ((JButton) component).setIcon(icon); } else if (component instanceof JLabel) { ((JLabel) component).setIcon(icon); } else if (component instanceof Frame) { ((Frame) component).setIconImage(icon.getImage()); } else { log.warn("Cannot set icon for unexpected JComponent object: " + component.getClass().getName()); return false; } return true; } else { log.warn("Unable to load icon with resource path: " + iconResourcePath); return false; } }
From source file:org.pluroid.pluroium.PlurkHelper.java
public Bitmap getAvatar(String userId, String scale, String avatarIndex) { Bitmap avatar = null;//from ww w . j a va 2 s.c o m try { File cacheDir = Utils.ensureCache(context, "avatars"); if ("".equals(avatarIndex) || "null".equals(avatarIndex) || avatarIndex == null) { avatarIndex = "0"; } String filename = scale + "-" + avatarIndex + ".png"; File d = new File(cacheDir, userId); if (d.exists()) { File f = new File(d, filename); if (f.exists()) { FileInputStream fis = new FileInputStream(f); avatar = BitmapFactory.decodeStream(fis); } } } catch (IOException e) { Log.e(TAG, "Read avatar cache failed!", e); } if (avatar == null) { // re-fetch the avatar if ("0".equals(avatarIndex) || "null".equals(avatarIndex) || avatarIndex == null) { avatarIndex = ""; } String suffix = ".gif"; if ("big".equals(scale)) { suffix = ".jpg"; } String url = "http://avatars.plurk.com/" + userId + "-" + scale + avatarIndex + suffix; InputStream is = null; try { Log.d(TAG, "Fetch avatar: " + url); URL avatarUrl = new URL(url); is = (InputStream) avatarUrl.getContent(); avatar = BitmapFactory.decodeStream(is); if (avatar != null) { File cacheDir = Utils.ensureCache(context, "avatars"); if ("".equals(avatarIndex)) { avatarIndex = "0"; } String filename = scale + "-" + avatarIndex + ".png"; File d = new File(cacheDir, userId); if (!d.exists()) { d.mkdirs(); } File f = new File(d, filename); if (!f.exists()) { f.createNewFile(); FileOutputStream fos = new FileOutputStream(f); avatar.compress(CompressFormat.PNG, 100, fos); fos.close(); } } } catch (IOException e) { Log.e(TAG, "Fetch avatar fail!", e); } } return avatar; }
From source file:org.kuali.kra.s2s.service.impl.KRAS2SServiceImpl.java
private String getOpportunityContent(String schemaUrl) throws S2SException { String opportunity = ""; InputStream is = null;// ww w . j av a 2s . com BufferedInputStream br = null; try { URL url = new URL(schemaUrl); is = (InputStream) url.getContent(); br = new BufferedInputStream(is); byte bufContent[] = new byte[is.available()]; br.read(bufContent); opportunity = new String(bufContent); } catch (Exception e) { LOG.error(S2SConstants.ERROR_MESSAGE, e); throw new S2SException(KeyConstants.ERROR_GRANTSGOV_FORM_SCHEMA_NOT_FOUND, e.getMessage(), schemaUrl); } finally { try { if (is != null) is.close(); if (br != null) br.close(); } catch (IOException e) { LOG.error("Cannot close stream after fetching the content of opportinity schema", e); } } return opportunity; }
From source file:org.hupo.psi.mi.psicquic.registry.PsicquicRegistryStatusChecker.java
private void checkStatus(ServiceType serviceStatus) { HttpURLConnection urlConnection = null; InputStream contentStream = null; InputStream countStream = null; try {// w w w.j a v a 2 s. c o m final URL versionUrl = new URL(serviceStatus.getRestUrl() + "version"); final URL countURL = new URL(serviceStatus.getRestUrl() + "query/*?format=count"); urlConnection = (HttpURLConnection) versionUrl.openConnection(); urlConnection.setConnectTimeout(threadTimeOut * 1000); urlConnection.setReadTimeout(threadTimeOut * 1000); urlConnection.connect(); int code = urlConnection.getResponseCode(); if (HttpURLConnection.HTTP_OK == code) { serviceStatus.setActive(true); final String version; final String strCount; //TODO Add a double check to know if the service is active // or not add a catch block for the exceptions contentStream = (InputStream) urlConnection.getContent(); version = IOUtils.toString(contentStream); serviceStatus.setVersion(version); countStream = (InputStream) countURL.getContent(); strCount = IOUtils.toString(countStream); serviceStatus.setCount(Long.valueOf(strCount)); } else { serviceStatus.setActive(false); } } catch (Throwable e) { serviceStatus.setActive(false); } finally { if (contentStream != null) { try { contentStream.close(); } catch (IOException e) { log.error("Cannot close psicquic content stream", e); } } if (countStream != null) { try { countStream.close(); } catch (IOException e) { log.error("Cannot close psicquic count stream", e); } } if (urlConnection != null) { urlConnection.disconnect(); } } }
From source file:org.apache.synapse.registry.url.SimpleURLRegistry.java
public RegistryEntry[] getChildren(RegistryEntry entry) { URL url; if (entry == null) { RegistryEntryImpl entryImpl = new RegistryEntryImpl(); entryImpl.setKey(""); entry = entryImpl;/*from www .ja va 2s.c om*/ } url = SynapseConfigUtils.getURLFromPath(root + entry.getKey(), properties.get(SynapseConstants.SYNAPSE_HOME) != null ? properties.get(SynapseConstants.SYNAPSE_HOME).toString() : ""); if (url == null) { return null; } if (url.getProtocol().equals("file")) { File file = new File(url.getFile()); if (!file.isDirectory()) { return null; } BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader((InputStream) url.getContent())); ArrayList<RegistryEntry> entryList = new ArrayList<RegistryEntry>(); String key; while ((key = reader.readLine()) != null) { RegistryEntryImpl registryEntryImpl = new RegistryEntryImpl(); if (entry.getKey().equals("")) { registryEntryImpl.setKey(key); } else { if (entry.getKey().endsWith("/")) { registryEntryImpl.setKey(entry.getKey() + key); } else { registryEntryImpl.setKey(entry.getKey() + "/" + key); } } entryList.add(registryEntryImpl); } RegistryEntry[] entries = new RegistryEntry[entryList.size()]; for (int i = 0; i < entryList.size(); i++) { entries[i] = entryList.get(i); } return entries; } catch (Exception e) { throw new SynapseException("Error in reading the URL."); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } } } else { throw new SynapseException("Invalid protocol."); } }
From source file:org.vufind.MaterialsRequest.java
/** * If a title has been added to the catalog, add *//* w w w. ja v a2s . c om*/ private void generateHolds() { processLog.addNote("Generating holds for materials requests that have arrived"); //Get a list of requests to generate holds for try { PreparedStatement requestsToEmailStmt = vufindConn.prepareStatement( "SELECT materials_request.*, cat_username, cat_password FROM materials_request inner join user on user.id = materials_request.createdBy WHERE placeHoldWhenAvailable = 1 and holdsCreated = 0 and status IN ('owned', 'purchased')"); PreparedStatement setHoldsCreatedStmt = vufindConn .prepareStatement("UPDATE materials_request SET holdsCreated=1 where id =?"); ResultSet requestsToCreateHolds = requestsToEmailStmt.executeQuery(); //For each request, while (requestsToCreateHolds.next()) { boolean holdCreated = false; //Check to see if the title has been received based on the ISBN or OCLC Number String requestId = requestsToCreateHolds.getString("id"); String requestIsbn = requestsToCreateHolds.getString("isbn"); String requestIssn = requestsToCreateHolds.getString("issn"); String requestUpc = requestsToCreateHolds.getString("upc"); String requestOclcNumber = requestsToCreateHolds.getString("oclcNumber"); String holdPickupLocation = requestsToCreateHolds.getString("holdPickupLocation"); String cat_username = requestsToCreateHolds.getString("cat_username"); String cat_password = requestsToCreateHolds.getString("cat_password"); String recordId = null; //Search for the isbn if ((requestIsbn != null && requestIsbn.length() > 0) || (requestIssn != null && requestIssn.length() > 0) || (requestUpc != null && requestUpc.length() > 0) || (requestOclcNumber != null && requestOclcNumber.length() > 0)) { URL searchUrl; if (requestIsbn != null && requestIsbn.length() > 0) { searchUrl = new URL( vufindUrl + "/API/SearchAPI?method=search&lookfor=" + requestIsbn + "&type=isn"); } else if (requestIssn != null && requestIssn.length() > 0) { searchUrl = new URL( vufindUrl + "/API/SearchAPI?method=search&lookfor=" + requestIssn + "&type=isn"); } else if (requestUpc != null && requestUpc.length() > 0) { searchUrl = new URL( vufindUrl + "/API/SearchAPI?method=search&lookfor=" + requestUpc + "&type=isn"); } else { searchUrl = new URL(vufindUrl + "/API/SearchAPI?method=search&lookfor=oclc" + requestOclcNumber + "&type=allfields"); } Object searchDataRaw = searchUrl.getContent(); if (searchDataRaw instanceof InputStream) { String searchDataJson = Util.convertStreamToString((InputStream) searchDataRaw); try { JSONObject searchData = new JSONObject(searchDataJson); JSONObject result = searchData.getJSONObject("result"); if (result.getInt("recordCount") > 0) { //Found a record JSONArray recordSet = result.getJSONArray("recordSet"); JSONObject firstRecord = recordSet.getJSONObject(0); recordId = firstRecord.getString("id"); } } catch (JSONException e) { logger.error("Unable to load search result", e); processLog.incErrors(); processLog.addNote("Unable to load search result " + e.toString()); } } else { logger.error("Error searching for isbn " + requestIsbn); processLog.incErrors(); processLog.addNote("Error searching for isbn " + requestIsbn); } } if (recordId != null) { //Place a hold on the title for the user URL placeHoldUrl; if (recordId.matches("econtentRecord\\d+")) { placeHoldUrl = new URL(vufindUrl + "/API/UserAPI?method=placeEContentHold&username=" + cat_username + "&password=" + cat_password + "&recordId=" + recordId); } else { placeHoldUrl = new URL( vufindUrl + "/API/UserAPI?method=placeHold&username=" + cat_username + "&password=" + cat_password + "&bibId=" + recordId + "&campus=" + holdPickupLocation); } logger.info("Place Hold URL: " + placeHoldUrl); Object placeHoldDataRaw = placeHoldUrl.getContent(); if (placeHoldDataRaw instanceof InputStream) { String placeHoldDataJson = Util.convertStreamToString((InputStream) placeHoldDataRaw); try { JSONObject placeHoldData = new JSONObject(placeHoldDataJson); JSONObject result = placeHoldData.getJSONObject("result"); holdCreated = result.getBoolean("success"); if (holdCreated) { logger.info("hold was created successfully."); processLog.incUpdated(); } else { logger.info("hold could not be created " + result.getString("holdMessage")); processLog.incErrors(); processLog.addNote("hold could not be created " + result.getString("holdMessage")); } } catch (JSONException e) { logger.error("Unable to load results of placing the hold", e); processLog.incErrors(); processLog.addNote("Unable to load results of placing the hold " + e.toString()); } } } if (holdCreated) { //Mark that the hold was created setHoldsCreatedStmt.setString(1, requestId); setHoldsCreatedStmt.executeUpdate(); } } } catch (Exception e) { logger.error("Error generating holds for purchased requests ", e); processLog.incErrors(); processLog.addNote("Error generating holds for purchased requests " + e.toString()); } }