Example usage for org.jsoup.nodes Element attr

List of usage examples for org.jsoup.nodes Element attr

Introduction

In this page you can find the example usage for org.jsoup.nodes Element attr.

Prototype

public String attr(String attributeKey) 

Source Link

Document

Get an attribute's value by its key.

Usage

From source file:de.geeksfactory.opacclient.apis.Open.java

@Override
public List<SearchField> getSearchFields() throws IOException, OpacErrorException, JSONException {
    String url = opac_url + "/" + data.getJSONObject("urls").getString("advanced_search") + NO_MOBILE;
    Document doc = Jsoup.parse(httpGet(url, getDefaultEncoding()));

    Element table = doc.select(".ModOPENExtendedSearchModuleC table").first();

    List<SearchField> fields = new ArrayList<>();

    JSONObject selectable = new JSONObject();
    selectable.put("selectable", true);

    JSONObject notSelectable = new JSONObject();
    notSelectable.put("selectable", false);

    // Selectable search criteria
    Elements options = table.select("select[id$=FirstSearchField] option");
    for (Element option : options) {
        TextSearchField field = new TextSearchField();
        field.setId(option.val());
        field.setDisplayName(option.text());
        field.setData(selectable);/*from  www .  j  a  va 2 s. c  om*/
        fields.add(field);
    }

    // More criteria
    Element moreHeader = table.select("span[id$=LblMoreCriterias]").parents().select("tr").first();
    if (moreHeader != null) {
        Elements siblings = moreHeader.siblingElements();
        int startIndex = moreHeader.elementSiblingIndex();
        for (int i = startIndex; i < siblings.size(); i++) {
            Element tr = siblings.get(i);
            if (tr.select("input, select").size() == 0)
                continue;

            if (tr.select("input[type=text]").size() == 1) {
                Element input = tr.select("input[type=text]").first();
                TextSearchField field = new TextSearchField();
                field.setId(input.attr("name"));
                field.setDisplayName(tr.select("span[id*=Lbl]").first().text());
                field.setData(notSelectable);
                if (tr.text().contains("nur Ziffern"))
                    field.setNumber(true);
                fields.add(field);
            } else if (tr.select("input[type=text]").size() == 2) {
                Element input1 = tr.select("input[type=text]").get(0);
                Element input2 = tr.select("input[type=text]").get(1);

                TextSearchField field1 = new TextSearchField();
                field1.setId(input1.attr("name"));
                field1.setDisplayName(tr.select("span[id*=Lbl]").first().text());
                field1.setData(notSelectable);
                if (tr.text().contains("nur Ziffern"))
                    field1.setNumber(true);
                fields.add(field1);

                TextSearchField field2 = new TextSearchField();
                field2.setId(input2.attr("name"));
                field2.setDisplayName(tr.select("span[id*=Lbl]").first().text());
                field2.setData(notSelectable);
                field2.setHalfWidth(true);
                if (tr.text().contains("nur Ziffern"))
                    field2.setNumber(true);
                fields.add(field2);
            } else if (tr.select("select").size() == 1) {
                Element select = tr.select("select").first();
                DropdownSearchField dropdown = new DropdownSearchField();
                dropdown.setId(select.attr("name"));
                dropdown.setDisplayName(tr.select("span[id*=Lbl]").first().text());
                List<DropdownSearchField.Option> values = new ArrayList<>();
                for (Element option : select.select("option")) {
                    DropdownSearchField.Option opt = new DropdownSearchField.Option(option.val(),
                            option.text());
                    values.add(opt);
                }
                dropdown.setDropdownValues(values);
                fields.add(dropdown);
            } else if (tr.select("input[type=checkbox]").size() == 1) {
                Element checkbox = tr.select("input[type=checkbox]").first();
                CheckboxSearchField field = new CheckboxSearchField();
                field.setId(checkbox.attr("name"));
                field.setDisplayName(tr.select("span[id*=Lbl]").first().text());
                fields.add(field);
            }
        }
    }
    return fields;
}

From source file:de.geeksfactory.opacclient.apis.Open.java

