Ejemplo n.º 1
0
  public List parsePage(String pageCode) {
    List sections = new ArrayList();
    List folders = new ArrayList();
    List files = new ArrayList();
    int start = pageCode.indexOf("<div id=\"list-view\" class=\"view\"");
    int end = pageCode.indexOf("<div id=\"gallery-view\" class=\"view\"");
    String usefulSection = "";
    if (start != -1 && end != -1) {
      usefulSection = pageCode.substring(start, end);
    } else {
      debug("Could not parse page");
    }
    try {
      DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      InputSource is = new InputSource();
      is.setCharacterStream(new StringReader(usefulSection));
      Document doc = db.parse(is);

      NodeList divs = doc.getElementsByTagName("div");
      for (int i = 0; i < divs.getLength(); i++) {
        Element div = (Element) divs.item(i);
        boolean isFolder = false;
        if (div.getAttribute("class").equals("filename")) {
          NodeList imgs = div.getElementsByTagName("img");
          for (int j = 0; j < imgs.getLength(); j++) {
            Element img = (Element) imgs.item(j);
            if (img.getAttribute("class").indexOf("folder") > 0) {
              isFolder = true;
            } else {
              isFolder = false; // it's a file
            }
          }

          NodeList anchors = div.getElementsByTagName("a");
          Element anchor = (Element) anchors.item(0);
          String attr = anchor.getAttribute("href");
          String fileName = anchor.getAttribute("title");
          String fileURL;
          if (isFolder && !attr.equals("#")) {
            folders.add(attr);
            folders.add(fileName);
          } else if (!isFolder && !attr.equals("#")) {
            // Dropbox uses ajax to get the file for download, so the url isn't enough. We must be
            // sneaky here.
            fileURL = "https://dl.dropbox.com" + attr.substring(23) + "?dl=1";
            files.add(fileURL);
            files.add(fileName);
          }
        }
      }
    } catch (Exception e) {
      debug(e.toString());
    }

    sections.add(files);
    sections.add(folders);

    return sections;
  }
Ejemplo n.º 2
0
 public String getData(String url) {
   HttpClient client = new DefaultHttpClient();
   HttpGet get = new HttpGet(url);
   String response = "";
   try {
     ResponseHandler<String> responseHandler = new BasicResponseHandler();
     response = client.execute(get, responseHandler);
   } catch (Exception e) {
     debug(e.toString());
   }
   return response;
 }
Ejemplo n.º 3
0
  public void downloadFile(String url, String savePath, String fileName) {

    try {
      URL theURL = new URL(url);
      InputStream input = theURL.openStream();
      OutputStream output = new FileOutputStream(new File(savePath, fileName));
      try {
        byte[] buffer = new byte[1024];
        int bytesRead = 0;
        while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
          output.write(buffer, 0, bytesRead);
        }
      } catch (Exception e) {
        debug(e.toString());
      } finally {
        output.close();
      }
    } catch (Exception e) {
      debug(e.toString());
    }
  }
Ejemplo n.º 4
0
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.receiver);

    final Button cancelbtn = (Button) findViewById(R.id.ButtonCancel);
    // cancelbtn.setEnabled(false);
    cancelbtn.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            // streamtask.cancel(true);
            finish();
          }
        });

    try {
      Intent intent = getIntent();
      String action = intent.getAction();
      String type = intent.getType();

      if ((!(Intent.ACTION_SEND.equals(action))) || (type == null)) {
        throw new RuntimeException("Unknown intent action or type");
      }

      if (!("text/plain".equals(type))) {
        throw new RuntimeException("Type is not text/plain");
      }

      String extra = intent.getStringExtra(Intent.EXTRA_TEXT);
      if (extra == null) {
        throw new RuntimeException("Cannot get shared text");
      }

      final DownloadStreamTask streamtask = new DownloadStreamTask(this);

      //	Once created, a task is executed very simply:
      streamtask.execute(extra);

    } catch (Exception e) {
      Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
    }
  }
