Example usage for java.net MalformedURLException printStackTrace

List of usage examples for java.net MalformedURLException printStackTrace

Introduction

In this page you can find the example usage for java.net MalformedURLException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.sun.portal.rssportlet.FeedHelper.java

/**
 * Get the ROME SyndFeed object for the specified feed. The object may come
 * from a cache; the data in the feed may not be read at the time
 * this method is called./* ww  w  .  j  a va  2 s  .c  o  m*/
 *
 * The <code>RssPortletBean</code> object is used to identify the feed
 * of interest, and the timeout value to be used when managing this
 * feed's cached value.
 *
 * @param bean an <code>RssPortletBean</code> object that describes
 * the feed of interest, and the cache timeout value for the feed.
 * @return a ROME <code>SyndFeed</code> object encapsulating the
 * feed specified by the URL.
 */
public SyndFeed getFeed(SettingsBean bean, String selectedFeed) throws IOException, FeedException {
    SyndFeed feed = null;
    FeedElement feedElement = (FeedElement) feeds.get(selectedFeed);

    if (feedElement != null && !feedElement.isExpired()) {
        feed = feedElement.getFeed();
    } else {
        GetMethod httpget = null;
        try {
            SyndFeedInput input = new SyndFeedInput();

            HttpClient httpclient = new HttpClient();
            httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_TIMEOUT);
            // SO_TIMEOUT -- timeout for blocking reads
            httpclient.getHttpConnectionManager().getParams().setSoTimeout(SOCKET_TIMEOUT);

            httpget = new GetMethod(selectedFeed);

            //httpget.getParams().setParameter("http.socket.timeout", new Integer(20000));
            // Internally the parameter collections will be linked together
            // by performing the following operations: 
            // hostconfig.getParams().setDefaults(httpclient.getParams());
            // httpget.getParams().setDefaults(hostconfig.getParams());
            //httpclient.executeMethod(hostconfig, httpget);
            // Execute the method.

            int statusCode = httpclient.executeMethod(httpget);
            if (statusCode != HttpStatus.SC_OK) {
                log.info("Method failed: " + httpget.getStatusLine());
            }
            // Read the response body.
            InputSource src = new InputSource(httpget.getResponseBodyAsStream());
            // Deal with the response.
            // Use caution: ensure correct character encoding and is not binary data
            feed = input.build(src);
            //
            // only cache the feed if the cache timeout is not equal to 0
            // a cache timeout of 0 means "don't cache"
            //
            int timeout = bean.getCacheTimeout();
            if (timeout != 0) {
                putFeed(selectedFeed, feed, timeout);
            }
        } catch (MalformedURLException mfurlex) {
            log.info("MalformedURLException: " + mfurlex.getMessage());
            mfurlex.printStackTrace();
            throw new IOException("MalformedURLException: " + mfurlex.getMessage());
        } catch (HttpException httpex) {
            log.info("Fatal protocol violation: " + httpex.getMessage());
            httpex.printStackTrace();
            throw new IOException("Fatal protocol violation: " + httpex.getMessage());
        } catch (IllegalArgumentException iae) {
            log.info("IllegalArgumentException: " + iae.getMessage());
            iae.printStackTrace();
            throw new IOException("IllegalArgumentException: " + iae.getMessage());
        } catch (IOException ioe) {
            log.info("Fatal transport error: " + ioe.getMessage());
            ioe.printStackTrace();
            throw new IOException("Fatal transport error: " + ioe.getMessage());
        } catch (ParsingFeedException parsingfeedex) {
            log.info("ParsingFeedException: " + parsingfeedex.getMessage());
            parsingfeedex.printStackTrace();
            throw new FeedException("ParsingFeedException: " + parsingfeedex.getMessage());
        } catch (FeedException feedex) {
            log.info("FeedException: " + feedex.getMessage());
            feedex.printStackTrace();
            throw new FeedException("FeedException: " + feedex.getMessage());
        } catch (Exception ex) {
            log.info("Exception ERROR: " + ex.getMessage());
            ex.printStackTrace();
        } finally {
            // Release the connection.
            httpget.releaseConnection();
        }
    }
    return feed;
}

