Search in sources :

Example 11 with Copy

use of de.geeksfactory.opacclient.objects.Copy in project opacclient by opacapp.

the class SISIS method parseDetail.

static DetailedItem parseDetail(String html, String html2, String html3, String coverJs, JSONObject data, StringProvider stringProvider) throws IOException {
    Document doc = Jsoup.parse(html);
    String opac_url = data.optString("baseurl", "");
    doc.setBaseUri(opac_url);
    Document doc2 = Jsoup.parse(html2);
    doc2.setBaseUri(opac_url);
    Document doc3 = Jsoup.parse(html3);
    doc3.setBaseUri(opac_url);
    DetailedItem result = new DetailedItem();
    try {
        result.setId(doc.select("#bibtip_id").text().trim());
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    List<String> reservationlinks = new ArrayList<>();
    for (Element link : doc3.select("#vormerkung a, #tab-content a")) {
        String href = link.absUrl("href");
        Map<String, String> hrefq = getQueryParamsFirst(href);
        if (result.getId() == null) {
            // ID retrieval
            String key = hrefq.get("katkey");
            if (key != null) {
                result.setId(key);
                break;
            }
        }
        // Vormerken
        if (hrefq.get("methodToCall") != null) {
            if (hrefq.get("methodToCall").equals("doVormerkung") || hrefq.get("methodToCall").equals("doBestellung")) {
                reservationlinks.add(href.split("\\?")[1]);
            }
        }
    }
    if (reservationlinks.size() == 1) {
        result.setReservable(true);
        result.setReservation_info(reservationlinks.get(0));
    } else if (reservationlinks.size() == 0) {
        result.setReservable(false);
    } else {
    // TODO: Multiple options - handle this case!
    }
    if (result.getId() == null && doc.select("#permalink_link").size() > 0) {
        result.setId(doc.select("#permalink_link").text());
    }
    if (coverJs != null) {
        Pattern srcPattern = Pattern.compile("<img .* src=\"([^\"]+)\">");
        Matcher matcher = srcPattern.matcher(coverJs);
        if (matcher.find()) {
            result.setCover(matcher.group(1));
        }
    } else if (doc.select(".data td img").size() == 1) {
        result.setCover(doc.select(".data td img").first().attr("abs:src"));
    }
    if (doc.select(".aw_teaser_title").size() == 1) {
        result.setTitle(doc.select(".aw_teaser_title").first().text().trim());
    } else if (doc.select(".data td strong").size() > 0) {
        result.setTitle(doc.select(".data td strong").first().text().trim());
    } else {
        result.setTitle("");
    }
    if (doc.select(".aw_teaser_title_zusatz").size() > 0) {
        result.addDetail(new Detail("Titelzusatz", doc.select(".aw_teaser_title_zusatz").text().trim()));
    }
    String title = "";
    String text = "";
    boolean takeover = false;
    Element detailtrs = doc2.select(".box-container .data td").first();
    for (Node node : detailtrs.childNodes()) {
        if (node instanceof Element) {
            Element element = (Element) node;
            if (element.tagName().equals("strong")) {
                if (element.hasClass("c2")) {
                    if (!title.equals("")) {
                        result.addDetail(new Detail(title, text.trim()));
                    }
                    title = element.text().trim();
                    text = "";
                } else {
                    text = text + element.text();
                }
            } else {
                if (element.tagName().equals("a")) {
                    if (element.text().trim().contains("hier klicken") || title.contains("Link")) {
                        text = text + node.attr("href");
                        takeover = true;
                        break;
                    } else {
                        text = text + element.text();
                    }
                }
            }
        } else if (node instanceof TextNode) {
            text = text + ((TextNode) node).text();
        }
    }
    if (!takeover) {
        text = "";
        title = "";
    }
    detailtrs = doc2.select("#tab-content .data td").first();
    if (detailtrs != null) {
        for (Node node : detailtrs.childNodes()) {
            if (node instanceof Element) {
                if (((Element) node).tagName().equals("strong")) {
                    if (!text.equals("") && !title.equals("")) {
                        result.addDetail(new Detail(title.trim(), text.trim()));
                        if (title.equals("Titel:")) {
                            result.setTitle(text.trim());
                        }
                        text = "";
                    }
                    title = ((Element) node).text().trim();
                } else {
                    if (((Element) node).tagName().equals("a") && (((Element) node).text().trim().contains("hier klicken") || title.equals("Link:"))) {
                        text = text + node.attr("href");
                    } else {
                        text = text + ((Element) node).text();
                    }
                }
            } else if (node instanceof TextNode) {
                text = text + ((TextNode) node).text();
            }
        }
    } else {
        if (doc2.select("#tab-content .fulltitle tr").size() > 0) {
            Elements rows = doc2.select("#tab-content .fulltitle tr");
            for (Element tr : rows) {
                if (tr.children().size() == 2) {
                    Element valcell = tr.child(1);
                    String value = valcell.text().trim();
                    if (valcell.select("a").size() == 1) {
                        value = valcell.select("a").first().absUrl("href");
                    }
                    result.addDetail(new Detail(tr.child(0).text().trim(), value));
                }
            }
        } else {
            result.addDetail(new Detail(stringProvider.getString(StringProvider.ERROR), stringProvider.getString(StringProvider.COULD_NOT_LOAD_DETAIL)));
        }
    }
    if (!text.equals("") && !title.equals("")) {
        result.addDetail(new Detail(title.trim(), text.trim()));
        if (title.equals("Titel:")) {
            result.setTitle(text.trim());
        }
    }
    for (Element link : doc3.select("#tab-content a")) {
        Map<String, String> hrefq = getQueryParamsFirst(link.absUrl("href"));
        if (result.getId() == null) {
            // ID retrieval
            String key = hrefq.get("katkey");
            if (key != null) {
                result.setId(key);
                break;
            }
        }
    }
    for (Element link : doc3.select(".box-container a")) {
        if (link.text().trim().equals("Download")) {
            result.addDetail(new Detail(stringProvider.getString(StringProvider.DOWNLOAD), link.absUrl("href")));
        }
    }
    if (doc3.select("#tab-content .textrot").size() > 0) {
        result.addDetail(new Detail(stringProvider.getString(StringProvider.STATUS), doc3.select("#tab-content .textrot").text()));
    }
    Map<String, Integer> copy_columnmap = new HashMap<>();
    // Default values
    copy_columnmap.put("barcode", 1);
    copy_columnmap.put("branch", 3);
    copy_columnmap.put("status", 4);
    Element table = doc.select("#tab-content .data").first();
    Elements copy_columns = table != null ? table.select("tr#bg2 th") : new Elements();
    for (int i = 0; i < copy_columns.size(); i++) {
        Element th = copy_columns.get(i);
        String head = th.text().trim();
        if (head.contains("Status")) {
            copy_columnmap.put("status", i);
        }
        if (head.contains("Zweigstelle")) {
            copy_columnmap.put("branch", i);
        }
        if (head.contains("Mediennummer")) {
            copy_columnmap.put("barcode", i);
        }
        if (head.contains("Standort")) {
            copy_columnmap.put("location", i);
        }
        if (head.contains("Signatur")) {
            copy_columnmap.put("signature", i);
        }
    }
    Pattern status_lent = Pattern.compile("^(entliehen) bis ([0-9]{1,2}.[0-9]{1,2}.[0-9]{2," + "4}) \\(gesamte Vormerkungen: ([0-9]+)\\)$");
    Pattern status_and_barcode = Pattern.compile("^(.*) ([0-9A-Za-z]+)$");
    Elements exemplartrs = table != null ? table.select("tr").not("#bg2") : new Elements();
    DateTimeFormatter fmt = DateTimeFormat.forPattern("dd.MM.yyyy").withLocale(Locale.GERMAN);
    for (Element tr : exemplartrs) {
        try {
            Copy copy = new Copy();
            Element status = tr.child(copy_columnmap.get("status"));
            Element barcode = tr.child(copy_columnmap.get("barcode"));
            String barcodetext = barcode.text().trim().replace(" Wegweiser", "");
            // STATUS
            String statustext;
            if (status.getElementsByTag("b").size() > 0) {
                statustext = status.getElementsByTag("b").text().trim();
            } else {
                statustext = status.text().trim();
            }
            if (copy_columnmap.get("status").equals(copy_columnmap.get("barcode"))) {
                Matcher matcher1 = status_and_barcode.matcher(statustext);
                if (matcher1.matches()) {
                    statustext = matcher1.group(1);
                    barcodetext = matcher1.group(2);
                }
            }
            Matcher matcher = status_lent.matcher(statustext);
            if (matcher.matches()) {
                copy.setStatus(matcher.group(1));
                copy.setReservations(matcher.group(3));
                copy.setReturnDate(fmt.parseLocalDate(matcher.group(2)));
            } else {
                copy.setStatus(statustext.trim().replace(" Wegweiser", ""));
            }
            copy.setBarcode(barcodetext);
            if (status.select("a[href*=doVormerkung]").size() == 1) {
                copy.setResInfo(status.select("a[href*=doVormerkung]").attr("href").split("\\?")[1]);
            }
            String branchtext = tr.child(copy_columnmap.get("branch")).text().trim().replace(" Wegweiser", "");
            copy.setBranch(branchtext);
            if (copy_columnmap.containsKey("location")) {
                copy.setLocation(tr.child(copy_columnmap.get("location")).text().trim().replace(" Wegweiser", ""));
            }
            if (copy_columnmap.containsKey("signature")) {
                copy.setShelfmark(tr.child(copy_columnmap.get("signature")).text().trim().replace(" Wegweiser", ""));
            }
            result.addCopy(copy);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    try {
        Element isvolume = null;
        Map<String, String> volume = new HashMap<>();
        Elements links = doc.select(".data td a");
        int elcount = links.size();
        for (int eli = 0; eli < elcount; eli++) {
            List<NameValuePair> anyurl = URLEncodedUtils.parse(new URI(links.get(eli).attr("href")), "UTF-8");
            for (NameValuePair nv : anyurl) {
                if (nv.getName().equals("methodToCall") && nv.getValue().equals("volumeSearch")) {
                    isvolume = links.get(eli);
                } else if (nv.getName().equals("catKey")) {
                    volume.put("catKey", nv.getValue());
                } else if (nv.getName().equals("dbIdentifier")) {
                    volume.put("dbIdentifier", nv.getValue());
                }
            }
            if (isvolume != null) {
                volume.put("volume", "true");
                result.setVolumesearch(volume);
                break;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
Also used : Pattern(java.util.regex.Pattern) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) Matcher(java.util.regex.Matcher) HashMap(java.util.HashMap) Element(org.jsoup.nodes.Element) Node(org.jsoup.nodes.Node) TextNode(org.jsoup.nodes.TextNode) ArrayList(java.util.ArrayList) TextNode(org.jsoup.nodes.TextNode) Document(org.jsoup.nodes.Document) Elements(org.jsoup.select.Elements) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) JSONException(org.json.JSONException) NotReachableException(de.geeksfactory.opacclient.networking.NotReachableException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) Copy(de.geeksfactory.opacclient.objects.Copy) DetailedItem(de.geeksfactory.opacclient.objects.DetailedItem) DateTimeFormatter(org.joda.time.format.DateTimeFormatter) Detail(de.geeksfactory.opacclient.objects.Detail)

Example 12 with Copy

use of de.geeksfactory.opacclient.objects.Copy in project opacclient by opacapp.

the class Adis method parseResult.

DetailedItem parseResult(String id, Document doc) throws IOException, OpacErrorException {
    List<NameValuePair> nvpairs;
    DetailedItem res = new DetailedItem();
    if (doc.select("#R001 img").size() == 1) {
        String cover_url = doc.select("#R001 img").first().absUrl("src");
        if (!cover_url.endsWith("erne.gif")) {
            // If there is no cover, the first image usually is the "n Stars" rating badge
            res.setCover(cover_url);
        }
    }
    for (Element tr : doc.select("#R06 .aDISListe table tbody tr")) {
        if (tr.children().size() < 2) {
            continue;
        }
        String title = tr.child(0).text().trim();
        String value = tr.child(1).text().trim();
        if (value.contains("hier klicken") || value.startsWith("zur ") || title.contains("URL")) {
            res.addDetail(new Detail(title, tr.child(1).select("a").first().absUrl("href")));
        } else {
            res.addDetail(new Detail(title, value));
        }
        if (title.contains("Titel") && res.getTitle() == null) {
            res.setTitle(value.split("[:/;]")[0].trim());
        }
    }
    if (res.getTitle() == null) {
        for (Detail d : res.getDetails()) {
            if (d.getDesc().contains("Gesamtwerk") || d.getDesc().contains("Zeitschrift")) {
                res.setTitle(d.getContent());
                break;
            }
        }
    }
    if (doc.select("input[value*=Reservieren], input[value*=Vormerken], " + "input[value*=Einzelbestellung]").size() > 0 && id != null) {
        res.setReservable(true);
        res.setReservation_info(id);
    }
    DateTimeFormatter fmt = DateTimeFormat.forPattern("dd.MM.yyyy").withLocale(Locale.GERMAN);
    if (doc.select("#R08 table.rTable_table, #R09 table.rTable_table").size() > 0) {
        Element table = doc.select("#R08 table.rTable_table, #R09 table.rTable_table").first();
        Map<Integer, String> colmap = new HashMap<>();
        int i = 0;
        for (Element th : table.select("thead tr th")) {
            String head = th.text().trim();
            if (head.contains("Bibliothek") || head.contains("Library")) {
                colmap.put(i, "branch");
            } else if (head.contains("Standort") || head.contains("Location")) {
                colmap.put(i, "location");
            } else if (head.contains("Signatur") || head.contains("Call number")) {
                colmap.put(i, "signature");
            } else if (head.contains("URL")) {
                colmap.put(i, "url");
            } else if (head.contains("Status") || head.contains("Hinweis") || head.contains("Leihfrist") || head.matches(".*Verf.+gbarkeit.*")) {
                colmap.put(i, "status");
            }
            i++;
        }
        for (Element tr : table.select("tbody tr")) {
            Copy copy = new Copy();
            for (Entry<Integer, String> entry : colmap.entrySet()) {
                if (entry.getValue().equals("status")) {
                    String status = tr.child(entry.getKey()).text().trim();
                    String currentStatus = copy.getStatus() != null ? copy.getStatus() + " - " : "";
                    if (status.contains(" am: ")) {
                        copy.setStatus(currentStatus + status.split("-")[0]);
                        try {
                            copy.setReturnDate(fmt.parseLocalDate(status.split(": ")[1]));
                        } catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        }
                    } else {
                        copy.setStatus(currentStatus + status);
                    }
                } else {
                    copy.set(entry.getValue(), tr.child(entry.getKey()).text().trim());
                }
            }
            res.addCopy(copy);
        }
    }
    if (doc.select("a:contains(Zitierlink)").size() > 0) {
        res.setId(doc.select("a:contains(Zitierlink)").attr("href"));
    } else {
        // null would be overridden by the UI, because there _is_
        res.setId("");
    // an id,< we just can not use it.
    }
    return res;
}
Also used : NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HashMap(java.util.HashMap) Element(org.jsoup.nodes.Element) Copy(de.geeksfactory.opacclient.objects.Copy) DetailedItem(de.geeksfactory.opacclient.objects.DetailedItem) DateTimeFormatter(org.joda.time.format.DateTimeFormatter) Detail(de.geeksfactory.opacclient.objects.Detail)

Example 13 with Copy

use of de.geeksfactory.opacclient.objects.Copy in project opacclient by opacapp.

the class IOpac method parse_result.

protected DetailedItem parse_result(String html) throws IOException {
    Document doc = Jsoup.parse(html);
    DetailedItem result = new DetailedItem();
    String id = null;
    if (doc.select("input[name=mednr]").size() > 0) {
        id = doc.select("input[name=mednr]").first().val().trim();
    } else if (doc.select("a[href*=mednr]").size() > 0) {
        String href = doc.select("a[href*=mednr]").first().attr("href");
        id = getQueryParamsFirst(href).get("mednr").trim();
    }
    result.setId(id);
    // check if new share button is available (allows to share a link to the standard
    // frameset of the OPAC instead of only the detail frame)
    newShareLinks = doc.select("#sharebutton").size() > 0;
    Elements table = doc.select("table").get(1).select("tr");
    // GET COVER IMAGE
    String imgUrl = table.get(0).select("img[src~=^https?://(:?images(?:-[^\\.]*)?\\.|[^\\.]*\\" + ".images-)amazon\\.com]").attr("src");
    result.setCover(imgUrl);
    // GET INFORMATION
    Copy copy = new Copy();
    for (Element row : table) {
        Element titleElem;
        Element detailElem;
        if (row.select("> th").size() > 0) {
            // iOpac < 2.87
            titleElem = row.select("th").first();
            detailElem = row.select("td").first();
        } else if (row.select("> td").size() >= 2) {
            // iOpac >= 2.87
            titleElem = row.select("> td").first();
            detailElem = row.select("> td").get(1);
        } else {
            // we don't know what to do
            continue;
        }
        String detail = detailElem.text().trim().replace("\u00a0", "");
        String title = titleElem.text().trim().replace("\u00a0", "");
        if (!title.equals("")) {
            if (title.contains("verliehen bis")) {
                if (detail.equals("")) {
                    copy.setStatus("verfügbar");
                } else {
                    copy.setStatus("verliehen bis " + detail);
                }
            } else if (title.contains("Abteilung")) {
                copy.setDepartment(detail);
            } else if (title.contains("Signatur")) {
                copy.setShelfmark(detail);
            } else if (title.contains("Titel")) {
                result.setTitle(detail);
            } else if (!title.contains("Cover")) {
                result.addDetail(new Detail(title, detail));
            }
        }
    }
    // GET RESERVATION INFO
    if ("verfügbar".equals(copy.getStatus()) || doc.select("a[href^=/cgi-bin/di.exe?mode=10], input.resbutton").size() == 0) {
        result.setReservable(false);
    } else {
        result.setReservable(true);
        if (doc.select("a[href^=/cgi-bin/di.exe?mode=10]").size() > 0) {
            // Reservation via link
            result.setReservation_info(doc.select("a[href^=/cgi-bin/di.exe?mode=10]").first().attr("href").substring(1).replace(" ", ""));
        } else {
            // Reservation via form (method="get")
            Element form = doc.select("input.resbutton").first().parent();
            result.setReservation_info(generateQuery(form));
        }
    }
    if (copy.notEmpty())
        result.addCopy(copy);
    return result;
}
Also used : Copy(de.geeksfactory.opacclient.objects.Copy) Element(org.jsoup.nodes.Element) DetailedItem(de.geeksfactory.opacclient.objects.DetailedItem) Document(org.jsoup.nodes.Document) Elements(org.jsoup.select.Elements) Detail(de.geeksfactory.opacclient.objects.Detail)

Example 14 with Copy

use of de.geeksfactory.opacclient.objects.Copy in project opacclient by opacapp.

the class SISIS method reservation.

@Override
public ReservationResult reservation(DetailedItem item, Account acc, int useraction, String selection) throws IOException {
    String reservation_info = item.getReservation_info();
    final String branch_inputfield = "issuepoint";
    Document doc = null;
    String action = "reservation";
    if (reservation_info.contains("doBestellung")) {
        action = "order";
    }
    if (useraction == MultiStepResult.ACTION_CONFIRMATION) {
        List<NameValuePair> nameValuePairs = new ArrayList<>(2);
        nameValuePairs.add(new BasicNameValuePair("methodToCall", action));
        nameValuePairs.add(new BasicNameValuePair("CSId", CSId));
        String html = httpPost(opac_url + "/" + action + ".do", new UrlEncodedFormEntity(nameValuePairs), ENCODING);
        doc = Jsoup.parse(html);
    } else if (selection == null || useraction == 0) {
        String html = httpGet(opac_url + "/availability.do?" + reservation_info, ENCODING);
        doc = Jsoup.parse(html);
        if (doc.select("input[name=username]").size() > 0) {
            // Login vonnöten
            CSId = doc.select("input[name=CSId]").val();
            List<NameValuePair> nameValuePairs = new ArrayList<>(2);
            nameValuePairs.add(new BasicNameValuePair("username", acc.getName()));
            nameValuePairs.add(new BasicNameValuePair("password", acc.getPassword()));
            nameValuePairs.add(new BasicNameValuePair("methodToCall", "submit"));
            nameValuePairs.add(new BasicNameValuePair("CSId", CSId));
            nameValuePairs.add(new BasicNameValuePair("login_action", "Login"));
            html = handleLoginMessage(httpPost(opac_url + "/login.do", new UrlEncodedFormEntity(nameValuePairs), ENCODING));
            doc = Jsoup.parse(html);
            if (doc.getElementsByClass("error").size() == 0) {
                logged_in = System.currentTimeMillis();
                logged_in_as = acc;
            }
        }
        if (doc.select("input[name=expressorder]").size() > 0) {
            List<NameValuePair> nameValuePairs = new ArrayList<>(2);
            nameValuePairs.add(new BasicNameValuePair(branch_inputfield, selection));
            nameValuePairs.add(new BasicNameValuePair("methodToCall", action));
            nameValuePairs.add(new BasicNameValuePair("CSId", CSId));
            nameValuePairs.add(new BasicNameValuePair("expressorder", " "));
            html = httpPost(opac_url + "/" + action + ".do", new UrlEncodedFormEntity(nameValuePairs), ENCODING);
            doc = Jsoup.parse(html);
        }
        if (doc.select("input[name=" + branch_inputfield + "]").size() > 0) {
            List<Map<String, String>> branches = new ArrayList<>();
            for (Element option : doc.select("input[name=" + branch_inputfield + "]").first().parent().parent().parent().select("td")) {
                if (option.select("input").size() != 1) {
                    continue;
                }
                String value = option.text().trim();
                String key = option.select("input").val();
                Map<String, String> selopt = new HashMap<>();
                selopt.put("key", key);
                selopt.put("value", value);
                branches.add(selopt);
            }
            ReservationResult result = new ReservationResult(MultiStepResult.Status.SELECTION_NEEDED);
            result.setActionIdentifier(ReservationResult.ACTION_BRANCH);
            result.setSelection(branches);
            return result;
        }
    } else if (useraction == ReservationResult.ACTION_BRANCH) {
        List<NameValuePair> nameValuePairs = new ArrayList<>(2);
        nameValuePairs.add(new BasicNameValuePair(branch_inputfield, selection));
        nameValuePairs.add(new BasicNameValuePair("methodToCall", action));
        nameValuePairs.add(new BasicNameValuePair("CSId", CSId));
        String html = httpPost(opac_url + "/" + action + ".do", new UrlEncodedFormEntity(nameValuePairs), ENCODING);
        doc = Jsoup.parse(html);
    }
    if (doc == null) {
        return new ReservationResult(MultiStepResult.Status.ERROR);
    }
    if (doc.getElementsByClass("error").size() >= 1) {
        return new ReservationResult(MultiStepResult.Status.ERROR, doc.getElementsByClass("error").get(0).text());
    }
    if (doc.html().contains("jsp/error.jsp")) {
        return new ReservationResult(MultiStepResult.Status.ERROR, doc.getElementsByTag("h2").get(0).text());
    }
    if (doc.select("#CirculationForm p").size() > 0 && doc.select("input[type=button]").size() >= 2) {
        List<String[]> details = new ArrayList<>();
        for (String row : doc.select("#CirculationForm p").first().html().split("<br>")) {
            Document frag = Jsoup.parseBodyFragment(row);
            if (frag.text().contains(":")) {
                String[] split = frag.text().split(":");
                if (split.length >= 2) {
                    details.add(new String[] { split[0].trim() + ":", split[1].trim() });
                }
            } else {
                details.add(new String[] { "", frag.text().trim() });
            }
        }
        ReservationResult result = new ReservationResult(Status.CONFIRMATION_NEEDED);
        result.setDetails(details);
        return result;
    }
    if (doc.select("#CirculationForm .textrot").size() >= 1) {
        String errmsg = doc.select("#CirculationForm .textrot").get(0).text();
        if (errmsg.contains("Dieses oder andere Exemplare in anderer Zweigstelle ausleihbar")) {
            Copy best = null;
            for (Copy copy : item.getCopies()) {
                if (copy.getResInfo() == null) {
                    continue;
                }
                if (best == null) {
                    best = copy;
                    continue;
                }
                try {
                    if (Integer.parseInt(copy.getReservations()) < Long.parseLong(best.getReservations())) {
                        best = copy;
                    } else if (Integer.parseInt(copy.getReservations()) == Long.parseLong(best.getReservations())) {
                        if (copy.getReturnDate().isBefore(best.getReturnDate())) {
                            best = copy;
                        }
                    }
                } catch (NumberFormatException e) {
                }
            }
            if (best != null) {
                item.setReservation_info(best.getResInfo());
                return reservation(item, acc, 0, null);
            }
        }
        return new ReservationResult(MultiStepResult.Status.ERROR, errmsg);
    }
    if (doc.select("#CirculationForm td[colspan=2] strong").size() >= 1) {
        return new ReservationResult(MultiStepResult.Status.OK, doc.select("#CirculationForm td[colspan=2] strong").get(0).text());
    }
    return new ReservationResult(Status.OK);
}
Also used : NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) Element(org.jsoup.nodes.Element) ArrayList(java.util.ArrayList) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) Document(org.jsoup.nodes.Document) Copy(de.geeksfactory.opacclient.objects.Copy) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap)

Example 15 with Copy

use of de.geeksfactory.opacclient.objects.Copy in project opacclient by opacapp.

the class TouchPoint method parse_result.

protected DetailedItem parse_result(String html) throws IOException {
    Document doc = Jsoup.parse(html);
    doc.setBaseUri(opac_url);
    DetailedItem result = new DetailedItem();
    result.setCover(findCoverUrl(doc, false));
    if (doc.select("#permalink-link").size() > 0) {
        String href = doc.select("#permalink-link").first().attr("href");
        JSONObject id = new JSONObject();
        try {
            id.put("url", href);
            result.setId(id.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    for (Element tr : doc.select(".titleinfo tr")) {
        // Sometimes there is one th and one td, sometimes two tds
        String detailName = tr.select("th, td").first().text().trim();
        if (detailName.endsWith(":")) {
            detailName = detailName.substring(0, detailName.length() - 1);
        }
        String detailValue = tr.select("td").last().text().trim();
        result.addDetail(new Detail(detailName, detailValue));
        if (detailName.contains("ID in diesem Katalog") && result.getId() == null) {
            result.setId(detailValue);
        }
        if (detailName.equals("Titel")) {
            result.setTitle(detailValue);
        }
    }
    if (result.getDetails().size() == 0 && doc.select("#details").size() > 0) {
        // e.g. Bayreuth_Uni
        String dname = "";
        String dval = "";
        boolean in_value = true;
        for (Node n : doc.select("#details").first().childNodes()) {
            if (n instanceof Element && ((Element) n).tagName().equals("strong")) {
                if (in_value) {
                    if (dname.length() > 0 && dval.length() > 0) {
                        result.addDetail(new Detail(dname, dval));
                        if (dname.equals("Titel")) {
                            result.setTitle(dval);
                        }
                    }
                    dname = ((Element) n).text();
                    in_value = false;
                } else {
                    dname += ((Element) n).text();
                }
            } else {
                String t = null;
                if (n instanceof TextNode) {
                    t = ((TextNode) n).text();
                } else if (n instanceof Element) {
                    t = ((Element) n).text();
                }
                if (t != null) {
                    if (in_value) {
                        dval += t;
                    } else {
                        in_value = true;
                        dval = t;
                    }
                }
            }
        }
    }
    if (result.getTitle() == null) {
        result.setTitle(doc.select("h1").first().text());
    }
    // Copies
    String copiesParameter = doc.select("div[id^=ajax_holdings_url").attr("ajaxParameter").replace("&amp;", "");
    if (!"".equals(copiesParameter)) {
        String copiesHtml = httpGet(opac_url + "/" + copiesParameter, ENCODING);
        Document copiesDoc = Jsoup.parse(copiesHtml);
        List<String> table_keys = new ArrayList<>();
        for (Element th : copiesDoc.select(".data tr th")) {
            if (th.text().contains("Zweigstelle")) {
                table_keys.add("branch");
            } else if (th.text().contains("Status")) {
                table_keys.add("status");
            } else if (th.text().contains("Signatur")) {
                table_keys.add("signature");
            } else {
                table_keys.add(null);
            }
        }
        for (Element tr : copiesDoc.select(".data tr:has(td)")) {
            Copy copy = new Copy();
            int i = 0;
            for (Element td : tr.select("td")) {
                if (table_keys.get(i) != null) {
                    copy.set(table_keys.get(i), td.text().trim());
                }
                i++;
            }
            result.addCopy(copy);
        }
    }
    // Reservation Info, only works if the code above could find a URL
    if (!"".equals(copiesParameter)) {
        String reservationParameter = copiesParameter.replace("showHoldings", "showDocument");
        try {
            String reservationHtml = httpGet(opac_url + "/" + reservationParameter, ENCODING);
            Document reservationDoc = Jsoup.parse(reservationHtml);
            reservationDoc.setBaseUri(opac_url);
            if (reservationDoc.select("a[href*=requestItem.do]").size() == 1) {
                result.setReservable(true);
                result.setReservation_info(reservationDoc.select("a").first().attr("abs:href"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        // fail silently
        }
    }
    try {
        Element isvolume = null;
        Map<String, String> volume = new HashMap<>();
        Elements links = doc.select(".data td a");
        int elcount = links.size();
        for (int eli = 0; eli < elcount; eli++) {
            List<NameValuePair> anyurl = URLEncodedUtils.parse(new URI(links.get(eli).attr("href")), "UTF-8");
            for (NameValuePair nv : anyurl) {
                if (nv.getName().equals("methodToCall") && nv.getValue().equals("volumeSearch")) {
                    isvolume = links.get(eli);
                } else if (nv.getName().equals("catKey")) {
                    volume.put("catKey", nv.getValue());
                } else if (nv.getName().equals("dbIdentifier")) {
                    volume.put("dbIdentifier", nv.getValue());
                }
            }
            if (isvolume != null) {
                volume.put("volume", "true");
                result.setVolumesearch(volume);
                break;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
Also used : NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HashMap(java.util.HashMap) Element(org.jsoup.nodes.Element) Node(org.jsoup.nodes.Node) TextNode(org.jsoup.nodes.TextNode) ArrayList(java.util.ArrayList) JSONException(org.json.JSONException) TextNode(org.jsoup.nodes.TextNode) Document(org.jsoup.nodes.Document) Elements(org.jsoup.select.Elements) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) JSONException(org.json.JSONException) NotReachableException(de.geeksfactory.opacclient.networking.NotReachableException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) JSONObject(org.json.JSONObject) Copy(de.geeksfactory.opacclient.objects.Copy) DetailedItem(de.geeksfactory.opacclient.objects.DetailedItem) Detail(de.geeksfactory.opacclient.objects.Detail)

Aggregations

Copy (de.geeksfactory.opacclient.objects.Copy)22 DetailedItem (de.geeksfactory.opacclient.objects.DetailedItem)17 Detail (de.geeksfactory.opacclient.objects.Detail)16 Element (org.jsoup.nodes.Element)15 Document (org.jsoup.nodes.Document)13 DateTimeFormatter (org.joda.time.format.DateTimeFormatter)10 Elements (org.jsoup.select.Elements)10 HashMap (java.util.HashMap)8 JSONException (org.json.JSONException)8 JSONObject (org.json.JSONObject)8 IOException (java.io.IOException)6 NotReachableException (de.geeksfactory.opacclient.networking.NotReachableException)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5 ArrayList (java.util.ArrayList)5 NameValuePair (org.apache.http.NameValuePair)5 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)5 Node (org.jsoup.nodes.Node)5 TextNode (org.jsoup.nodes.TextNode)5 Volume (de.geeksfactory.opacclient.objects.Volume)4 URI (java.net.URI)3