Search in sources :

Example 1 with FormElement

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

the class Open method formData.

/**
 * Better version of JSoup's implementation of this function ({@link
 * org.jsoup.nodes.FormElement#formData()}).
 *
 * @param form       The form to submit
 * @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 MultipartBody.Builder formData(FormElement form, String submitName) {
    MultipartBody.Builder data = new MultipartBody.Builder();
    data.setType(MediaType.parse("multipart/form-data; charset=utf-8"));
    // iterate the form control elements and accumulate their values
    for (Element el : form.elements()) {
        if (!el.tag().isFormSubmittable()) {
            // contents are form listable, superset of submitable
            continue;
        }
        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.addPart(createFormData(name, option.val()));
                set = true;
            }
            if (!set) {
                Element option = el.select("option").first();
                if (option != null) {
                    data.addPart(createFormData(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.addFormDataPart(name, el.val().length() > 0 ? el.val() : "on");
            }
        } else if ("submit".equalsIgnoreCase(type) || "image".equalsIgnoreCase(type) || "button".equalsIgnoreCase(type)) {
            if (submitName != null && el.attr("name").contains(submitName)) {
                data.addPart(createFormData(name, el.val()));
            }
        } else {
            data.addPart(createFormData(name, el.val()));
        }
    }
    return data;
}
Also used : MultipartBody(okhttp3.MultipartBody) Element(org.jsoup.nodes.Element) FormElement(org.jsoup.nodes.FormElement) Elements(org.jsoup.select.Elements)

Example 2 with FormElement

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

the class WinBiap method reservation.

@Override
public ReservationResult reservation(DetailedItem item, Account account, int useraction, String selection) throws IOException {
    if (selection == null) {
        // Which copy?
        List<Map<String, String>> options = new ArrayList<>();
        for (Copy copy : item.getCopies()) {
            if (copy.getResInfo() == null)
                continue;
            Map<String, String> option = new HashMap<>();
            option.put("key", copy.getResInfo());
            option.put("value", copy.getBarcode() + " - " + copy.getBranch() + " - " + copy.getReturnDate());
            options.add(option);
        }
        if (options.size() == 0) {
            return new ReservationResult(MultiStepResult.Status.ERROR, stringProvider.getString(StringProvider.NO_COPY_RESERVABLE));
        } else if (options.size() == 1) {
            return reservation(item, account, useraction, options.get(0).get("key"));
        } else {
            ReservationResult res = new ReservationResult(MultiStepResult.Status.SELECTION_NEEDED);
            res.setSelection(options);
            return res;
        }
    } else {
        // Reservation
        // the URL stored in selection might be absolute (WinBiap 4.3) or relative (4.2)
        String reservationUrl = new URL(new URL(opac_url), selection).toString();
        // the URL stored in selection contains "=" and other things inside params
        // and will be messed up by our cleanUrl function, therefore we use a direct HttpGet
        Document doc = Jsoup.parse(httpGet(reservationUrl, getDefaultEncoding()));
        if (doc.select("[id$=LabelLoginMessage]").size() > 0) {
            doc.select("[id$=TextBoxLoginName]").val(account.getName());
            doc.select("[id$=TextBoxLoginPassword]").val(account.getPassword());
            FormElement form = (FormElement) doc.select("form").first();
            List<Connection.KeyVal> formData = form.formData();
            FormBody.Builder paramBuilder = new FormBody.Builder();
            for (Connection.KeyVal kv : formData) {
                if (!kv.key().contains("Button") || kv.key().endsWith("ButtonLogin")) {
                    paramBuilder.add(kv.key(), kv.value());
                }
            }
            doc = Jsoup.parse(httpPost(opac_url + "/user/" + form.attr("action"), paramBuilder.build(), getDefaultEncoding()));
        }
        FormElement confirmationForm = (FormElement) doc.select("form").first();
        List<Connection.KeyVal> formData = confirmationForm.formData();
        FormBody.Builder paramBuilder = new FormBody.Builder();
        for (Connection.KeyVal kv : formData) {
            if (!kv.key().contains("Button") || kv.key().endsWith("ButtonVorbestOk")) {
                paramBuilder.add(kv.key(), kv.value());
            }
        }
        httpPost(opac_url + "/user/" + confirmationForm.attr("action"), paramBuilder.build(), getDefaultEncoding());
        return new ReservationResult(MultiStepResult.Status.OK);
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) FormBody(okhttp3.FormBody) Connection(org.jsoup.Connection) Document(org.jsoup.nodes.Document) URL(java.net.URL) FormElement(org.jsoup.nodes.FormElement) Copy(de.geeksfactory.opacclient.objects.Copy) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with FormElement

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

the class ConnectTest method postHtmlFile.

/**
 * Test fetching a form, and submitting it with a file attached.
 */
