Search in sources :

Example 6 with FormElement

use of org.jsoup.nodes.FormElement in project jsoup by jhy.

the class ElementsTest method forms.

@Test
public void forms() {
    Document doc = Jsoup.parse("<form id=1><input name=q></form><div /><form id=2><input name=f></form>");
    Elements els = doc.select("*");
    assertEquals(9, els.size());
    List<FormElement> forms = els.forms();
    assertEquals(2, forms.size());
    assertTrue(forms.get(0) != null);
    assertTrue(forms.get(1) != null);
    assertEquals("1", forms.get(0).id());
    assertEquals("2", forms.get(1).id());
}
Also used : Document(org.jsoup.nodes.Document) FormElement(org.jsoup.nodes.FormElement) Test(org.junit.Test)

Example 7 with FormElement

use of org.jsoup.nodes.FormElement in project opacclient by opacapp.

the class WinBiap method prolong.

@Override
public ProlongResult prolong(String media, Account account, int useraction, String selection) throws IOException {
    try {
        login(account);
    } catch (OpacErrorException e) {
        return new ProlongResult(MultiStepResult.Status.ERROR, e.getMessage());
    }
    Document lentPage = Jsoup.parse(httpGet(opac_url + "/user/borrow.aspx", getDefaultEncoding()));
    lentPage.select("input[name=" + media + "]").first().attr("checked", true);
    List<Connection.KeyVal> formData = ((FormElement) lentPage.select("form").first()).formData();
    FormBody.Builder paramBuilder = new FormBody.Builder();
    for (Connection.KeyVal kv : formData) {
        paramBuilder.add(kv.key(), kv.value());
    }
    if (lentPage.select("a[id$=ButtonBorrowChecked][href^=javascript]").size() > 0) {
        String href = lentPage.select("a[id$=ButtonBorrowChecked][href^=javascript]").attr("href");
        Pattern pattern = Pattern.compile("javascript:__doPostBack\\('([^,]*)','([^\\)]*)'\\)");
        Matcher matcher = pattern.matcher(href);
        if (!matcher.find()) {
            return new ProlongResult(MultiStepResult.Status.ERROR, StringProvider.INTERNAL_ERROR);
        }
        paramBuilder.add("__EVENTTARGET", matcher.group(1));
        paramBuilder.add("__EVENTARGUMENT", matcher.group(2));
    }
    String html = httpPost(opac_url + "/user/borrow.aspx", paramBuilder.build(), getDefaultEncoding());
    Document confirmationPage = Jsoup.parse(html);
    FormElement confirmationForm = (FormElement) confirmationPage.select("form").first();
    List<Connection.KeyVal> formData2 = confirmationForm.formData();
    FormBody.Builder params2 = new FormBody.Builder();
    for (Connection.KeyVal kv : formData2) {
        if (!kv.key().contains("Button") || kv.key().endsWith("ButtonProlongationOk")) {
            params2.add(kv.key(), kv.value());
        }
    }
    httpPost(opac_url + "/user/" + confirmationForm.attr("action"), params2.build(), getDefaultEncoding());
    return new ProlongResult(MultiStepResult.Status.OK);
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) FormBody(okhttp3.FormBody) Connection(org.jsoup.Connection) Document(org.jsoup.nodes.Document) FormElement(org.jsoup.nodes.FormElement)

Example 8 with FormElement

use of org.jsoup.nodes.FormElement in project opacclient by opacapp.

the class Open method searchGetPage.