/**
 * Better version of JSoup's implementation of this function ({@link
 * org.jsoup.nodes.FormElement#formData()}).
 *
 * @param form       The form to submit/*from   ww w  . j av  a 2s .  c om*/
 * @param submitName The name attribute of the button which is clicked to submit the form, or
 *                   null
 * @return A MultipartEntityBuilder containing the data of the form
 */
protected MultipartEntityBuilder formData(FormElement form, String submitName) {
    MultipartEntityBuilder data = MultipartEntityBuilder.create();
    data.setLaxMode();

    // iterate the form control elements and accumulate their values
    for (Element el : form.elements()) {
        if (!el.tag().isFormSubmittable()) {
            continue; // contents are form listable, superset of submitable
        }
        String name = el.attr("name");
        if (name.length() == 0)
            continue;
        String type = el.attr("type");

        if ("select".equals(el.tagName())) {
            Elements options = el.select("option[selected]");
            boolean set = false;
            for (Element option : options) {
                data.addTextBody(name, option.val());
                set = true;
            }
            if (!set) {
                Element option = el.select("option").first();
                if (option != null) {
                    data.addTextBody(name, option.val());
                }
            }
        } else if ("checkbox".equalsIgnoreCase(type) || "radio".equalsIgnoreCase(type)) {
            // only add checkbox or radio if they have the checked attribute
            if (el.hasAttr("checked")) {
                data.addTextBody(name, el.val().length() > 0 ? el.val() : "on");
            }
        } else if ("submit".equalsIgnoreCase(type) || "image".equalsIgnoreCase(type)) {
            if (submitName != null && el.attr("name").contains(submitName)) {
                data.addTextBody(name, el.val());
            }
        } else {
            data.addTextBody(name, el.val());
        }
    }
    return data;
}

From source file:de.geeksfactory.opacclient.apis.Pica.java

@Override
public List<SearchField> getSearchFields() throws IOException, JSONException {
    if (!initialised) {
        start();/*from  w ww . j  a  va2  s  .c o m*/
    }

    String html = httpGet(opac_url + "/LNG=" + getLang() + "/DB=" + db + "/ADVANCED_SEARCHFILTER",
            getDefaultEncoding());
    Document doc = Jsoup.parse(html);
    List<SearchField> fields = new ArrayList<>();

    Elements options = doc.select("select[name=IKT0] option");
    for (Element option : options) {
        TextSearchField field = new TextSearchField();
        field.setDisplayName(option.text());
        field.setId(option.attr("value"));
        field.setHint("");
        field.setData(new JSONObject("{\"ADI\": false}"));

        Pattern pattern = Pattern.compile("\\[X?[A-Za-z]{2,3}:?\\]|\\(X?[A-Za-z]{2,3}:?\\)");
        Matcher matcher = pattern.matcher(field.getDisplayName());
        if (matcher.find()) {
            field.getData().put("meaning", matcher.group().replace(":", "").toUpperCase());
            field.setDisplayName(matcher.replaceFirst("").trim());
        }

        fields.add(field);
    }

    Elements sort = doc.select("select[name=SRT]");
    if (sort.size() > 0) {
        DropdownSearchField field = new DropdownSearchField();
        field.setDisplayName(sort.first().parent().parent().select(".longval").first().text());
        field.setId("SRT");
        for (Element option : sort.select("option")) {
            field.addDropdownValue(option.attr("value"), option.text());
        }
        fields.add(field);
    }

    for (Element input : doc.select("input[type=text][name^=ADI]")) {
        TextSearchField field = new TextSearchField();
        field.setDisplayName(input.parent().parent().select(".longkey").text());
        field.setId(input.attr("name"));
        field.setHint(input.parent().select("span").text());
        field.setData(new JSONObject("{\"ADI\": true}"));
        fields.add(field);
    }

    for (Element dropdown : doc.select("select[name^=ADI]")) {
        DropdownSearchField field = new DropdownSearchField();
        field.setDisplayName(dropdown.parent().parent().select(".longkey").text());
        field.setId(dropdown.attr("name"));
        for (Element option : dropdown.select("option")) {
            field.addDropdownValue(option.attr("value"), option.text());
        }
        fields.add(field);
    }

    Elements fuzzy = doc.select("input[name=FUZZY]");
    if (fuzzy.size() > 0) {
        CheckboxSearchField field = new CheckboxSearchField();
        field.setDisplayName(fuzzy.first().parent().parent().select(".longkey").first().text());
        field.setId("FUZZY");
        fields.add(field);
    }

    Elements mediatypes = doc.select("input[name=ADI_MAT]");
    if (mediatypes.size() > 0) {
        DropdownSearchField field = new DropdownSearchField();
        field.setDisplayName("Materialart");
        field.setId("ADI_MAT");

        field.addDropdownValue("", "Alle");
        for (Element mt : mediatypes) {
            field.addDropdownValue(mt.attr("value"),
                    mt.parent().nextElementSibling().text().replace("\u00a0", ""));
        }
        fields.add(field);
    }

    return fields;
}

