List of usage examples for java.net MalformedURLException printStackTrace
public void printStackTrace()
From source file:net.kervala.comicsreader.BrowseRemoteAlbumsTask.java
@Override protected String doInBackground(String... params) { String error = null;// w w w .ja va 2 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:com.bazaarvoice.BazaarRequest.java
/** * Send a request, spawn a thread, and return the result via the listener. * (non-blocking)//w w w .j av a 2 s .co m * * @param type * the type of request * @param params * the parameters for the request * @param listener * the listener to handle the results on * @throws BazaarException */ public void sendDisplayRequest(final RequestType type, DisplayParams params, final OnBazaarResponse listener) { //build url xxxx.ugc.bazaarvoice.com/data/xxx.json String requestString = requestUrl + type.getDisplayName() + ".json"; //add API key and version requestString = requestString + "?" + "apiversion=" + apiVersion + "&" + "passkey=" + passKey; //if any, add params to request string if (params != null) { requestString = requestString + params.toURL(apiVersion, passKey); } this.url = null; try { url = new URL(requestString); } catch (MalformedURLException e) { e.printStackTrace(); } this.listener = listener; new AsyncTransaction().execute("GET"); }
From source file:edu.csh.coursebrowser.DepartmentActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_departments); // Show the Up button in the action bar. // getActionBar().setDisplayHomeAsUpEnabled(false); this.getActionBar().setHomeButtonEnabled(true); final Bundle b = this.getIntent().getExtras(); map_item = new HashMap<String, Department>(); map = new ArrayList<String>(); Bundle args = this.getIntent().getExtras(); this.setTitle(args.getCharSequence("from")); try {/* ww w. ja v a 2 s .c o m*/ JSONObject jso = new JSONObject(args.get("args").toString()); JSONArray jsa = new JSONArray(jso.getString("departments")); ListView lv = (ListView) this.findViewById(R.id.department_list); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, map); for (int i = 0; i < jsa.length(); ++i) { String s = jsa.getString(i); JSONObject obj = new JSONObject(s); Department dept = new Department(obj.getString("title"), obj.getString("id"), obj.getString("code")); addItem(dept); Log.v("Added", dept.toString()); } lv.setAdapter(adapter); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { String s = ((TextView) arg1).getText().toString(); final Department department = map_item.get(s); new AsyncTask<String, String, String>() { ProgressDialog p; protected void onPreExecute() { p = new ProgressDialog(DepartmentActivity.this); p.setTitle("Fetching Info"); p.setMessage("Contacting Server..."); p.setCancelable(false); p.show(); } protected String doInBackground(String... dep) { String params = "action=getCourses&department=" + dep[0] + "&quarter=" + b.getString("qCode"); Log.v("Params", params); URL url; String back = ""; try { url = new URL("http://iota.csh.rit" + ".edu/schedule/js/browseAjax" + ".php"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(params); writer.flush(); String line; BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getInputStream())); while ((line = reader.readLine()) != null) { Log.v("Back:", line); back += line; } writer.close(); reader.close(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); p.dismiss(); return null; } return back; } protected void onPostExecute(String s) { if (s == null || s == "") { new AlertError(DepartmentActivity.this, "IO Error!").show(); return; } try { JSONObject jso = new JSONObject(s); JSONArray jsa = new JSONArray(jso.getString("courses")); } catch (JSONException e) { e.printStackTrace(); new AlertError(DepartmentActivity.this, "Invalid JSON From Server").show(); p.dismiss(); return; } Intent intent = new Intent(DepartmentActivity.this, CourseActivity.class); intent.putExtra("title", department.title); intent.putExtra("id", department.id); intent.putExtra("code", department.code); intent.putExtra("args", s); startActivity(intent); p.dismiss(); } }.execute(department.id); } }); } catch (JSONException e) { // TODO Auto-generated catch block new AlertError(this, "Invalid JSON"); e.printStackTrace(); } }
From source file:ca.licef.lompad.Classification.java
public Classification(File file) { this.file = file; try {// w w w . ja v a 2s . c o m URL url = file.toURI().toURL(); this.url = url.toString(); } catch (MalformedURLException e) { e.printStackTrace(); // Should never happen. - FB } }
From source file:eu.udig.style.advanced.utils.Utilities.java
/** * Change the external graphic in a rule. * //from w ww.jav a 2s . c om * @param rule the rule of which the external graphic has to be changed. * @param path the path of the image. */ public static void substituteExternalGraphics(Rule rule, URL externalGraphicsUrl) { String urlString = externalGraphicsUrl.toString(); String format = ""; if (urlString.toLowerCase().endsWith(".png")) { format = "image/png"; } else if (urlString.toLowerCase().endsWith(".jpg")) { format = "image/jpg"; } else if (urlString.toLowerCase().endsWith(".svg")) { format = "image/svg+xml"; } else { urlString = ""; try { externalGraphicsUrl = new URL("file:"); } catch (MalformedURLException e) { e.printStackTrace(); } } PointSymbolizer pointSymbolizer = Utilities.pointSymbolizerFromRule(rule); Graphic graphic = SLDs.graphic(pointSymbolizer); graphic.graphicalSymbols().clear(); ExternalGraphic exGraphic = sf.createExternalGraphic(externalGraphicsUrl, format); graphic.graphicalSymbols().add(exGraphic); }
From source file:es.tekniker.framework.ktek.questionnaire.mng.server.OrionContextBrokerClient.java
public boolean subscribeContext(String codUser, String nameContext) { HttpURLConnection conn = null; StringBuffer strBOutput = new StringBuffer(); boolean boolOK = true; String input = null;//from w w w.ja v a 2 s . co m StringBuffer stbInput = new StringBuffer(); try { log.debug("subscribeContext Start "); conn = getOrionContextBrokerGEConnection(this.methodSubscribeContext, this.endpointOrionContextBroker, this.headerContentTypeJSON); stbInput.append("{\"entities\": [{\"type\": \"" + this.typeContextValue + "\",\"isPattern\": \"false\",\"id\": \"" + codUser + "\" } ],"); stbInput.append("\"attributes\": [\"" + nameContext + "\"] ,"); stbInput.append("\"reference\": \"" + this.notificationEndpoint + "\","); stbInput.append("\"duration\": \"P1M\","); stbInput.append("\"notifyConditions\": [ {\"type\": \"ONCHANGE\",\"condValues\": [\"" + nameContext + "\"]}],\"throttling\": \"PT5S\"}"); input = stbInput.toString(); log.debug(input); OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); if (conn.getResponseCode() == 200) { log.debug("subscribeContext Response code " + conn.getResponseCode()); } else if (conn.getResponseCode() != 201) { throw new RuntimeException("subscribeContext Failed : HTTP error code : " + conn.getResponseCode()); } log.debug("subscribeContext OutputStream wrote"); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); log.debug("subscribeContext Waiting server response "); log.debug("subscribeContext Output from Server .... \n"); String output; while ((output = br.readLine()) != null) { strBOutput.append(output); log.debug(output); } conn.disconnect(); boolOK = true; } catch (MalformedURLException e) { log.error("subscribeContext MalformedURLException " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { log.error("subscribeContext IOException " + e.getMessage()); e.printStackTrace(); } return boolOK; }
From source file:com.redhat.rhn.frontend.xmlrpc.packages.search.PackagesSearchHandler.java
protected List<PackageOverview> performSearch(String sessionKey, String query, String mode) throws FaultException { if (StringUtils.isBlank(query)) { throw new SearchServerQueryException(); }/* w ww . ja va 2s .com*/ WebSession session = SessionManager.loadSession(sessionKey); Long sessionId = session.getId(); List<PackageOverview> pkgs = null; try { pkgs = PackageSearchHelper.performSearch(sessionId, query, mode, null, null, true, null, PackageSearchAction.WHERE_ALL); } catch (MalformedURLException e) { log.info("Caught Exception :" + e); e.printStackTrace(); throw new SearchServerCommException(); } catch (XmlRpcFault e) { log.info("Caught Exception :" + e); e.printStackTrace(); // Connection error throw new SearchServerCommException(); } if (log.isDebugEnabled()) { log.debug("Query = : " + query + ", mode = " + mode); log.debug(pkgs.size() + " packages were fetched"); } return pkgs; }
From source file:es.tekniker.framework.ktek.questionnaire.mng.server.OrionContextBrokerClient.java
public boolean updateContext(String codUser, String nameContext, String typeContext, String valueContext, boolean valueIsjson) { HttpURLConnection conn = null; StringBuffer strBOutput = new StringBuffer(); boolean boolOK = true; String input = null;/*from w w w.j a v a 2 s .co m*/ StringBuffer stbInput = new StringBuffer(); try { log.debug("updateContext Start "); conn = getOrionContextBrokerGEConnection(this.methodUpdateContext, this.endpointOrionContextBroker, this.headerContentTypeJSON); stbInput.append("{\"contextElements\": [{\"type\": \"" + this.typeContextValue + "\",\"isPattern\": \"false\",\"id\": \"" + codUser + "\",\"attributes\":"); if (valueIsjson) { stbInput.append(" [{\"name\": \"" + nameContext + "\",\"type\": \"" + typeContext + "\",\"value\": " + valueContext + "}]}]"); } else { stbInput.append(" [{\"name\": \"" + nameContext + "\",\"type\": \"" + typeContext + "\",\"value\": \"" + valueContext + "\"}]}]"); } stbInput.append(",\"updateAction\": \"APPEND\"}"); input = stbInput.toString(); log.debug(input); OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); if (conn.getResponseCode() == 200) { log.debug("updateContext Response code " + conn.getResponseCode()); } else if (conn.getResponseCode() != 201) { throw new RuntimeException("updateContext Failed : HTTP error code : " + conn.getResponseCode()); } log.debug("updateContext OutputStream wrote"); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); log.debug("updateContext Waiting server response "); log.debug("updateContext Output from Server .... \n"); String output; while ((output = br.readLine()) != null) { strBOutput.append(output); log.debug(output); } conn.disconnect(); boolOK = true; } catch (MalformedURLException e) { log.error("updateContext MalformedURLException " + e.getMessage()); e.printStackTrace(); boolOK = false; } catch (IOException e) { log.error("updateContext IOException " + e.getMessage()); e.printStackTrace(); boolOK = false; } return boolOK; }
From source file:com.esri.geoevent.processor.geonames.GeoNamesWikipediaProcessor.java
private String getReverseGeocode(URL url) { String output = ""; try {// w ww . j a va 2 s . c o m HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { String errorString = "Failed : HTTP error code : " + conn.getResponseCode(); throw new RuntimeException(errorString); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String line; while ((line = br.readLine()) != null) { output += line; } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return output; }
From source file:com.concentricsky.android.khanacademy.data.remote.VideoProgressPostTask.java
private VideoProgressResult remoteFetch(VideoProgressUpdate update) { VideoProgressResult result = null;/*from ww w. ja v a2s. c om*/ String q = String.format(Locale.US, "last_second_watched=%d&seconds_watched=%d", update.getLast_second_watched(), update.getSeconds_watched()); url = String.format("%s?%s", url, q); Log.d(KAAPIAdapter.LOG_TAG, "posting video progress: " + url); // Use this! The response is chunked, so don't try to get the Content-Length and read a buffer of that length. // However, the response is small, so it isn't a big deal that this handler blocks until it's done. ResponseHandler<String> h = new BasicResponseHandler(); HttpClient httpClient = new DefaultHttpClient(); HttpPost request = new HttpPost(url); ObjectMapper mapper = new ObjectMapper(); try { consumer.sign(request); String response = httpClient.execute(request, h); result = mapper.readValue(response, VideoProgressResult.class); // DEBUG // User ud = result.action_results.user_data; // UserVideo uv = result.action_results.user_video; // if (result.action_results.badges_earned != null) { // List<Badge> badges = result.action_results.badges_earned.getBadges(); // if (badges != null) { // Log.d(KAAPIAdapter.LOG_TAG, "Badges: "); // for (Badge b : badges) { // Log.d(KAAPIAdapter.LOG_TAG, " " + b.getDescription() + " (" + b.getPoints() + " points)"); // } // } else { // Log.d(KAAPIAdapter.LOG_TAG, "badges was null"); // } // } else { // Log.d(KAAPIAdapter.LOG_TAG, "badges was null"); // } // // Log.d(KAAPIAdapter.LOG_TAG, "url was " + url); // Log.d(KAAPIAdapter.LOG_TAG, "got data for " + ud.getNickname() + ", video points: " + uv.getPoints()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (OAuthMessageSignerException e) { e.printStackTrace(); } catch (OAuthExpectationFailedException e) { e.printStackTrace(); } catch (OAuthCommunicationException e) { e.printStackTrace(); } catch (HttpResponseException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; }