Example usage for org.jsoup.nodes Document getElementById

List of usage examples for org.jsoup.nodes Document getElementById

Introduction

In this page you can find the example usage for org.jsoup.nodes Document getElementById.

Prototype

public Element getElementById(String id) 

Source Link

Document

Find an element by ID, including or under this element.

Usage

From source file:eu.masconsult.bgbanking.banks.dskbank.DskClient.java

@Override
public List<RawBankAccount> getBankAccounts(String authToken)
        throws IOException, ParseException, AuthenticationException {
    String uri = BASE_URL + "?" + URLEncodedUtils.format(
            Arrays.asList(new BasicNameValuePair(XML_ID, LIST_ACCOUNTS_XML_ID)), ENCODING) + "&" + authToken;

    // Get the accounts list
    Log.i(TAG, "Getting from: " + uri);
    final HttpGet get = new HttpGet(uri);
    get.setHeader("Accept", "*/*");

    DefaultHttpClient httpClient = getHttpClient();

    Log.v(TAG, "sending " + get.toString());
    final HttpResponse resp = httpClient.execute(get);

    if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new ParseException("getBankAccounts: unhandled http status "
                + resp.getStatusLine().getStatusCode() + " " + resp.getStatusLine().getReasonPhrase());
    }//from  w w  w . j a  va2  s . co m

    HttpEntity entity = resp.getEntity();
    Document doc = Jsoup.parse(entity.getContent(), "utf-8", BASE_URL);

    if (!checkLoggedIn(doc)) {
        throw new AuthenticationException("session expired!");
    }

    Element content = doc.getElementById("PageContent");
    if (content == null) {
        throw new ParseException("getBankAccounts: can't find PageContent");
    }

    Elements tables = content.getElementsByTag("table");
    if (tables == null || tables.size() == 0) {
        throw new ParseException("getBankAccounts: can't find table in PageContent");
    }

    Elements rows = tables.first().getElementsByTag("tr");
    if (rows == null || rows.size() == 0) {
        throw new ParseException("getBankAccounts: first table is empty in PageContent");
    }

    ArrayList<RawBankAccount> bankAccounts = new ArrayList<RawBankAccount>(rows.size());

    String lastCurrency = null;
    for (Element row : rows) {
        RawBankAccount bankAccount = obtainBankAccountFromHtmlTableRow(row);
        if (bankAccount != null) {
            if (bankAccount.getCurrency() == null) {
                bankAccount.setCurrency(lastCurrency);
            } else {
                lastCurrency = bankAccount.getCurrency();
            }
            bankAccounts.add(bankAccount);
        }
    }

    return bankAccounts;
}

From source file:prince.app.ccm.tools.Task.java

public String getFormParams(String html, String username, String password) throws UnsupportedEncodingException {

    System.out.println("Extracting form's data...");

    Document doc = Jsoup.parse(html);

    // Google form id
    Element loginform = doc.getElementById("contenido_right");
    Elements loginaction = doc.getElementsByTag("form");
    Element form = loginaction.first();
    log = MAIN_PAGE + form.attr("action");
    Log.e(TAG, "Action: " + log);
    Elements inputElements = loginform.getElementsByTag("input");
    List<String> paramList = new ArrayList<String>();
    for (Element inputElement : inputElements) {
        String key = inputElement.attr("name");
        String value = inputElement.attr("value");

        if (key.equals("usuario")) {
            value = username;//from   w ww .j  a va  2 s  .  c om
            paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
        } else if (key.equals("contrasena")) {
            value = password;
            paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
        }
    }

    // build parameters list
    StringBuilder result = new StringBuilder();
    for (String param : paramList) {
        if (result.length() == 0) {
            result.append(param);
        } else {
            result.append("&" + param);
        }
    }

    Log.d(TAG, "Done in getFormParams: " + result.toString());
    return result.toString();
}

From source file:jobhunter.cb.Client.java