From source file:edu.csh.coursebrowser.CourseActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_course);
    // Show the Up button in the action bar.
    this.getActionBar().setHomeButtonEnabled(false);
    map_item = new HashMap<String, Course>();
    map = new ArrayList<String>();
    Bundle args = this.getIntent().getExtras();
    this.setTitle(args.getCharSequence("title"));
    try {/*from  w  w  w.  j a  va 2 s. co m*/
        JSONObject jso = new JSONObject(args.get("args").toString());
        JSONArray jsa = new JSONArray(jso.getString("courses"));
        ListView lv = (ListView) this.findViewById(R.id.course_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);
            Course course = new Course(obj.getString("title"), obj.getString("department"),
                    obj.getString("course"), obj.getString("description"), obj.getString("id"));
            addItem(course);
            Log.v("Added", course.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 Course course = map_item.get(s);
                new AsyncTask<String, String, String>() {
                    ProgressDialog p;

                    protected void onPreExecute() {
                        p = new ProgressDialog(CourseActivity.this);
                        p.setTitle("Fetching Info");
                        p.setMessage("Contacting Server...");
                        p.setCancelable(false);
                        p.show();
                    }

                    protected String doInBackground(String... dep) {
                        String params = "action=getSections&course=" + course.id;
                        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(CourseActivity.this, "IO Error!").show();
                            return;
                        }
                        try {
                            JSONObject jso = new JSONObject(s);
                            JSONArray jsa = new JSONArray(jso.getString("sections"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                            new AlertError(CourseActivity.this, "Invalid JSON From Server").show();
                            p.dismiss();
                            return;
                        }
                        Intent intent = new Intent(CourseActivity.this, SectionsActivity.class);
                        intent.putExtra("title", course.title);
                        intent.putExtra("id", course.id);
                        intent.putExtra("description", course.description);
                        intent.putExtra("args", s);
                        startActivity(intent);
                        p.dismiss();
                    }
                }.execute(course.id);
            }

        });

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        new AlertError(this, "Invalid JSON");
        e.printStackTrace();
    }

}

From source file:eu.planets_project.tb.impl.services.mockups.workflow.WorkflowDroidXCDLExtractorComparator.java

/**
 * Runs droid on a given File and returns an Array of PronomIDs
 * @param f1//w  w  w .  j a  va2  s . co m
 * @return
 * @throws Exception
 */
private String[] runDroid(File f1) throws Exception {
    //Step1: identify using droid - returns a status and a list of IDs
    URL url = null;
    try {
        url = new URL(URL_DROID);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        throw e;
    }
    Service service = Service.create(url, new QName(PlanetsServices.NS, Identify.NAME));
    Identify droid = service.getPort(Identify.class);
    byte[] array = FileUtils.readFileToByteArray(f1);

    //invoke the service and extract results
    IdentifyResult identify = droid.identify(new DigitalObject.Builder(Content.byValue(array)).build(), null);
    List<URI> result = identify.getTypes();
    String status = identify.getReport().getMessage();

    if (!status.equals("Positive")) {
        throw new Exception("Service execution failed");
    }
    if (result.size() < 1) {
        throw new Exception("The specified file type is currently not supported by this workflow");
    }

    String[] strings = new String[result.size()];
    for (int i = 0; i < result.size(); i++) {
        String string = result.get(i).toASCIIString();
        //received 1..n Pronom IDs
        strings[i] = string;
    }
    return strings;
}

From source file:com.tempescope.wunderground.WundergroundManager.java

