List of usage examples for java.net MalformedURLException toString
public String toString()
From source file:com.easy.facebook.android.apicall.RestApi.java
private String postToFriendCall(String message, String friendID, String urlPicture) throws EasyFacebookError { Bundle params = new Bundle(); params.putString("format", "json"); params.putString("method", "stream.publish"); params.putString("access_token", facebook.getAccessToken()); params.putString("message", message); params.putString("target_id", friendID); if (urlPicture != null) { String pictureName = urlPicture.substring(urlPicture.lastIndexOf('/'), urlPicture.length()); params.putString("attachment", "{\"media\": [{\"type\": \"image\",\"src\": \"" + pictureName + "\", \"href\": \"" + urlPicture + "\"}]}"); }/*from w ww .ja v a 2 s.co m*/ String jsonResponse = ""; try { jsonResponse = Util.openUrl("https://api.facebook.com/restserver.php", "POST", params); } catch (MalformedURLException e) { throw new EasyFacebookError(e.toString(), "MalformedURLException"); } catch (IOException e) { throw new EasyFacebookError(e.toString(), "IOException"); } return jsonResponse.replace("\"", ""); }
From source file:com.easy.facebook.android.apicall.RestApi.java
public List<String> getFriendUIDs() throws EasyFacebookError { Bundle params = new Bundle(); params.putString("format", "json"); params.putString("method", "friends.get"); params.putString("access_token", facebook.getAccessToken()); String jsonResponse;/*from ww w. java2 s. c o m*/ List<String> stringList = new ArrayList<String>(); try { jsonResponse = Util.openUrl("https://api.facebook.com/restserver.php", "POST", params); JSONArray jsonArray = new JSONArray(jsonResponse); for (int i = 0; i < jsonArray.length(); i++) stringList.add(jsonArray.get(i).toString().replaceAll("\"", "")); } catch (MalformedURLException e) { throw new EasyFacebookError(e.toString(), "MalformedURLException"); } catch (IOException e) { throw new EasyFacebookError(e.toString(), "IOException"); } catch (JSONException e) { throw new EasyFacebookError(e.toString(), "JSONException"); } return stringList; }
From source file:com.easy.facebook.android.apicall.RestApi.java
private List<Status> getStatusCall(Integer limit) throws EasyFacebookError { Bundle params = new Bundle(); params.putString("format", "json"); params.putString("method", "status.get"); params.putString("access_token", facebook.getAccessToken()); if (limit != null) params.putString("limit", limit.toString()); String jsonResponse;/* w w w .j a va 2 s .c o m*/ List<Status> statusList = new ArrayList<Status>(); try { jsonResponse = Util.openUrl("https://api.facebook.com/restserver.php", "POST", params); JSONObjectDecode jsonArray = new JSONObjectDecode(jsonResponse); for (int i = 0; i < jsonArray.length(); i++) statusList.add(jsonArray.getStatus(i)); } catch (MalformedURLException e) { throw new EasyFacebookError(e.toString(), "MalformedURLException"); } catch (IOException e) { throw new EasyFacebookError(e.toString(), "IOException"); } catch (JSONException e) { throw new EasyFacebookError(e.toString(), "JSONException"); } return statusList; }
From source file:info.smartkit.hairy_batman.query.SogouSearchQuery.java
public String getJsonContent(String urlStr) { try {// ?HttpURLConnection URL url = new URL(urlStr); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); // //w w w . j a va2 s . co m httpConn.setConnectTimeout(3000); httpConn.setDoInput(true); httpConn.setRequestMethod("GET"); // ?? int respCode = httpConn.getResponseCode(); if (respCode == 200) { String a = ConvertStream2Json(httpConn.getInputStream()); return a.substring(a.indexOf("(") + 1, a.lastIndexOf(")")); } } catch (MalformedURLException e) { LOG.error(e.toString()); } catch (IOException e) { LOG.error(e.toString()); } return ""; }
From source file:org.apache.nutch.plugin.PluginManifestParser.java
/** * Returns a list of all found plugin descriptors. * /* w ww . j av a2s. c om*/ * @param pluginFolders * folders to search plugins from * @return A {@link Map} of all found {@link PluginDescriptor}s. */ public Map<String, PluginDescriptor> parsePluginFolder(String[] pluginFolders) { Map<String, PluginDescriptor> map = new HashMap<String, PluginDescriptor>(); if (pluginFolders == null) { throw new IllegalArgumentException("plugin.folders is not defined"); } for (String name : pluginFolders) { File directory = getPluginFolder(name); if (directory == null) { continue; } LOG.info("Plugins: looking in: " + directory.getAbsolutePath()); for (File oneSubFolder : directory.listFiles()) { if (oneSubFolder.isDirectory()) { String manifestPath = oneSubFolder.getAbsolutePath() + File.separator + "plugin.xml"; try { LOG.debug("parsing: " + manifestPath); PluginDescriptor p = parseManifestFile(manifestPath); map.put(p.getPluginId(), p); } catch (MalformedURLException e) { LOG.warn(e.toString()); } catch (SAXException e) { LOG.warn(e.toString()); } catch (IOException e) { LOG.warn(e.toString()); } catch (ParserConfigurationException e) { LOG.warn(e.toString()); } } } } return map; }
From source file:com.intuit.tank.http.multipart.MultiPartRequest.java
/** * Execute the POST.//from w ww. j a v a 2 s . c o m */ public void doPost(BaseResponse response) { PostMethod httppost = null; String theUrl = null; try { URL url = BaseRequestHandler.buildUrl(protocol, host, port, path, urlVariables); theUrl = url.toExternalForm(); httppost = new PostMethod(url.toString()); String requestBody = getBody(); List<Part> parts = buildParts(); httppost.setRequestEntity( new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), httppost.getParams())); sendRequest(response, httppost, requestBody); } catch (MalformedURLException e) { LOG.error(LogUtil.getLogMessage("Malformed URL Exception: " + e.toString(), LogEventType.IO), e); // swallowing error. validatin will check if there is no response // and take appropriate action throw new RuntimeException(e); } catch (Exception ex) { // logger.error(LogUtil.getLogMessage(ex.toString()), ex); // swallowing error. validatin will check if there is no response // and take appropriate action throw new RuntimeException(ex); } finally { if (null != httppost) { httppost.releaseConnection(); } if (APITestHarness.getInstance().getTankConfig().getAgentConfig().getLogPostResponse()) { LOG.info( LogUtil.getLogMessage( "Response from POST to " + theUrl + " got status code " + response.getHttpCode() + " BODY { " + response.getResponseBody() + " }", LogEventType.Informational)); } } }
From source file:net.kervala.comicsreader.BrowseRemoteAlbumsTask.java
@Override protected String doInBackground(String... params) { String error = null;//from ww w. j a v a2 s . c om URL url = null; try { // open a stream on URL url = new URL(mUrl); } catch (MalformedURLException e) { error = e.toString(); e.printStackTrace(); } boolean retry = false; HttpURLConnection urlConnection = null; int resCode = 0; do { // create the new connection ComicsAuthenticator.sInstance.reset(); if (urlConnection != null) { urlConnection.disconnect(); } try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(ComicsParameters.TIME_OUT); urlConnection.setReadTimeout(ComicsParameters.TIME_OUT); resCode = urlConnection.getResponseCode(); } catch (EOFException e) { // under Android 4 resCode = -1; } catch (IOException e) { e.printStackTrace(); } Log.d("ComicsReader", "Rescode " + resCode); if (resCode < 0) { retry = true; } else if (resCode == 401) { ComicsAuthenticator.sInstance.setResult(false); // user pressed cancel if (!ComicsAuthenticator.sInstance.isValidated()) { return null; } retry = true; } else { retry = false; } } while (retry); if (resCode != HttpURLConnection.HTTP_OK) { ComicsAuthenticator.sInstance.setResult(false); // TODO: HTTP error occurred return null; } final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); InputStream is = null; try { // download the file is = new BufferedInputStream(urlConnection.getInputStream(), ComicsParameters.BUFFER_SIZE); int count = 0; byte data[] = new byte[ComicsParameters.BUFFER_SIZE]; while ((count = is.read(data)) != -1) { bytes.write(data, 0, count); } ComicsAuthenticator.sInstance.setResult(true); } catch (IOException e) { error = e.toString(); e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (urlConnection != null) { urlConnection.disconnect(); } } if (bytes != null) { final String text = new String(bytes.toByteArray()); if (text.contains("<albums>")) { parseXml(text); } else if (text.contains("\"albums\":")) { parseJson(text); } else { Log.e("ComicsReader", "Error"); } } return error; }
From source file:org.biopax.validator.ws.ValidatorController.java
/** * JSP pages and RESTful web services controller, the main one that checks BioPAX data. * All parameter names are important, i.e., these are part of public API (for clients) * //from ww w . j av a 2 s .c om * Framework's built-in parameters: * @param request the web request object (may contain multi-part data, i.e., multiple files uploaded) * @param response * @param mvcModel Spring MVC Model * @param writer HTTP response writer * * BioPAX Validator/Normalizer query parameters: * @param url * @param retDesired * @param autofix * @param filter * @param maxErrors * @param profile * @param normalizer binds to three boolean options: normalizer.fixDisplayName, normalizer.inferPropertyOrganism, normalizer.inferPropertyDataSource * @return * @throws IOException */ @RequestMapping(value = "/check", method = RequestMethod.POST) public String check(HttpServletRequest request, HttpServletResponse response, Model mvcModel, Writer writer, @RequestParam(required = false) String url, @RequestParam(required = false) String retDesired, @RequestParam(required = false) Boolean autofix, @RequestParam(required = false) Behavior filter, @RequestParam(required = false) Integer maxErrors, @RequestParam(required = false) String profile, //normalizer!=null when called from the JSP; //but it's usually null when from the validator-client or a web script @ModelAttribute("normalizer") Normalizer normalizer) throws IOException { Resource resource = null; // a resource to validate // create the response container ValidatorResponse validatorResponse = new ValidatorResponse(); if (url != null && url.length() > 0) { if (url != null) log.info("url : " + url); try { resource = new UrlResource(url); } catch (MalformedURLException e) { mvcModel.addAttribute("error", e.toString()); return "check"; } try { Validation v = execute(resource, resource.getDescription(), maxErrors, autofix, filter, profile, normalizer); validatorResponse.addValidationResult(v); } catch (Exception e) { return errorResponse(mvcModel, "check", "Exception: " + e); } } else if (request instanceof MultipartHttpServletRequest) { MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; Map files = multiRequest.getFileMap(); Assert.state(!files.isEmpty(), "No files to validate"); for (Object o : files.values()) { MultipartFile file = (MultipartFile) o; String filename = file.getOriginalFilename(); // a workaround (for some reason there is always a no-name-file; // this might be a javascript isue) if (file.getBytes().length == 0 || filename == null || "".equals(filename)) continue; log.info("check : " + filename); resource = new ByteArrayResource(file.getBytes()); try { Validation v = execute(resource, filename, maxErrors, autofix, filter, profile, normalizer); validatorResponse.addValidationResult(v); } catch (Exception e) { return errorResponse(mvcModel, "check", "Exception: " + e); } } } else { return errorResponse(mvcModel, "check", "No BioPAX input source provided!"); } if ("xml".equalsIgnoreCase(retDesired)) { response.setContentType("application/xml"); ValidatorUtils.write(validatorResponse, writer, null); } else if ("html".equalsIgnoreCase(retDesired)) { /* could also use ValidatorUtils.write with a xml-to-html xslt source but using JSP here makes it easier to keep the same style, header, footer*/ mvcModel.addAttribute("response", validatorResponse); return "groupByCodeResponse"; } else { // owl only response.setContentType("text/plain"); // write all the OWL results one after another TODO any better solution? for (Validation result : validatorResponse.getValidationResult()) { if (result.getModelData() != null) writer.write(result.getModelData() + NEWLINE); else // empty result writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<rdf:RDF></rdf:RDF>" + NEWLINE); } } return null; // (Writer is used instead) }
From source file:trollbox.GateClient.java
public void preparePipeline() throws MalformedURLException { if (!isGateInitilised) { // initialise GATE initialiseGate();/*from w w w .j av a2 s . c o m*/ } try { // create an instance of a Document Reset processing resource ProcessingResource documentResetPR = (ProcessingResource) Factory .createResource("gate.creole.annotdelete.AnnotationDeletePR"); // create an instance of a English Tokeniser processing resource ProcessingResource tokenizerPR = (ProcessingResource) Factory .createResource("gate.creole.tokeniser.DefaultTokeniser"); // create an instance of a Sentence Splitter processing resource //ProcessingResource sentenceSplitterPR = (ProcessingResource) Factory.createResource("gate.creole.splitter.SentenceSplitter"); /*System.out.println("Working Directory = " + System.getProperty("user.dir")); */ // locate the JAPE grammar file File japeOrigFile = new File("/Users/jakub/Documents/skola/ddw/jape/trollbox.jape"); java.net.URI japeURI = japeOrigFile.toURI(); // create feature map for the transducer FeatureMap transducerFeatureMap = Factory.newFeatureMap(); try { // set the grammar location transducerFeatureMap.put("grammarURL", japeURI.toURL()); // set the grammar encoding transducerFeatureMap.put("encoding", "UTF-8"); } catch (MalformedURLException e) { System.out.println("Malformed URL of JAPE grammar"); System.out.println(e.toString()); } // create an instance of a JAPE Transducer processing resource ProcessingResource japeTransducerPR = (ProcessingResource) Factory .createResource("gate.creole.Transducer", transducerFeatureMap); FeatureMap gazetteerFeatureMap = Factory.newFeatureMap(); try { // set the grammar location gazetteerFeatureMap.put("caseSensitive", "false"); // set the grammar encoding gazetteerFeatureMap.put("encoding", "UTF-8"); File listsFile = new File("/Users/jakub/Documents/skola/ddw/lists/trollbox.def"); java.net.URI listsURI = listsFile.toURI(); gazetteerFeatureMap.put("listsURL", listsURI.toURL()); } catch (MalformedURLException e) { System.out.println("Malformed URL of JAPE grammar"); System.out.println(e.toString()); } ProcessingResource gazetteer = (ProcessingResource) Factory .createResource("gate.creole.gazetteer.DefaultGazetteer", gazetteerFeatureMap); // create corpus pipeline annotationPipeline = (SerialAnalyserController) Factory .createResource("gate.creole.SerialAnalyserController"); // add the processing resources (modules) to the pipeline annotationPipeline.add(documentResetPR); annotationPipeline.add(tokenizerPR); annotationPipeline.add(gazetteer); //annotationPipeline.add(sentenceSplitterPR); annotationPipeline.add(japeTransducerPR); } catch (GateException ex) { Logger.getLogger(GateClient.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.freedomotic.plugins.devices.tcw122bcm.Tcw122bcm.java
private void changeRelayStatus(String hostname, int hostport, String relayNumber, int control) { try {//from ww w. j a v a 2 s .c o m String authString = USERNAME + ":" + PASSWORD; //System.out.println("auth string: " + authString); byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); //System.out.println("Base64 encoded auth string: " + authStringEnc); //FOR DEBUG //Create a URL for the desired page URL url = new URL("http://" + hostname + ":" + hostport + "/?" + relayNumber + "=" + control); LOG.info("Freedomotic sends the command " + url); URLConnection urlConnection = url.openConnection(); // if required set the authentication if (HTTP_AUTHENTICATION.equalsIgnoreCase("true")) { urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc); } InputStream is = urlConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); int numCharsRead; char[] charArray = new char[1024]; StringBuffer sb = new StringBuffer(); while ((numCharsRead = isr.read(charArray)) > 0) { sb.append(charArray, 0, numCharsRead); } String result = sb.toString(); } catch (MalformedURLException e) { LOG.severe("Change relay status malformed URL " + e.toString()); } catch (IOException e) { LOG.severe("Change relay status IOexception" + e.toString()); } }