public Job execute() throws IOException, URISyntaxException {
    l.debug("Connecting to {}", url);

    update("Connecting", 1L);
    final Document doc = Jsoup.connect(url).get();

    update("Parsing HTML", 2L);
    final Job job = Job.of();
    job.setPortal(CareerBuilderPlugin.portal);
    job.setLink(url);/*  www  .  j av a2s . c o m*/

    URLEncodedUtils.parse(new URI(url), "UTF-8").stream()
            .filter(nvp -> nvp.getName().equalsIgnoreCase("job_did")).findFirst()
            .ifPresent(param -> job.setExtId(param.getValue()));

    job.setPosition(doc.getElementById("job-title").text());
    job.setAddress(doc.getElementById("CBBody_Location").text());

    job.getCompany().setName(doc.getElementById("CBBody_CompanyName").text());

    StringBuilder description = new StringBuilder();

    description.append(StringEscapeUtils.unescapeHtml4(doc.getElementById("pnlJobDescription").html()));

    Element div = doc.getElementById("job-requirements");

    description.append(StringEscapeUtils.unescapeHtml4(div.getElementsByClass("section-body").html()));

    div = doc.getElementById("job-snapshot-section");

    description.append(StringEscapeUtils.unescapeHtml4(div.getElementsByClass("section-body").html()));

    job.setDescription(description.toString());
    update("Done", 3L);
    return job;
}

From source file:tkbautobooking.BookingSystem.java

private void praseBookingPage() throws Exception {

    Document doc = Jsoup.parse(BookingPageHTML);
    Element class_selector = doc.getElementById("class_selector");

    if (class_selector == null)
        throw new Exception("Prase Booking Page fail !");

    classMap = new TreeMap<>();
    for (Element option : class_selector.getElementsByTag("option")) {
        if (option.attr("value").equals(""))
            continue;

        classMap.put(option.attr("value"), option.text().replace("", " "));
    }//from   w ww  .ja  v a  2 s. c om
}

From source file:net.GoTicketing.GoTicketing.java

/**
 * ??/*from   w ww . j a  va  2s  .com*/
 * @throws Exception 
 */
private void praseImageCaptchaSrc() throws Exception {
    Document doc = Jsoup.parse(TicketingPageHTML);
    Element img = doc.getElementById("idRandomPic");
    if (img == null)
        throw new Exception("Can't get image captcha source !");

    //out.println(host + img.attr("src"));
    ImageCaptchaSrc = host + img.attr("src");
}

From source file:info.mikaelsvensson.devtools.sitesearch.SiteSearchPlugin.java