From source file:de.geeksfactory.opacclient.apis.IOpac.java

public void updateRechnr(Document doc) {
    String url = null;/*  www.  jav a  2 s  .c o m*/
    for (Element a : doc.select("table a")) {
        if (a.attr("href").contains("rechnr=")) {
            url = a.attr("href");
            break;
        }
    }
    if (url == null) {
        return;
    }

    Integer rechnrPosition = url.indexOf("rechnr=") + 7;
    rechnr = url.substring(rechnrPosition, url.indexOf("&", rechnrPosition));
}

From source file:com.salsaberries.narchiver.Trawler.java

/**
 * Extracts links from html, and returns a set of Pages with their parent
 * page already defined./*from  ww  w.j  av  a 2 s.  c o  m*/
 *
 * @param html
 * @return A list of pages to follow.
 */
private ArrayList<Page> extractPages(Page extractPage) {

    String html = extractPage.getHtml();

    ArrayList<Page> pages = new ArrayList<>();

    // Are we at a stop at page?
    for (String e : stopAt) {
        if (extractPage.getTagURL().contains(e)) {
            return pages;
        }
    }

    // Parse the html
    Document doc = Jsoup.parse(html);
    Elements links = doc.getElementsByTag("a");

    for (Element link : links) {

        String tagURL = "";
        String linkText = "";
        boolean alreadyFollowed;
        boolean validURL = false;

        // First format the link
        if (link.attr("href").startsWith(baseURL)) {
            tagURL = link.attr("href").replace(baseURL, "");
            linkText = link.html();
            validURL = true;
        } else if (link.attr("href").startsWith("/")) {
            tagURL = link.attr("href");
            linkText = link.html();
            validURL = true;
        } else if (link.attr("href").startsWith("./")) {
            tagURL = link.attr("href").substring(1);
            linkText = link.html();
            validURL = true;
        }

        //else if (!link.attr("href").startsWith("/") && !link.attr("href").startsWith("http")) {
        //    tagURL = "/" + link.attr("href");
        //    linkText = link.html();
        //    validURL = true;
        //}
        // Has it already been followed?
        alreadyFollowed = trawledPages.contains(tagURL);

        // Does it violate the exclusion rules?
        boolean excluded = false;
        for (String e : exclude) {
            if (tagURL.contains(e)) {
                excluded = true;
            }
        }

        // Does it violate the exclusion equal rule?
        for (String e : excludeIfEqual) {
            if (tagURL.equals(e)) {
                excluded = true;
            }
        }

        if (!alreadyFollowed && validURL && !excluded) {
            logger.debug("Creating new page at URL " + tagURL);
            Page page = new Page(tagURL, extractPage, linkText);
            trawledPages.add(tagURL);
            pages.add(page);
        }

        if (alreadyFollowed) {
            logger.debug("Skipping duplicate at URL " + tagURL);
        }
        if (!validURL) {
            logger.debug("Invalid URL at " + link.attr("href"));
        }
        if (excluded) {
            logger.debug("Exclusion at " + link.attr("href"));
        }
    }
    return pages;
}

From source file:faescapeplan.FAEscapePlanUI.java