public URL getURLForConditions(Coordinate coord) {
    String urlStr = "http://api.wunderground.com/api/" + api + "/conditions/q/" + coord.latitude + ","
            + coord.longitude + ".json";
    try {//from   www . j  a  v a 2  s .  com
        return new URL(urlStr);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.tempescope.wunderground.WundergroundManager.java

public URL getForecastURLForConditions(Coordinate coord) {
    String urlStr = "http://api.wunderground.com/api/" + api + "/hourly/q/" + coord.latitude + ","
            + coord.longitude + ".json";
    try {//from  w  w w  .  j a  v a2s  . co m
        return new URL(urlStr);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:eu.planets_project.tb.impl.services.mockups.workflow.WorkflowDroidXCDLExtractorComparator.java

/**
 * Runs the XCDL extractor on a given file and for a given xcel descriptor
 * Returns the XCDL description (UTF-8 encoded) for the provided file
 * @param f1/*  w w  w  .  j  av a 2  s .c o m*/
 * @param xcel
 * @return
 * @throws Exception
 */
private String runXCDLExtractor(File f1 /*, String xcel*/) throws Exception {
    URL url = null;
    try {
        url = new URL(URL_XCDLEXTRACTOR);

        Service service = Service.create(url, new QName(PlanetsServices.NS, Migrate.NAME));
        Migrate extractor = service.getPort(Migrate.class);

        //the service's input
        byte[] array = FileUtils.readFileToByteArray(f1);

        //the service call and it's result
        DigitalObject digitalObject = extractor
                .migrate(new DigitalObject.Builder(Content.byValue(array)).build(), null, null, null)
                .getDigitalObject();
        byte[] results = IOUtils.toByteArray(digitalObject.getContent().getInputStream());
        String xcdl = new String(results, "UTF-8");

        if (xcdl == null) {
            throw new Exception("XCDL extraction failed - please check service logs for details");
        }

        return xcdl;

    } catch (MalformedURLException e) {
        e.printStackTrace();
        throw e;
    } catch (UnsupportedEncodingException e) {
        //xcel file was not UTF-8 encodable
        e.printStackTrace();
        throw e;
    } catch (PlanetsException e) {
        //error calling the web-service
        e.printStackTrace();
        throw e;
    }
}

From source file:javarestart.WebClassLoader.java

private URL findResourceImpl(final String name) {
    boolean handleWavSpecially = change4WavToHttp && name.endsWith(".wav");
    if (handleWavSpecially && initialBundle.containsKey(name)) {
        int dot = name.lastIndexOf(".");
        String resName;//from   w w w  .jav  a 2s  . co  m
        String ext;
        if (dot == -1) {
            resName = name;
            ext = "";
        } else {
            resName = name.substring(0, dot);
            ext = name.substring(dot + 1);
        }
        int slash = resName.lastIndexOf("/");
        if (slash != -1) {
            resName = resName.substring(slash + 1);
        }
        File f = Utils.fetchResourceToTempFile(resName, ext, new ByteArrayInputStream(initialBundle.get(name)));
        try {
            return f.toURI().toURL();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
    if (!potentiallyExists(name)) {
        return null;
    }
    try {
        return new URL(
                //see comment above for this hack explanation
                handleWavSpecially ? "http" : baseURL.getProtocol(), baseURL.getHost(), baseURL.getPort(),
                baseURL.getPath() + '/' + name);
    } catch (final MalformedURLException e) {
        return null;
    }
}

From source file:com.jiramot.foursquare.android.FSAPITest.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);//from ww w .  j  a v  a  2s.c om

    venue = (Button) findViewById(R.id.button);
    OnClickListener venues = new OnClickListener() {
        @Override
        public void onClick(View v) {
            String aa = null;
            try {
                aa = searchVenue();
                JSONObject obj = new JSONObject(aa);
                //               Log.i("fsapitest", obj.toString(2));
                JSONObject response = obj.getJSONObject("response");
                JSONArray groups = response.getJSONArray("groups");
                JSONObject element = groups.getJSONObject(0);
                JSONArray items = element.getJSONArray("items");

                File sdcardpath = Environment.getExternalStorageDirectory();
                File f = new File(sdcardpath, "test" + count + ".txt");
                FileOutputStream outStream = new FileOutputStream(f);
                ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(outStream));

                for (int i = 0; i < items.length(); i++) {
                    JSONObject item = items.getJSONObject(i);
                    Log.i("corso", "item " + i + " -- " + item.getString("id"));
                    Log.i("corso", "item " + i + " -- " + item.getString("name"));
                }

                //               out.writeObject(items.toString(2));

                out.flush();
                out.close();
                outStream.close();

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    };

    OnClickListener friends = new OnClickListener() {

        @Override
        public void onClick(View v) {
            venue.setText("friends");

            try {
                String result = foursquare.request("users/self/friends");
                JSONObject obj = new JSONObject(result);
                JSONObject response = obj.getJSONObject("response");
                JSONObject friends = response.getJSONObject("friends");
                JSONArray items = friends.getJSONArray("items");

                for (int i = 0; i < items.length(); i++) {
                    JSONObject item = items.getJSONObject(i);

                    Log.i("debug", item.getString("id") + " - " + item.getString("firstName") + " "
                            + item.getString("lastName"));
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    };

    venue.setOnClickListener(friends);

    init(getIntent());

    //         JSONObject response = obj.getJSONObject("response");
    //         JSONArray venues = response.getJSONArray("groups");

    //         File sdcardpath = Environment.getExternalStorageDirectory();
    //         File f = new File(sdcardpath,"test"+count+".txt");
    //         FileOutputStream outStream = new FileOutputStream(f);
    //         ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(outStream));

    //         out.writeObject(obj.toString(2));

    //         for (int i=0; i<venues.length(); i++) {
    //            JSONObject venue = venues.getJSONObject(i);

    //            out.writeObject(venue.toString(2));

    //            Log.i("corso", venue.getString("id"));
    //            Log.i("corso", venue.getString("name"));
    //         }

    //         out.flush();
    //         out.close();
    //         outStream.close();
    //
    //         count++;
    //         Log.i("fsapitest", "calls: "+count);
    //
}

From source file:de.appplant.cordova.plugin.notification.Asset.java

/**
 *Get Uri for HTTP Content//  w  w w  . ja  v a2 s  . c om
 * @param path HTTP adress
 * @return Uri of the downloaded file
 */
private Uri getUriForHTTP(String path) {
    try {
        URL url = new URL(path);
        String fileName = path.substring(path.lastIndexOf('/') + 1);
        String resName = fileName.substring(0, fileName.lastIndexOf('.'));
        String extension = path.substring(path.lastIndexOf('.'));
        File dir = activity.getExternalCacheDir();
        if (dir == null) {
            Log.e("Asset", "Missing external cache dir");
            return Uri.EMPTY;
        }
        String storage = dir.toString() + STORAGE_FOLDER;
        File file = new File(storage, resName + extension);
        new File(storage).mkdir();

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy);

        connection.setDoInput(true);
        connection.connect();

        InputStream input = connection.getInputStream();
        FileOutputStream outStream = new FileOutputStream(file);
        copyFile(input, outStream);
        outStream.flush();
        outStream.close();

        return Uri.fromFile(file);
    } catch (MalformedURLException e) {
        Log.e("Asset", "Incorrect URL");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        Log.e("Asset", "Failed to create new File from HTTP Content");
        e.printStackTrace();
    } catch (IOException e) {
        Log.e("Asset", "No Input can be created from http Stream");
        e.printStackTrace();
    }
    return Uri.EMPTY;
}

From source file:es.tekniker.framework.ktek.questionnaire.mng.server.OrionContextBrokerClient.java

public String queryContext(String codUser) {
    String strJSON = null;/*from  w  w w . j a v  a2 s.c  om*/
    HttpURLConnection conn = null;
    StringBuffer strBOutput = new StringBuffer();
    boolean boolOK = true;
    String input = null;
    StringBuffer stbInput = new StringBuffer();
    try {
        log.debug("queryContext Start ");

        conn = getOrionContextBrokerGEConnection(this.methodQueryContext, this.endpointOrionContextBroker,
                this.headerContentTypeJSON);

        stbInput.append("{\"entities\": [ {\"type\": \"" + this.typeContextValue
                + "\", \"isPattern\": \"false\", \"id\": \"" + codUser + "\"}]}");

        input = stbInput.toString();
        log.debug(input);

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();
        if (conn.getResponseCode() == 200) {
            log.debug("queryContext Response code " + conn.getResponseCode());
        } else if (conn.getResponseCode() != 201) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }
        log.debug("queryContext OutputStream wrote");

        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        log.debug("queryContext Waiting server response ");

        log.debug("queryContext Output from Server .... \n");
        String output;
        while ((output = br.readLine()) != null) {
            strBOutput.append(output);
            log.debug(output);
        }
        conn.disconnect();

        strJSON = strBOutput.toString();

        boolOK = true;
    } catch (MalformedURLException e) {
        log.error("queryContext MalformedURLException " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        log.error("queryContext IOException " + e.getMessage());
        e.printStackTrace();
    }
    return strJSON;
}