@Override
public SearchRequestResult searchGetPage(int page) throws IOException, OpacErrorException, JSONException {
    if (searchResultDoc == null)
        throw new NotReachableException();
    Document doc = searchResultDoc;
    if (doc.select("span[id$=DataPager1]").size() == 0) {
        /*
                New style: Page buttons using normal links
                We can go directly to the correct page
            */
        if (doc.select("a[id*=LinkButtonPageN]").size() > 0) {
            String href = doc.select("a[id*=LinkButtonPageN][href*=page]").first().attr("href");
            String url = href.replaceFirst("page=\\d+", "page=" + page);
            Document doc2 = Jsoup.parse(httpGet(url, getDefaultEncoding()));
            doc2.setBaseUri(url);
            return parse_search(doc2, page);
        } else {
            int totalCount;
            try {
                totalCount = Integer.parseInt(doc.select("span[id$=TotalItemsLabel]").first().text());
            } catch (Exception e) {
                totalCount = 0;
            }
            // Next page does not exist
            return new SearchRequestResult(new ArrayList<SearchResult>(), 0, totalCount);
        }
    } else {
        /*
                Old style: Page buttons using Javascript
                When there are many pages of results, there will only be links to the next 4 and
                previous 4 pages, so we will click links until it gets to the correct page.
            */
        Elements pageLinks = doc.select("span[id$=DataPager1]").first().select("a[id*=LinkButtonPageN], span[id*=LabelPageN]");
        int from = Integer.valueOf(pageLinks.first().text());
        int to = Integer.valueOf(pageLinks.last().text());
        Element linkToClick;
        boolean willBeCorrectPage;
        if (page < from) {
            linkToClick = pageLinks.first();
            willBeCorrectPage = false;
        } else if (page > to) {
            linkToClick = pageLinks.last();
            willBeCorrectPage = false;
        } else {
            linkToClick = pageLinks.get(page - from);
            willBeCorrectPage = true;
        }
        if (linkToClick.tagName().equals("span")) {
            // we are trying to get the page we are already on
            return parse_search(searchResultDoc, page);
        }
        Pattern pattern = Pattern.compile("javascript:__doPostBack\\('([^,]*)','([^\\)]*)'\\)");
        Matcher matcher = pattern.matcher(linkToClick.attr("href"));
        if (!matcher.find())
            throw new OpacErrorException(StringProvider.INTERNAL_ERROR);
        FormElement form = (FormElement) doc.select("form").first();
        MultipartBody data = formData(form, null).addFormDataPart("__EVENTTARGET", matcher.group(1)).addFormDataPart("__EVENTARGUMENT", matcher.group(2)).build();
        String postUrl = form.attr("abs:action");
        String html = httpPost(postUrl, data, "UTF-8");
        if (willBeCorrectPage) {
            // We clicked on the correct link
            Document doc2 = Jsoup.parse(html);
            doc2.setBaseUri(postUrl);
            return parse_search(doc2, page);
        } else {
            // There was no correct link, so try to find one again
            searchResultDoc = Jsoup.parse(html);
            searchResultDoc.setBaseUri(postUrl);
            return searchGetPage(page);
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) NotReachableException(de.geeksfactory.opacclient.networking.NotReachableException) Matcher(java.util.regex.Matcher) Element(org.jsoup.nodes.Element) FormElement(org.jsoup.nodes.FormElement) SearchResult(de.geeksfactory.opacclient.objects.SearchResult) Document(org.jsoup.nodes.Document) Elements(org.jsoup.select.Elements) JSONException(org.json.JSONException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) NotReachableException(de.geeksfactory.opacclient.networking.NotReachableException) FormElement(org.jsoup.nodes.FormElement) SearchRequestResult(de.geeksfactory.opacclient.objects.SearchRequestResult) MultipartBody(okhttp3.MultipartBody)

Example 9 with FormElement

use of org.jsoup.nodes.FormElement in project opacclient by opacapp.

the class Open method search.

@Override
public SearchRequestResult search(List<SearchQuery> queries) throws IOException, OpacErrorException, JSONException {
    String url = opac_url + "/" + data.getJSONObject("urls").getString("advanced_search") + NO_MOBILE;
    Document doc = Jsoup.parse(httpGet(url, getDefaultEncoding()));
    doc.setBaseUri(url);
    int selectableCount = 0;
    for (SearchQuery query : queries) {
        if (query.getValue().equals("") || query.getValue().equals("false"))
            continue;
        if (query.getSearchField() instanceof TextSearchField | query.getSearchField() instanceof BarcodeSearchField) {
            SearchField field = query.getSearchField();
            if (field.getData().getBoolean("selectable")) {
                selectableCount++;
                if (selectableCount > 3) {
                    throw new OpacErrorException(stringProvider.getQuantityString(StringProvider.LIMITED_NUM_OF_CRITERIA, 3, 3));
                }
                String number = numberToText(selectableCount);
                Element searchField = doc.select("select[name$=" + number + "SearchField]").first();
                Element searchValue = doc.select("input[name$=" + number + "SearchValue]").first();
                setSelectValue(searchField, field.getId());
                searchValue.val(query.getValue());
            } else {
                Element input = doc.select("input[name=" + field.getId() + "]").first();
                input.val(query.getValue());
            }
        } else if (query.getSearchField() instanceof DropdownSearchField) {
            DropdownSearchField field = (DropdownSearchField) query.getSearchField();
            Element select = doc.select("select[name=" + field.getId() + "]").first();
            setSelectValue(select, query.getValue());
        } else if (query.getSearchField() instanceof CheckboxSearchField) {
            CheckboxSearchField field = (CheckboxSearchField) query.getSearchField();
            Element input = doc.select("input[name=" + field.getId() + "]").first();
            input.attr("checked", query.getValue());
        }
    }
    // Submit form
    FormElement form = (FormElement) doc.select("form").first();
    MultipartBody data = formData(form, "BtnSearch").build();
    String postUrl = form.attr("abs:action");
    String html = httpPost(postUrl, data, "UTF-8");
    Document doc2 = Jsoup.parse(html);
    doc2.setBaseUri(postUrl);
    return parse_search(doc2, 0);
}
Also used : SearchQuery(de.geeksfactory.opacclient.searchfields.SearchQuery) BarcodeSearchField(de.geeksfactory.opacclient.searchfields.BarcodeSearchField) Element(org.jsoup.nodes.Element) FormElement(org.jsoup.nodes.FormElement) Document(org.jsoup.nodes.Document) TextSearchField(de.geeksfactory.opacclient.searchfields.TextSearchField) FormElement(org.jsoup.nodes.FormElement) DropdownSearchField(de.geeksfactory.opacclient.searchfields.DropdownSearchField) TextSearchField(de.geeksfactory.opacclient.searchfields.TextSearchField) CheckboxSearchField(de.geeksfactory.opacclient.searchfields.CheckboxSearchField) BarcodeSearchField(de.geeksfactory.opacclient.searchfields.BarcodeSearchField) DropdownSearchField(de.geeksfactory.opacclient.searchfields.DropdownSearchField) SearchField(de.geeksfactory.opacclient.searchfields.SearchField) CheckboxSearchField(de.geeksfactory.opacclient.searchfields.CheckboxSearchField) MultipartBody(okhttp3.MultipartBody)

Example 10 with FormElement

use of org.jsoup.nodes.FormElement in project opacclient by opacapp.

the class PicaLBS method reservation.

@Override
public ReservationResult reservation(DetailedItem item, Account account, int useraction, String selection) throws IOException {
    try {
        JSONArray json = new JSONArray(item.getReservation_info());
        if (json.length() != 1) {
            // TODO: This case is not implemented, don't know if it is possible with LBS
            ReservationResult res = new ReservationResult(MultiStepResult.Status.ERROR);
            res.setMessage(stringProvider.getString(StringProvider.INTERNAL_ERROR));
            return res;
        } else {
            String url = json.getJSONObject(0).getString("link");
            Document doc = Jsoup.parse(httpGet(url, getDefaultLBSEncoding()));
            if (doc.select("#opacVolumesForm").size() == 0) {
                List<NameValuePair> params = new ArrayList<>();
                params.add(new BasicNameValuePair("j_username", account.getName()));
                params.add(new BasicNameValuePair("j_password", account.getPassword()));
                params.add(new BasicNameValuePair("login", "Login"));
                doc = Jsoup.parse(httpPost(url, new UrlEncodedFormEntity(params), getDefaultLBSEncoding()));
            }
            if (doc.select(".error, font[color=red]").size() > 0) {
                ReservationResult res = new ReservationResult(MultiStepResult.Status.ERROR);
                res.setMessage(doc.select(".error, font[color=red]").text());
                return res;
            }
            System.out.println(doc.text());
            List<Connection.KeyVal> keyVals = ((FormElement) doc.select("#opacVolumesForm").first()).formData();
            List<NameValuePair> params = new ArrayList<>();
            for (Connection.KeyVal kv : keyVals) {
                params.add(new BasicNameValuePair(kv.key(), kv.value()));
            }
            doc = Jsoup.parse(httpPost(url, new UrlEncodedFormEntity(params), getDefaultEncoding()));
            if (doc.select(".error").size() > 0) {
                ReservationResult res = new ReservationResult(MultiStepResult.Status.ERROR);
                res.setMessage(doc.select(".error").text());
                return res;
            } else if (doc.select(".info").text().contains("Reservation saved") || doc.select(".info").text().contains("vorgemerkt")) {
                return new ReservationResult(MultiStepResult.Status.OK);
            } else {
                ReservationResult res = new ReservationResult(MultiStepResult.Status.ERROR);
                res.setMessage(stringProvider.getString(StringProvider.UNKNOWN_ERROR));
                return res;
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
        ReservationResult res = new ReservationResult(MultiStepResult.Status.ERROR);
        res.setMessage(stringProvider.getString(StringProvider.INTERNAL_ERROR));
        return res;
    }
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) Connection(org.jsoup.Connection) JSONException(org.json.JSONException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) Document(org.jsoup.nodes.Document) FormElement(org.jsoup.nodes.FormElement) BasicNameValuePair(org.apache.http.message.BasicNameValuePair)

Aggregations

FormElement (org.jsoup.nodes.FormElement)12 Document (org.jsoup.nodes.Document)9 Connection (org.jsoup.Connection)6 Element (org.jsoup.nodes.Element)5 MultipartBody (okhttp3.MultipartBody)3 File (java.io.File)2 FileInputStream (java.io.FileInputStream)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 Matcher (java.util.regex.Matcher)2 Pattern (java.util.regex.Pattern)2 FormBody (okhttp3.FormBody)2 JSONException (org.json.JSONException)2 Elements (org.jsoup.select.Elements)2 Test (org.junit.Test)2 BoxAPIConnection (com.box.sdk.BoxAPIConnection)1 NotReachableException (de.geeksfactory.opacclient.networking.NotReachableException)1 Copy (de.geeksfactory.opacclient.objects.Copy)1 SearchRequestResult (de.geeksfactory.opacclient.objects.SearchRequestResult)1 SearchResult (de.geeksfactory.opacclient.objects.SearchResult)1