private IndexEntry createIndexEntry(final File file) {
    try {//from ww  w .j a v a  2s  . com
        Document document = Jsoup.parse(file, "UTF-8", "http://invalid.host");
        Element contentEl = document.getElementById("contentBox");
        if (contentEl == null) {
            contentEl = document.body();
        }
        if (contentEl != null) {
            String text = Jsoup.clean(contentEl.html(), Whitelist.simpleText());
            Collection<WordCount> wordCount = getWordCount(text);
            Collection<WordCount> filteredWordCount = filterWordCount(wordCount);
            return new IndexEntry(document.title(), getRelativePath(getSiteOutputFolder(), file),
                    filteredWordCount);
        }
    } catch (IOException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
    return null;
}

From source file:jobhunter.infoempleo.Client.java

public Job execute() throws IOException, URISyntaxException {
    l.debug("Connecting to {}", url);

    update("Connecting", 1L);
    final Document doc = Jsoup.connect(url).get();

    update("Parsing HTML", 2L);
    final Job job = Job.of();

    job.setPortal(InfoEmpleoWebPlugin.portal);
    job.setLink(url);//  w w  w.  ja  v  a  2  s  . c  om
    job.setExtId("");

    final StringBuilder description = new StringBuilder();

    doc.getElementsByClass("linea").forEach(td -> {
        td.getElementsByTag("p").forEach(p -> {
            description.append(StringEscapeUtils.unescapeHtml4(p.html())).append(System.lineSeparator());
        });
    });

    job.setDescription(description.toString());

    job.setPosition(doc.getElementById("ctl00_CPH_Body_Link_Subtitulo").attr("title"));

    job.getCompany().setName(getCompany(doc));

    final String href = doc.getElementById("ctl00_CPH_Body_lnkEnviarAmigoI").attr("href");

    final String extId = URLEncodedUtils.parse(new URI(href), "UTF-8").stream()
            .filter(nvp -> nvp.getName().equalsIgnoreCase("Id_Oferta")).findFirst().get().getValue();

    job.setExtId(extId);

    update("Done", 3L);
    return job;
}

From source file:biz.shadowservices.DegreesToolbox.DataFetcher.java

public FetchResult updateData(Context context, boolean force) {
    //Open database
    DBOpenHelper dbhelper = new DBOpenHelper(context);
    SQLiteDatabase db = dbhelper.getWritableDatabase();

    // check for internet connectivity
    try {//  w  w w.j a v  a2 s .c  om
        if (!isOnline(context)) {
            Log.d(TAG, "We do not seem to be online. Skipping Update.");
            return FetchResult.NOTONLINE;
        }
    } catch (Exception e) {
        exceptionReporter.reportException(Thread.currentThread(), e, "Exception during isOnline()");
    }
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    if (!force) {
        try {
            if (sp.getBoolean("loginFailed", false) == true) {
                Log.d(TAG, "Previous login failed. Skipping Update.");
                DBLog.insertMessage(context, "i", TAG, "Previous login failed. Skipping Update.");
                return FetchResult.LOGINFAILED;
            }
            if (sp.getBoolean("autoupdates", true) == false) {
                Log.d(TAG, "Automatic updates not enabled. Skipping Update.");
                DBLog.insertMessage(context, "i", TAG, "Automatic updates not enabled. Skipping Update.");
                return FetchResult.NOTALLOWED;
            }
            if (!isBackgroundDataEnabled(context) && sp.getBoolean("obeyBackgroundData", true)) {
                Log.d(TAG, "Background data not enabled. Skipping Update.");
                DBLog.insertMessage(context, "i", TAG, "Background data not enabled. Skipping Update.");
                return FetchResult.NOTALLOWED;
            }
            if (!isAutoSyncEnabled() && sp.getBoolean("obeyAutoSync", true)
                    && sp.getBoolean("obeyBackgroundData", true)) {
                Log.d(TAG, "Auto sync not enabled. Skipping Update.");
                DBLog.insertMessage(context, "i", TAG, "Auto sync not enabled. Skipping Update.");
                return FetchResult.NOTALLOWED;
            }
            if (isWifi(context) && !sp.getBoolean("wifiUpdates", true)) {
                Log.d(TAG, "On wifi, and wifi auto updates not allowed. Skipping Update");
                DBLog.insertMessage(context, "i", TAG,
                        "On wifi, and wifi auto updates not allowed. Skipping Update");
                return FetchResult.NOTALLOWED;
            } else if (!isWifi(context)) {
                Log.d(TAG, "We are not on wifi.");
                if (!isRoaming(context) && !sp.getBoolean("2DData", true)) {
                    Log.d(TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update.");
                    DBLog.insertMessage(context, "i", TAG,
                            "Automatic updates on 2Degrees data not enabled. Skipping Update.");
                    return FetchResult.NOTALLOWED;
                } else if (isRoaming(context) && !sp.getBoolean("roamingData", false)) {
                    Log.d(TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update.");
                    DBLog.insertMessage(context, "i", TAG,
                            "Automatic updates on roaming mobile data not enabled. Skipping Update.");
                    return FetchResult.NOTALLOWED;
                }

            }
        } catch (Exception e) {
            exceptionReporter.reportException(Thread.currentThread(), e,
                    "Exception while finding if to update.");
        }

    } else {
        Log.d(TAG, "Update Forced");
    }

    try {
        String username = sp.getString("username", null);
        String password = sp.getString("password", null);
        if (username == null || password == null) {
            DBLog.insertMessage(context, "i", TAG, "Username or password not set.");
            return FetchResult.USERNAMEPASSWORDNOTSET;
        }

        // Find the URL of the page to send login data to.
        Log.d(TAG, "Finding Action. ");
        HttpGetter loginPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/web/ip/login");
        String loginPageString = loginPageGet.execute();
        if (loginPageString != null) {
            Document loginPage = Jsoup.parse(loginPageString,
                    "https://secure.2degreesmobile.co.nz/web/ip/login");
            Element loginForm = loginPage.getElementsByAttributeValue("name", "loginFrm").first();
            String loginAction = loginForm.attr("action");
            // Send login form
            List<NameValuePair> loginValues = new ArrayList<NameValuePair>();
            loginValues.add(new BasicNameValuePair("externalURLRedirect", ""));
            loginValues.add(new BasicNameValuePair("hdnAction", "login_userlogin"));
            loginValues.add(new BasicNameValuePair("hdnAuthenticationType", "M"));
            loginValues.add(new BasicNameValuePair("hdnlocale", ""));

            loginValues.add(new BasicNameValuePair("userid", username));
            loginValues.add(new BasicNameValuePair("password", password));
            Log.d(TAG, "Sending Login ");
            HttpPoster sendLoginPoster = new HttpPoster(loginAction, loginValues);
            // Parse result

            String loginResponse = sendLoginPoster.execute();
            Document loginResponseParsed = Jsoup.parse(loginResponse);
            // Determine if this is a pre-pay or post-paid account.
            boolean postPaid;
            if (loginResponseParsed
                    .getElementById("p_CustomerPortalPostPaidHomePage_WAR_customerportalhomepage") == null) {
                Log.d(TAG, "Pre-pay account or no account.");
                postPaid = false;
            } else {
                Log.d(TAG, "Post-paid account.");
                postPaid = true;
            }

            String homepageUrl = "https://secure.2degreesmobile.co.nz/group/ip/home";
            if (postPaid) {
                homepageUrl = "https://secure.2degreesmobile.co.nz/group/ip/postpaid";
            }
            HttpGetter homepageGetter = new HttpGetter(homepageUrl);
            String homepageHTML = homepageGetter.execute();
            Document homePage = Jsoup.parse(homepageHTML);

            Element accountSummary = homePage.getElementById("accountSummary");
            if (accountSummary == null) {
                Log.d(TAG, "Login failed.");
                return FetchResult.LOGINFAILED;
            }
            db.delete("cache", "", null);
            /* This code fetched some extra details for postpaid users, but on reflection they aren't that useful.
             * Might reconsider this.
             *
             if (postPaid) {
                     
               Element accountBalanceSummaryTable = accountSummary.getElementsByClass("tableBillSummary").first();
               Elements rows = accountBalanceSummaryTable.getElementsByTag("tr");
               int rowno = 0;
               for (Element row : rows) {
                  if (rowno > 1) {
             break;
                  }
                  //Log.d(TAG, "Starting row");
                  //Log.d(TAG, row.html());
                  Double value;
                  try {
             Element amount = row.getElementsByClass("tableBillamount").first();
             String amountHTML = amount.html();
             Log.d(TAG, amountHTML.substring(1));
             value = Double.parseDouble(amountHTML.substring(1));
                  } catch (Exception e) {
             Log.d(TAG, "Failed to parse amount from row.");
             value = null;
                  }
                  String expiresDetails = "";
                  String expiresDate = null;
                  String name = null;
                  try {
             Element details = row.getElementsByClass("tableBilldetail").first();
             name = details.ownText();
             Element expires = details.getElementsByTag("em").first();
             if (expires != null) {
                 expiresDetails = expires.text();
             } 
             Log.d(TAG, expiresDetails);
             Pattern pattern;
             pattern = Pattern.compile("\\(payment is due (.*)\\)");
             Matcher matcher = pattern.matcher(expiresDetails);
             if (matcher.find()) {
                /*Log.d(TAG, "matched expires");
                Log.d(TAG, "group 0:" + matcher.group(0));
                Log.d(TAG, "group 1:" + matcher.group(1));
                Log.d(TAG, "group 2:" + matcher.group(2)); *
                String expiresDateString = matcher.group(1);
                Date expiresDateObj;
                if (expiresDateString != null) {
                   if (expiresDateString.length() > 0) {
                      try {
                         expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString);
                         expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj);
                      } catch (java.text.ParseException e) {
                         Log.d(TAG, "Could not parse date: " + expiresDateString);
                      }
                   }   
                }
             }
                  } catch (Exception e) {
             Log.d(TAG, "Failed to parse details from row.");
                  }
                  String expirev = null;
                  ContentValues values = new ContentValues();
                  values.put("name", name);
                  values.put("value", value);
                  values.put("units", "$NZ");
                  values.put("expires_value", expirev );
                  values.put("expires_date", expiresDate);
                  db.insert("cache", "value", values );
                  rowno++;
               }
            } */
            Element accountSummaryTable = accountSummary.getElementsByClass("tableAccountSummary").first();
            Elements rows = accountSummaryTable.getElementsByTag("tr");
            for (Element row : rows) {
                // We are now looking at each of the rows in the data table.
                //Log.d(TAG, "Starting row");
                //Log.d(TAG, row.html());
                Double value;
                String units;
                try {
                    Element amount = row.getElementsByClass("tableBillamount").first();
                    String amountHTML = amount.html();
                    //Log.d(TAG, amountHTML);
                    String[] amountParts = amountHTML.split("&nbsp;", 2);
                    //Log.d(TAG, amountParts[0]);
                    //Log.d(TAG, amountParts[1]);
                    if (amountParts[0].contains("Included") || amountParts[0].equals("All You Need")
                            || amountParts[0].equals("Unlimited Text*")) {
                        value = Values.INCLUDED;
                    } else {
                        try {
                            value = Double.parseDouble(amountParts[0]);
                        } catch (NumberFormatException e) {
                            exceptionReporter.reportException(Thread.currentThread(), e, "Decoding value.");
                            value = 0.0;
                        }
                    }
                    units = amountParts[1];
                } catch (NullPointerException e) {
                    //Log.d(TAG, "Failed to parse amount from row.");
                    value = null;
                    units = null;
                }
                Element details = row.getElementsByClass("tableBilldetail").first();
                String name = details.getElementsByTag("strong").first().text();
                Element expires = details.getElementsByTag("em").first();
                String expiresDetails = "";
                if (expires != null) {
                    expiresDetails = expires.text();
                }
                Log.d(TAG, expiresDetails);
                Pattern pattern;
                if (postPaid == false) {
                    pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?expiring on (.*)\\)");
                } else {
                    pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?will expire on (.*)\\)");
                }
                Matcher matcher = pattern.matcher(expiresDetails);
                Double expiresValue = null;
                String expiresDate = null;
                if (matcher.find()) {
                    /*Log.d(TAG, "matched expires");
                    Log.d(TAG, "group 0:" + matcher.group(0));
                    Log.d(TAG, "group 1:" + matcher.group(1));
                    Log.d(TAG, "group 2:" + matcher.group(2)); */
                    try {
                        expiresValue = Double.parseDouble(matcher.group(1));
                    } catch (NumberFormatException e) {
                        expiresValue = null;
                    }
                    String expiresDateString = matcher.group(2);
                    Date expiresDateObj;
                    if (expiresDateString != null) {
                        if (expiresDateString.length() > 0) {
                            try {
                                expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString);
                                expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj);
                            } catch (java.text.ParseException e) {
                                Log.d(TAG, "Could not parse date: " + expiresDateString);
                            }
                        }
                    }
                }
                ContentValues values = new ContentValues();
                values.put("name", name);
                values.put("value", value);
                values.put("units", units);
                values.put("expires_value", expiresValue);
                values.put("expires_date", expiresDate);
                db.insert("cache", "value", values);
            }

            if (postPaid == false) {
                Log.d(TAG, "Getting Value packs...");
                // Find value packs
                HttpGetter valuePacksPageGet = new HttpGetter(
                        "https://secure.2degreesmobile.co.nz/group/ip/prevaluepack");
                String valuePacksPageString = valuePacksPageGet.execute();
                //DBLog.insertMessage(context, "d", "",  valuePacksPageString);
                if (valuePacksPageString != null) {
                    Document valuePacksPage = Jsoup.parse(valuePacksPageString);
                    Elements enabledPacks = valuePacksPage.getElementsByClass("yellow");
                    for (Element enabledPack : enabledPacks) {
                        Element offerNameElemt = enabledPack
                                .getElementsByAttributeValueStarting("name", "offername").first();
                        if (offerNameElemt != null) {
                            String offerName = offerNameElemt.val();
                            DBLog.insertMessage(context, "d", "", "Got element: " + offerName);
                            ValuePack[] packs = Values.valuePacks.get(offerName);
                            if (packs == null) {
                                DBLog.insertMessage(context, "d", "",
                                        "Offer name: " + offerName + " not matched.");
                            } else {
                                for (ValuePack pack : packs) {
                                    ContentValues values = new ContentValues();
                                    values.put("plan_startamount", pack.value);
                                    values.put("plan_name", offerName);
                                    DBLog.insertMessage(context, "d", "",
                                            "Pack " + pack.type.id + " start value set to " + pack.value);
                                    db.update("cache", values, "name = '" + pack.type.id + "'", null);
                                }
                            }
                        }
                    }
                }
            }

            SharedPreferences.Editor prefedit = sp.edit();
            Date now = new Date();
            prefedit.putString("updateDate", DateFormatters.ISO8601FORMAT.format(now));
            prefedit.putBoolean("loginFailed", false);
            prefedit.putBoolean("networkError", false);
            prefedit.commit();
            DBLog.insertMessage(context, "i", TAG, "Update Successful");
            return FetchResult.SUCCESS;

        }
    } catch (ClientProtocolException e) {
        DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage());
        return FetchResult.NETWORKERROR;
    } catch (IOException e) {
        DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage());
        return FetchResult.NETWORKERROR;
    } finally {
        db.close();
    }
    return null;
}