Ejemplo n.º 5
0
 public String getFolderName(String pageCode) {
   String usefulSection =
       pageCode.substring(
           pageCode.indexOf("<h3 id=\"breadcrumb\">"),
           pageCode.indexOf("<div id=\"list-view\" class=\"view\""));
   String folderName;
   try {
     DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
     InputSource is = new InputSource();
     is.setCharacterStream(new StringReader(usefulSection));
     Document doc = db.parse(is);
     NodeList divs = doc.getElementsByTagName("h3");
     for (int i = 0; i < divs.getLength(); i++) {
       Element div = (Element) divs.item(i);
       String a = div.getTextContent();
       folderName = a.substring(a.indexOf("/>") + 2).trim();
       return folderName;
     }
   } catch (Exception e) {
     debug(e.toString());
   }
   return "Error!";
 }
  /* Called when the activity is first created */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    try {

      super.onCreate(savedInstanceState);
      setContentView(R.layout.give_ride_content);
      /* Creating DBAdapter instance */
      gr_datasource = new DBAdapter(this);

      /* Get email ID from previous activity to maintain session */
      Bundle extras = getIntent().getExtras();
      if (extras != null) {
        str_usrid = extras.getString("usrid");
      }

      buttonSubmit = (Button) findViewById(R.id.btn_gr_submit);
      buttonCancel = (Button) findViewById(R.id.btn_gr_cancel);
      /* Get radius and cost */
      et_radius = (EditText) this.findViewById(R.id.txt_gr_radius);
      et_cost = (EditText) this.findViewById(R.id.txt_gr_cost);

      /* Adding PlacesAutoComplete adapter to the FROM autocomplete field */
      gr_frm_acView = (AutoCompleteTextView) findViewById(R.id.txt_gr_from);
      gr_frm_adapter = new PlacesAutoCompleteAdapter(this, R.layout.frm_item_list);
      gr_frm_acView.setAdapter(gr_frm_adapter);
      gr_frm_acView.setOnItemClickListener(this);

      /* Adding PlacesAutoComplete adapter to the TO autocomplete field */
      gr_to_acView = (AutoCompleteTextView) findViewById(R.id.txt_gr_to);
      gr_to_adapter = new PlacesAutoCompleteAdapter(this, R.layout.to_item_list);
      gr_to_acView.setAdapter(gr_to_adapter);
      gr_to_acView.setOnItemClickListener(this);

      /* Adding array adapter to spinner control for seats */
      sp_seats = (Spinner) findViewById(R.id.spn_gr_seats);
      ArrayAdapter<String> seats_adapter =
          new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, str_seats);
      sp_seats.setAdapter(seats_adapter);

      /* Prompt a dialog box upon Date button click */
      datePicker = (Button) findViewById(R.id.btn_gr_datepicker);
      datePicker.setText(dateFormatter.format(dateTime.getTime()));
      datePicker.setOnClickListener(
          new View.OnClickListener() {
            public void onClick(View v) {
              showDialog(DIALOG_DATE);
            }
          });

      /* Prompt a dialog box upon Time button click */
      timePicker = (Button) findViewById(R.id.btn_gr_timepicker);
      timePicker.setText(timeFormatter.format(dateTime.getTime()));
      timePicker.setOnClickListener(
          new View.OnClickListener() {

            public void onClick(View v) {
              showDialog(DIALOG_TIME);
            }
          });

      buttonSubmit.setOnClickListener(buttonSubmitOnClickListener);
      buttonCancel.setOnClickListener(buttonCancelOnClickListener);
      sp_seats.setOnItemSelectedListener(spinnerseatsOnItemSelectedListener);
    } catch (Exception e) {
      Log.e("Places AutoComplete Activity OnCreate:", e.toString());
    }
  }
        @Override
        public void onClick(View arg0) {
          try {
            /* Open Database */
            gr_datasource.open();
            /* Get from and to address from autocomplete fields */
            gr_frm_addr = gr_frm_acView.getText().toString();
            gr_to_addr = gr_to_acView.getText().toString();

            flag = 0;
            /* Checking if FROM and TO address is empty */
            if (gr_frm_addr.length() == 0) {
              gr_frm_acView.setError("Enter from address");
              flag = 1;
            } else if (gr_to_addr.length() == 0) {
              gr_to_acView.setError("Enter to address");
              flag = 1;
            }
            /* Radius validation */
            String str_radius = et_radius.getText().toString();
            if (str_radius.length() == 0) {
              et_radius.setError("Enter valid radius");
              flag = 1;
            } else {
              rad_value = Integer.valueOf(et_radius.getText().toString());
              if (rad_value < 0 || rad_value > 20) {
                et_radius.setError("Limit 20 miles");
                flag = 1;
              }
            }
            /* Cost Validation */
            String str_cost = et_cost.getText().toString();
            if (str_cost.length() == 0) {
              et_cost.setError("Enter valid cost");
              flag = 1;
            } else {
              cost_value = Float.valueOf(et_cost.getText().toString());
              if (cost_value < 0 || cost_value > 1000) {
                et_cost.setError("Limit 1000 dollars");
                flag = 1;
              }
            }

            if (flag == 0) {
              /* Function call to calculate lattitudes and longitudes for FROM address */
              jsonObject_main_frm = getLocationInfo(gr_frm_addr);
              frm_lattitude = getLattitude(jsonObject_main_frm);
              frm_longitude = getLongitude(jsonObject_main_frm);

              /* Function call to calculate lattitudes and longitudes for TO address */
              jsonObject_main_to = getLocationInfo(gr_to_addr);
              to_lattitude = getLattitude(jsonObject_main_to);
              to_longitude = getLongitude(jsonObject_main_to);

              str_date = datePicker.getText().toString();
              /* Convert time to milliseconds */
              time = dateTime.getTimeInMillis();
              /* Insert into RIDEDETAILS table */
              long id;
              id =
                  gr_datasource.insertridedetails(
                      str_usrid,
                      gr_frm_addr,
                      gr_to_addr,
                      rad_value,
                      str_date,
                      time,
                      selected_seat,
                      cost_value,
                      frm_lattitude,
                      frm_longitude,
                      to_lattitude,
                      to_longitude);
              /* Close database object */
              gr_datasource.close();

              /* On inserting Ride Details redirect to choose ride screen or exit */
              AlertDialog.Builder alertDialogBuilder =
                  new AlertDialog.Builder(PlacesAutoCompleteActivity.this);
              alertDialogBuilder.setTitle("Ride 'n Divide");
              alertDialogBuilder
                  .setMessage("Thank you, for giving a ride! Do you want to check other rides?")
                  .setCancelable(false)
                  .setPositiveButton(
                      "Check Rides",
                      new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                          Intent reselect =
                              new Intent(PlacesAutoCompleteActivity.this, ChooseRideActivity.class);
                          reselect.putExtra("usrid", str_usrid);
                          startActivity(reselect);
                        }
                      })
                  .setNegativeButton(
                      "Exit",
                      new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                          dialog.cancel();
                          PlacesAutoCompleteActivity.this.finish();
                        }
                      });

              AlertDialog alertDialog = alertDialogBuilder.create();
              alertDialog.show();
            }

          } catch (Exception e) {
            Log.e("Places AutoComplete Activity buttonsubmit:", e.toString());
          }
        }