@Test
public void postHtmlFile() throws IOException {
    Document index = Jsoup.connect(FileServlet.urlTo("/htmltests/upload-form.html")).get();
    List<FormElement> forms = index.select("[name=tidy]").forms();
    assertEquals(1, forms.size());
    FormElement form = forms.get(0);
    Connection post = form.submit();
    File uploadFile = ParseTest.getFile("/htmltests/google-ipod.html.gz");
    FileInputStream stream = new FileInputStream(uploadFile);
    Connection.KeyVal fileData = post.data("_file");
    assertNotNull(fileData);
    fileData.value("check.html");
    fileData.inputStream(stream);
    Connection.Response res;
    try {
        res = post.execute();
    } finally {
        stream.close();
    }
    Document doc = res.parse();
    // from form action
    assertEquals(ihVal("Method", doc), "POST");
    assertEquals(ihVal("Part _file Filename", doc), "check.html");
    assertEquals(ihVal("Part _file Name", doc), "_file");
    assertEquals(ihVal("_function", doc), "tidy");
}
Also used : Connection(org.jsoup.Connection) Document(org.jsoup.nodes.Document) File(java.io.File) FormElement(org.jsoup.nodes.FormElement) FileInputStream(java.io.FileInputStream) Test(org.junit.jupiter.api.Test)

Example 4 with FormElement

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

the class HtmlTreeBuilder method parseFragment.

List<Node> parseFragment(String inputFragment, @Nullable Element context, String baseUri, Parser parser) {
    // context may be null
    state = HtmlTreeBuilderState.Initial;
    initialiseParse(new StringReader(inputFragment), baseUri, parser);
    contextElement = context;
    fragmentParsing = true;
    Element root = null;
    if (context != null) {
        if (// quirks setup:
        context.ownerDocument() != null)
            doc.quirksMode(context.ownerDocument().quirksMode());
        // initialise the tokeniser state:
        String contextTag = context.normalName();
        switch(contextTag) {
            case "title":
            case "textarea":
                tokeniser.transition(TokeniserState.Rcdata);
                break;
            case "iframe":
            case "noembed":
            case "noframes":
            case "style":
            case "xml":
                tokeniser.transition(TokeniserState.Rawtext);
                break;
            case "script":
                tokeniser.transition(TokeniserState.ScriptData);
                break;
            case "noscript":
                // if scripting enabled, rawtext
                tokeniser.transition(TokeniserState.Data);
                break;
            case "plaintext":
                tokeniser.transition(TokeniserState.PLAINTEXT);
                break;
            case "template":
                tokeniser.transition(TokeniserState.Data);
                pushTemplateMode(HtmlTreeBuilderState.InTemplate);
                break;
            default:
                tokeniser.transition(TokeniserState.Data);
        }
        root = new Element(tagFor(contextTag, settings), baseUri);
        doc.appendChild(root);
        stack.add(root);
        resetInsertionMode();
        // setup form element to nearest form on context (up ancestor chain). ensures form controls are associated
        // with form correctly
        Element formSearch = context;
        while (formSearch != null) {
            if (formSearch instanceof FormElement) {
                formElement = (FormElement) formSearch;
                break;
            }
            formSearch = formSearch.parent();
        }
    }
    runParser();
    if (context != null) {
        // depending on context and the input html, content may have been added outside of the root el
        // e.g. context=p, input=div, the div will have been pushed out.
        List<Node> nodes = root.siblingNodes();
        if (!nodes.isEmpty())
            root.insertChildren(-1, nodes);
        return root.childNodes();
    } else
        return doc.childNodes();
}
Also used : Element(org.jsoup.nodes.Element) FormElement(org.jsoup.nodes.FormElement) TextNode(org.jsoup.nodes.TextNode) Node(org.jsoup.nodes.Node) DataNode(org.jsoup.nodes.DataNode) CDataNode(org.jsoup.nodes.CDataNode) StringReader(java.io.StringReader) FormElement(org.jsoup.nodes.FormElement)

Example 5 with FormElement

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

the class UrlConnectTest method postHtmlFile.

/**
     * Test fetching a form, and submitting it with a file attached.
     */
@Test
public void postHtmlFile() throws IOException {
    Document index = Jsoup.connect("http://direct.infohound.net/tidy/").get();
    FormElement form = index.select("[name=tidy]").forms().get(0);
    Connection post = form.submit();
    File uploadFile = ParseTest.getFile("/htmltests/google-ipod.html");
    FileInputStream stream = new FileInputStream(uploadFile);
    Connection.KeyVal fileData = post.data("_file");
    fileData.value("check.html");
    fileData.inputStream(stream);
    Connection.Response res;
    try {
        res = post.execute();
    } finally {
        stream.close();
    }
    Document out = res.parse();
    assertTrue(out.text().contains("HTML Tidy Complete"));
}
Also used : Connection(org.jsoup.Connection) Document(org.jsoup.nodes.Document) File(java.io.File) FormElement(org.jsoup.nodes.FormElement) FileInputStream(java.io.FileInputStream) Test(org.junit.Test)

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