From source file:com.liato.bankdroid.banking.banks.coop.Coop.java

@Override
public void update() throws BankException, LoginException, BankChoiceException {
    super.update();
    if (username == null || password == null || username.length() == 0 || password.length() == 0) {
        throw new LoginException(res.getText(R.string.invalid_username_password).toString());
    }//w w  w . j ava  2  s. com

    login();

    try {
        for (AccountType at : AccountType.values()) {
            response = urlopen.open(at.getUrl());
            Document d = Jsoup.parse(response);
            Elements historik = d.select("#historik section");
            TransactionParams params = new TransactionParams();
            mTransactionParams.put(at, params);
            if (historik != null && !historik.isEmpty()) {
                String data = historik.first().attr("data-controller");
                Matcher m = rePageGuid.matcher(data);
                if (m.find()) {
                    params.setPageGuid(m.group(1));
                }
            }
            Element date = d.getElementById("dateFrom");
            if (date != null) {
                params.setMinDate(date.hasAttr("min") ? date.attr("min") : null);
                params.setMaxDate(date.hasAttr("max") ? date.attr("max") : null);
            }
            Elements es = d.select(".List:contains(Saldo)");
            if (es != null && !es.isEmpty()) {
                List<String> names = new ArrayList<String>();
                List<String> values = new ArrayList<String>();
                for (Element e : es.first().select("dt")) {
                    names.add(e.text().replaceAll(":", "").trim());
                }
                for (Element e : es.first().select("dd")) {
                    values.add(e.text().trim());
                }
                for (int i = 0; i < Math.min(names.size(), values.size()); i++) {
                    Account a = new Account(names.get(i), Helpers.parseBalance(values.get(i)),
                            String.format("%s%d", at.getPrefix(), i));
                    a.setCurrency(Helpers.parseCurrency(values.get(i), "SEK"));
                    if (a.getName().toLowerCase().contains("disponibelt")) {
                        a.setType(Account.REGULAR);
                        balance = a.getBalance();
                        setCurrency(a.getCurrency());
                    } else {
                        a.setType(Account.OTHER);
                    }

                    if (i > 0) {
                        a.setAliasfor(String.format("%s%d", at.getPrefix(), 0));
                    }
                    accounts.add(a);
                }
            }
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new BankException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new BankException(e.getMessage());
    }

    try {
        RefundSummaryRequest refsumReq = new RefundSummaryRequest(mUserId, mToken, APPLICATION_ID);
        HttpEntity e = new StringEntity(getObjectmapper().writeValueAsString(refsumReq));
        InputStream is = urlopen
                .openStream("https://www.coop.se/ExternalServices/RefundService.svc/RefundSummary", e, true);
        RefundSummaryResponse refsumResp = readJsonValue(is, RefundSummaryResponse.class);
        if (refsumResp != null && refsumResp.getRefundSummaryResult() != null) {
            Account a = new Account("terbring p ditt kort",
                    BigDecimal.valueOf(refsumResp.getRefundSummaryResult().getAccountBalance()), "refsummary");
            a.setCurrency("SEK");
            if (accounts.isEmpty()) {
                balance = a.getBalance();
                setCurrency(a.getCurrency());
            }
            accounts.add(a);
            a = new Account(
                    String.format("terbring fr %s", refsumResp.getRefundSummaryResult().getMonthName()),
                    BigDecimal.valueOf(refsumResp.getRefundSummaryResult().getTotalRefund()),
                    "refsummary_month");
            accounts.add(a);
        }
    } catch (JsonParseException e) {
        e.printStackTrace();
        throw new BankException(e.getMessage());
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new BankException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new BankException(e.getMessage());
    }

    if (accounts.isEmpty()) {
        throw new BankException(res.getText(R.string.no_accounts_found).toString());
    }
    super.updateComplete();
}

From source file:faescapeplan.FAEscapePlanUI.java

private void loginButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_loginButtonMouseClicked
    if (!userData.getLoginState()) {
        if (this.loginUser.getText().trim().isEmpty()
                || String.valueOf(this.loginPass.getPassword()).trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Fields cannot be empty.");
        } else {//w  ww. j a  v a 2s  .  c  om
            try {
                updateTextLog("Logging in...");
                this.loginButton.setEnabled(false);
                this.loginUser.setEditable(false);
                this.loginPass.setEditable(false);

                Map<String, String> sessionCookies = Jsoup.connect("http://www.furaffinity.net")
                        .userAgent(USER_AGENT).execute().cookies();

                Response loginResponse = Jsoup.connect("https://www.furaffinity.net/login/")
                        .userAgent(USER_AGENT).data("action", "login").data("name", this.loginUser.getText())
                        .data("pass", String.valueOf(this.loginPass.getPassword()))
                        .data("login", "Login+to FurAffinity").cookies(sessionCookies)
                        .referrer("http://www.furaffinity.net/login/").timeout(10000)
                        .method(Connection.Method.POST).execute();
                Document doc = loginResponse.parse();

                if (!doc.getElementById("my-username").text()
                        .equalsIgnoreCase("~" + this.loginUser.getText())) {
                    JOptionPane.showMessageDialog(this, "Login failed, check your username and password");
                } else {
                    userData.setName(this.loginUser.getText());
                    sessionCookies.putAll(loginResponse.cookies());
                    userData.setCookies(sessionCookies);
                    this.loginPass.setText("000000000000");
                    userData.setLoginState(true);
                    getProfileImg();
                    unlockForm();
                    updateTextLog("Successfully logged in");
                }
            } catch (IOException ex) {
                Logger.getLogger(FAEscapePlanUI.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println("Could not connect to FA");
                this.loginUser.setEditable(true);
                this.loginPass.setEditable(true);
            } finally {
                this.loginButton.setEnabled(true);
            }
        }
    } else {
        loginDisconnect();
        resetForm();
    }
}