Ejemplo n.º 8
-52
    @Override
    protected String[] doInBackground(String... parms) {
      String[] resultarr = new String[1];
      String intentstr = parms[0];

      // int count = urls.length;
      // long totalSize = 0; for (int i = 0; i < count; i++) { totalSize +=
      // Downloader.downloadFile(urls[i]);
      // publishProgress((int) ((i / (float) count) * 100));
      // Escape early if cancel() is called
      // if (isCancelled())
      //		break;

      try {
        // Connect to API and authenticate
        publishProgress("Connecting and authenticating API session...");

        ApiWrapper wrapper;
        // wrapper = Api.wrapper;
        wrapper = new ApiWrapper(Api.mClientID, Api.mClientSecret, null, null);
        wrapper.login("un1tz3r0", "Farscap3");

        publishProgress("Resolving url...");

        String resolvedurl = resolveURL(wrapper, intentstr);

        publishProgress("Getting metadata...");

        HttpResponse resp = wrapper.get(Request.to(resolvedurl));

        JSONObject jso = Http.getJSON(resp);
        // resultstr = jso.toString();

        if (jso.getString("kind").equals("track")) {
          if (jso.getBoolean("downloadable")) {
            publishProgress("Getting download redirect URL...");

            String dlrurl =
                wrapper
                    .getURI(
                        Request.to(jso.getString("download_url")).add("allow_redirect", false),
                        false,
                        false)
                    .toString();
            HttpResponse dlrresp = wrapper.get(Request.to(dlrurl));
            String dlstr = dlrurl;
            if (dlrresp.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
              Header dlloch = dlrresp.getFirstHeader("location");
              if ((dlloch == null) || (dlloch.getValue() == null))
                throw new RuntimeException("Download url HEAD response has no location header");

              dlstr = wrapper.getURI(Request.to(dlloch.getValue()), false, false).toString();
            } else if (dlrresp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
              dlstr = dlrurl;
            } else {
              throw new RuntimeException(
                  "Download url HEAD response has wrong status ("
                      + String.valueOf(dlrresp.getStatusLine().getStatusCode())
                      + " "
                      + dlrresp.getStatusLine().getReasonPhrase()
                      + ")");
            }
            // String dlstr = Request.to( dlloch.getValue() ).add("CLIENT_ID",
            // Api.mClientID).toString();

            //												if(dlresp2.getStatusLine().getStatusCode() !=
            // HttpStatus.SC_MOVED_TEMPORARILY)
            //														throw new RuntimeException("Download redirect url HEAD response has
            // wrong status: " + dlresp2.getStatusLine().toString());
            //												Header dlloc2 = dlresp2.getFirstHeader("location");
            //												if((dlloc2 == null) || (dlloc2.getValue() == null))
            //														throw new RuntimeException("Download redirect url HEAD response has no
            // location header");
            //

            resultarr = new String[2];
            resultarr[1] =
                jso.getString("title").replaceAll("[^A-Za-z0-9 -]*", "")
                    + "."
                    + jso.getString("original_format");
            resultarr[0] = dlstr;
          } else {
            Stream st = wrapper.resolveStreamUrl(jso.getString("stream_url"), true);
            resultarr = new String[2];
            resultarr[1] = jso.getString("title").replaceAll("[^A-Za-z0-9 -]*", "").concat(".mp3");
            resultarr[0] = st.streamUrl;
          }
        }
      } catch (JSONException e) {
        resultarr = new String[1];
        resultarr[0] = e.toString();
      } catch (IOException e) {
        resultarr = new String[1];
        resultarr[0] = e.toString();
      } catch (Exception e) {
        resultarr = new String[1];
        resultarr[0] = e.toString();
      }

      return resultarr;
    }