private ArrayList<String> indexJournals() {
    ArrayList<String> journalList = new ArrayList<>();
    updateTextLog("Indexing journal entries...");

    try {/* w  ww . ja va2  s  .com*/
        Document currentPage = Jsoup.connect("http://www.furaffinity.net/journals/" + userData.getName() + "/")
                .cookies(userData.getCookies()).userAgent(USER_AGENT).get();
        Elements elementList = currentPage.getElementsByAttributeValueMatching("id", "jid:\\d+");

        for (Element item : elementList) {
            String cleanJid = item.attr("id").replace("jid:", "");
            journalList.add(cleanJid);
        }

    } catch (IOException ex) {
        Logger.getLogger(FAEscapePlanUI.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(this, "An IOException occurred while indexing journals");
    }
    return journalList;
}

From source file:de.geeksfactory.opacclient.apis.Zones.java

private Document login(Account acc) throws IOException, OpacErrorException {
    String html = httpGet(/*w w w  .ja  va 2 s  .  c  o  m*/
            opac_url + "/APS_ZONES?fn=MyZone&Style=Portal3&SubStyle=&Lang=GER&ResponseEncoding" + "=utf-8",
            getDefaultEncoding());
    Document doc = Jsoup.parse(html);
    doc.setBaseUri(opac_url + "/APS_ZONES");
    if (doc.select(".AccountSummaryCounterLink").size() > 0) {
        return doc;
    }
    if (doc.select("#LoginForm").size() == 0) {
        throw new NotReachableException("Login form not found");
    }
    List<NameValuePair> params = new ArrayList<>();

    for (Element input : doc.select("#LoginForm input")) {
        if (!input.attr("name").equals("BRWR") && !input.attr("name").equals("PIN")) {
            params.add(new BasicNameValuePair(input.attr("name"), input.attr("value")));
        }
    }
    params.add(new BasicNameValuePair("BRWR", acc.getName()));
    params.add(new BasicNameValuePair("PIN", acc.getPassword()));

    String loginHtml;
    try {
        loginHtml = httpPost(doc.select("#LoginForm").get(0).absUrl("action"), new UrlEncodedFormEntity(params),
                getDefaultEncoding());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    if (!loginHtml.contains("Kontostand")) {
        throw new OpacErrorException(stringProvider.getString(StringProvider.LOGIN_FAILED));
    }

    Document doc2 = Jsoup.parse(loginHtml);
    Pattern objid_pat = Pattern.compile("Obj_([0-9]+)\\?.*");
    for (Element a : doc2.select("a")) {
        Matcher objid_matcher = objid_pat.matcher(a.attr("href"));
        if (objid_matcher.matches()) {
            accountobj = objid_matcher.group(1);
        }
    }

    return doc2;
}

From source file:com.salsaberries.narchiver.Trawler.java

/**
 * Logs into the site.//from  w  w  w .  j  av a2  s  . c om
 *
 * @return
 * @throws TrawlException
 */
private boolean login() throws TrawlException {
    --loginAttempts;

    if (loginAttempts < 0) {
        logger.error("Warning! Exceeded maximum number of login attempts! Program is now exiting.");
        throw new TrawlException("Maximum login attempts exceeded.");
    }

    logger.info("Attempting to log in at " + baseURL + site.getString("LOGIN_URL"));

    try {

        // follow redirects until you get it right
        HttpRequest httpRequest;
        HttpMessage httpGet;
        String url = baseURL + site.getString("LOGIN_URL");

        while (true) {
            httpGet = new HttpMessage(HttpType.GET);
            httpGet.setUrl(url);
            httpGet.initializeDefaultHeaders(site);
            httpGet.addCookieHeaders(cookies);

            httpRequest = new HttpRequest(httpGet);

            if (httpRequest.getStatusCode() != 200) {
                getTempCookies(httpRequest.getHeaders());

                // Find the header I want
                boolean found = false;
                for (Header h : httpRequest.getHeaders()) {
                    if (h.getName().equals("Location")) {
                        url = h.getValue();
                        found = true;
                    }
                }

                if (!found) {
                    throw new TrawlException("Redirect loop.");
                }

            } else {
                break;
            }

        }

        // Get headers
        ArrayList<Header> headers = httpRequest.getHeaders();
        // Parse the cookies
        getTempCookies(headers);

        String body = httpRequest.getHtml();
        Document doc = Jsoup.parse(body);
        Elements logins = doc.getElementsByAttributeValue("action", site.getString("LOGIN_SUBMIT"));

        if (logins.isEmpty()) {
            logins = doc.getElementsByAttributeValue("action",
                    site.getString("BASE_URL") + site.getString("LOGIN_SUBMIT"));
        }
        if (logins.isEmpty()) {
            logins = doc.getElementsByAttributeValue("method", "POST");
        }

        if (logins.isEmpty()) {
            throw new TrawlException("Failed to find login form!");
        }
        if (logins.size() > 1) {
            logger.warn("Found multiple login forms. Picking the first one...");
        }

        Element login = logins.get(0);

        // Extract the captcha image if appropriate
        String captchaResult = "";
        if (!site.getString("CAPTCHA").equals("")) {
            // Download the captcha image
            HttpMessage getCaptcha = new HttpMessage(HttpType.GET);
            getCaptcha.setImage(true);
            if (!site.isNull("CAPTCHA_IMAGE")) {
                getCaptcha.setUrl(baseURL + site.getString("CAPTCHA_IMAGE"));

                getCaptcha.initializeDefaultImageHeaders(site);
                getCaptcha.addHeader(new Header("Referrer", baseURL + site.getString("LOGIN_URL")));
                getCaptcha.addCookieHeaders(cookies);

                // Send it to deathbycaptcha
                SocketClient client = new SocketClient("njanetos", "2point7182");
                HttpRequest image = new HttpRequest(getCaptcha);
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ImageIO.write(image.getImage(), "png", os);
                Captcha result = client.decode(os.toByteArray());
                captchaResult = result.toString();
            } else {
                // Just try to get the image
                Elements captchas = login.getElementsByTag("img");

                if (captchas.size() != 1) {
                    throw new TrawlException(
                            "Failed to find captcha, but the initialization file says there should be one.");
                }

                Element captchaImage = captchas.get(0);

                // Does it contain base64?
                if (captchaImage.attr("src").contains("base64")) {
                    String src = captchaImage.attr("src").split(",")[1];

                    byte image[] = Base64.decodeBase64(src);
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    os.write(image);

                    SocketClient client = new SocketClient("njanetos", "2point7182");

                    Captcha result = client.decode(os.toByteArray());
                    captchaResult = result.toString();

                } else {
                    if (captchaImage.attr("src").contains(baseURL)) {
                        getCaptcha.setUrl(captchaImage.attr("src"));
                    } else {
                        getCaptcha.setUrl(baseURL + captchaImage.attr("src"));
                    }

                    getCaptcha.initializeDefaultImageHeaders(site);
                    getCaptcha.addHeader(new Header("Referrer", baseURL + site.getString("LOGIN_URL")));
                    getCaptcha.addCookieHeaders(cookies);

                    // Send it to deathbycaptcha
                    SocketClient client = new SocketClient("njanetos", "2point7182");
                    HttpRequest image = new HttpRequest(getCaptcha);
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    ImageIO.write(image.getImage(), "png", os);
                    Captcha result = client.decode(os.toByteArray());
                    captchaResult = result.toString();
                }
            }

            logger.info("Decoded captcha: " + captchaResult);
        }

        // Grab any hidden fields
        Elements hidden = login.getElementsByAttributeValue("type", "hidden");

        // Build the post response
        HttpMessage httpPost = new HttpMessage(HttpType.POST);
        httpPost.initializeDefaultHeaders(site);
        httpPost.addCookieHeaders(cookies);
        // TODO: Read this from the html!
        httpPost.setUrl(baseURL + site.getString("LOGIN_SUBMIT"));

        httpPost.appendContent(site.getString("USERNAME_FIELD"), site.getString("USERNAME"));
        httpPost.appendContent(site.getString("PASSWORD_FIELD"), site.getString("PASSWORD"));
        if (!captchaResult.equals("")) {
            httpPost.appendContent(site.getString("CAPTCHA_FIELD"), captchaResult);
        }

        for (int i = 0; i < hidden.size(); ++i) {
            httpPost.appendContent(hidden.get(i).attr("name"), hidden.get(i).attr("value"));
        }

        // Add the submit info
        Element submit = login.getElementsByAttributeValue("type", "submit").get(0);
        httpPost.appendContent(submit.attr("name"), submit.attr("value"));

        // Add the referrer
        httpPost.addHeader(new Header("Referer", baseURL + site.getString("LOGIN_URL")));

        // Log in
        HttpRequest response = new HttpRequest(httpPost);
        headers = response.getHeaders();
        // Add any relevant cookies
        getTempCookies(headers);
        logger.info("Successfully logged in, response code: " + response.getStatusCode());

        // Were we redirected? If so, visit the redirection URL before continuing. 
        if (response.getStatusCode() == 302) {
            // Send a GET request to the redirection URL before continuing. 
            httpGet = new HttpMessage(HttpType.GET);
            httpGet.initializeDefaultHeaders(site);
            httpGet.addHeader(new Header("Referer", baseURL + site.getString("LOGIN_URL")));
            String redirectionURL = getRedirectionURL(headers);
            httpGet.setUrl(redirectionURL);
            httpGet.addCookieHeaders(cookies);

            httpRequest = new HttpRequest(httpGet);
            logger.debug("Visited redirected page. Status code " + httpRequest.getStatusCode());
        }

    } catch (ConnectionException | MalformedURLException | ProtocolException ex) {
        // Did not successfully log in
        logger.error(ex.getMessage());
        return false;
    } catch (IOException ex) {
        // Did not successfully log in
        logger.error(ex.getMessage());
        return false;
    } catch (Exception | InterruptedException ex) {
        // Did not successfully log in
        logger.error(ex.getMessage());
        return false;
    }

    // Did we successfully log in? Then return true.
    return true;

}

From source file:de.geeksfactory.opacclient.apis.Heidi.java

@Override
public ReservationResult reservation(DetailledItem item, Account account, int useraction, String selection)
        throws IOException {
    String html = httpGet(opac_url + "/bestellung.cgi?ks=" + item.getId() + "&sess=" + sessid, ENCODING, false,
            cookieStore);/* ww  w . j  ava2  s  . com*/
    Document doc = Jsoup.parse(html);
    if (doc.select("input[name=pw]").size() > 0) {
        List<NameValuePair> nameValuePairs = new ArrayList<>(2);
        nameValuePairs.add(new BasicNameValuePair("id", account.getName()));
        nameValuePairs.add(new BasicNameValuePair("pw", account.getPassword()));
        nameValuePairs.add(new BasicNameValuePair("sess", sessid));
        nameValuePairs.add(new BasicNameValuePair("log", "login"));
        nameValuePairs.add(new BasicNameValuePair("weiter", "bestellung.cgi?ks=" + item.getId()));
        html = httpPost(opac_url + "/login.cgi", new UrlEncodedFormEntity(nameValuePairs), ENCODING);
        doc = Jsoup.parse(html);
        if (doc.select(".loginbox .meld").size() > 0) {
            return new ReservationResult(MultiStepResult.Status.ERROR, doc.select(".loginbox .meld").text());
        }
    }
    if (doc.select("input[name=ort]").size() > 0) {
        if (selection != null) {
            List<NameValuePair> nameValuePairs = new ArrayList<>(2);
            nameValuePairs.add(new BasicNameValuePair("ks", item.getId()));
            nameValuePairs.add(new BasicNameValuePair("ort", selection));
            nameValuePairs.add(new BasicNameValuePair("sess", sessid));
            nameValuePairs.add(new BasicNameValuePair("funktion", "Vormerkung"));
            html = httpPost(opac_url + "/bestellung.cgi", new UrlEncodedFormEntity(nameValuePairs), ENCODING);
            doc = Jsoup.parse(html);
        } else {
            List<Map<String, String>> options = new ArrayList<>();
            for (Element input : doc.select("input[name=ort]")) {
                Element label = doc.select("label[for=" + input.id() + "]").first();
                Map<String, String> selopt = new HashMap<>();
                selopt.put("key", input.attr("value"));
                selopt.put("value", label.text());
                options.add(selopt);
            }
            ReservationResult res = new ReservationResult(MultiStepResult.Status.SELECTION_NEEDED);
            res.setSelection(options);
            return res;
        }
    }
    if (doc.select(".fehler").size() > 0) {
        String text = doc.select(".fehler").text();
        return new ReservationResult(MultiStepResult.Status.ERROR, text);
    }
    String text = doc.select(".meld2").text();
    if (text.contains("Das Medium wurde")) {
        return new ReservationResult(MultiStepResult.Status.OK, text);
    } else {
        return new ReservationResult(MultiStepResult.Status.ERROR, text);
    }
}

From source file:de.geeksfactory.opacclient.apis.Zones.java

@Override
public ReservationResult reservation(DetailledItem item, Account acc, int useraction, String selection)
        throws IOException {
    String reservation_info = item.getReservation_info();
    String html = httpGet(opac_url + "/" + reservation_info, getDefaultEncoding());
    Document doc = Jsoup.parse(html);
    if (html.contains("Geheimnummer")) {
        List<NameValuePair> params = new ArrayList<>();
        for (Element input : doc.select("#MainForm input")) {
            if (!input.attr("name").equals("BRWR") && !input.attr("name").equals("PIN")) {
                params.add(new BasicNameValuePair(input.attr("name"), input.attr("value")));
            }/*from   ww w.  j a va2  s  . c  o  m*/
        }
        params.add(new BasicNameValuePair("BRWR", acc.getName()));
        params.add(new BasicNameValuePair("PIN", acc.getPassword()));
        html = httpGet(opac_url + "/" + doc.select("#MainForm").attr("action") + "?"
                + URLEncodedUtils.format(params, getDefaultEncoding()), getDefaultEncoding());
        doc = Jsoup.parse(html);
    }

    if (useraction == ReservationResult.ACTION_BRANCH) {
        List<NameValuePair> params = new ArrayList<>();
        for (Element input : doc.select("#MainForm input")) {
            if (!input.attr("name").equals("Confirm")) {
                params.add(new BasicNameValuePair(input.attr("name"), input.attr("value")));
            }

        }
        params.add(new BasicNameValuePair("MakeResTypeDef.Reservation.RecipientLocn", selection));
        params.add(new BasicNameValuePair("Confirm", "1"));
        httpGet(opac_url + "/" + doc.select("#MainForm").attr("action") + "?"
                + URLEncodedUtils.format(params, getDefaultEncoding()), getDefaultEncoding());
        return new ReservationResult(MultiStepResult.Status.OK);
    }

    if (useraction == 0) {
        ReservationResult res = null;
        for (Node n : doc.select("#MainForm").first().childNodes()) {
            if (n instanceof TextNode) {
                if (((TextNode) n).text().contains("Entgelt")) {
                    res = new ReservationResult(ReservationResult.Status.CONFIRMATION_NEEDED);
                    List<String[]> details = new ArrayList<>();
                    details.add(new String[] { ((TextNode) n).text().trim() });
                    res.setDetails(details);
                    res.setMessage(((TextNode) n).text().trim());
                    res.setActionIdentifier(MultiStepResult.ACTION_CONFIRMATION);
                }
            }
        }
        if (res != null) {
            return res;
        }
    }
    if (doc.select("#MainForm select").size() > 0) {
        ReservationResult res = new ReservationResult(ReservationResult.Status.SELECTION_NEEDED);
        List<Map<String, String>> sel = new ArrayList<>();
        for (Element opt : doc.select("#MainForm select option")) {
            Map<String, String> selopt = new HashMap<>();
            selopt.put("key", opt.attr("value"));
            selopt.put("value", opt.text().trim());
            sel.add(selopt);
        }
        res.setSelection(sel);
        res.setMessage("Bitte Zweigstelle auswhlen");
        res.setActionIdentifier(ReservationResult.ACTION_BRANCH);
        return res;
    }

    return new ReservationResult(ReservationResult.Status.ERROR);
}