Search in sources :

Example 6 with NotReachableException

use of de.geeksfactory.opacclient.networking.NotReachableException in project opacclient by opacapp.

the class SearchResultListFragment method setSearchResult.

public void setSearchResult(final SearchRequestResult searchresult) {
    for (SearchResult result : searchresult.getResults()) {
        result.setPage(searchresult.getPage_index());
    }
    if (searchresult.getTotal_result_count() >= 0) {
        ((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(getResources().getQuantityString(R.plurals.result_number, searchresult.getTotal_result_count(), searchresult.getTotal_result_count()));
    }
    if (searchresult.getResults().size() == 0 && searchresult.getTotal_result_count() <= 0) {
        setEmptyText(getString(R.string.no_results));
    }
    this.searchresult = searchresult;
    OpacApi api = null;
    try {
        api = app.getApi();
    } catch (OpacClient.LibraryRemovedException ignored) {
    }
    adapter = new ResultsAdapterEndless(getActivity(), searchresult, new OnLoadMoreListener() {

        @Override
        public SearchRequestResult onLoadMore(int page) throws Exception {
            SearchRequestResult res = app.getApi().searchGetPage(page);
            setLastLoadedPage(page);
            return res;
        }

        @Override
        public void onError(Exception e) {
            if (getActivity() != null) {
                if (e instanceof OpacErrorException) {
                    showConnectivityError(e.getMessage());
                } else if (e instanceof SSLSecurityException) {
                    showConnectivityError(getResources().getString(R.string.connection_error_detail_security));
                } else if (e instanceof NotReachableException) {
                    showConnectivityError(getResources().getString(R.string.connection_error_detail_nre));
                } else {
                    e.printStackTrace();
                    showConnectivityError();
                }
            }
        }

        @Override
        public void updateResultCount(int resultCount) {
            /*
                         * When IOpac finds more than 200 results, the real
						 * result count is not known until the second page is
						 * loaded
						 */
            if (resultCount >= 0 && getActivity() != null) {
                ((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(getResources().getQuantityString(R.plurals.result_number, resultCount, resultCount));
            }
        }
    }, api);
    setListAdapter(adapter);
    getListView().setTextFilterEnabled(true);
    setListShown(true);
}
Also used : OnLoadMoreListener(de.geeksfactory.opacclient.frontend.ResultsAdapterEndless.OnLoadMoreListener) OpacClient(de.geeksfactory.opacclient.OpacClient) SearchRequestResult(de.geeksfactory.opacclient.objects.SearchRequestResult) NotReachableException(de.geeksfactory.opacclient.networking.NotReachableException) OpacApi(de.geeksfactory.opacclient.apis.OpacApi) SSLSecurityException(de.geeksfactory.opacclient.networking.SSLSecurityException) SearchResult(de.geeksfactory.opacclient.objects.SearchResult) OpacErrorException(de.geeksfactory.opacclient.apis.OpacApi.OpacErrorException) JSONException(org.json.JSONException) OpacErrorException(de.geeksfactory.opacclient.apis.OpacApi.OpacErrorException) IOException(java.io.IOException) SSLSecurityException(de.geeksfactory.opacclient.networking.SSLSecurityException) NotReachableException(de.geeksfactory.opacclient.networking.NotReachableException)

Example 7 with NotReachableException

use of de.geeksfactory.opacclient.networking.NotReachableException in project opacclient by opacapp.

the class TestApi method account.

@Override
public AccountData account(Account account) throws IOException, JSONException, OpacErrorException {
    AccountData data = new AccountData(account.getId());
    List<LentItem> lent = new ArrayList<>();
    List<ReservedItem> reservations = new ArrayList<>();
    try {
        JSONObject d = new JSONObject(httpGet(library.getData().getString("url"), "UTF-8"));
        for (int i = 0; i < d.getJSONArray("lent").length(); i++) {
            JSONObject l = d.getJSONArray("lent").getJSONObject(i);
            LentItem lentItem = new LentItem();
            for (Iterator iter = l.keys(); iter.hasNext(); ) {
                String key = (String) iter.next();
                lentItem.set(key, l.getString(key));
            }
            lent.add(lentItem);
        }
        for (int i = 0; i < d.getJSONArray("reservations").length(); i++) {
            JSONObject l = d.getJSONArray("reservations").getJSONObject(i);
            ReservedItem resItem = new ReservedItem();
            for (Iterator iter = l.keys(); iter.hasNext(); ) {
                String key = (String) iter.next();
                resItem.set(key, l.getString(key));
            }
            reservations.add(resItem);
        }
    } catch (NotReachableException e) {
        for (int i = 0; i < 6; i++) {
            LentItem lentItem = new LentItem();
            lentItem.setAuthor("Max Mustermann");
            lentItem.setTitle("Lorem Ipsum");
            lentItem.setStatus("hier ist der Status");
            lentItem.setDeadline(new LocalDate(1442564454547L));
            lentItem.setRenewable(true);
            lentItem.setProlongData("foo");
            lentItem.setHomeBranch("Meine Zweigstelle");
            lentItem.setLendingBranch("Ausleihzweigstelle");
            lentItem.setBarcode("Barcode");
            lent.add(lentItem);
            ReservedItem reservedItem = new ReservedItem();
            reservedItem.setAuthor("Max Mustermann");
            reservedItem.setTitle("Lorem Ipsum");
            reservedItem.setReadyDate(LocalDate.now());
            reservations.add(reservedItem);
        }
    }
    data.setLent(lent);
    data.setReservations(reservations);
    return data;
}
Also used : JSONObject(org.json.JSONObject) AccountData(de.geeksfactory.opacclient.objects.AccountData) NotReachableException(de.geeksfactory.opacclient.networking.NotReachableException) ArrayList(java.util.ArrayList) Iterator(java.util.Iterator) ReservedItem(de.geeksfactory.opacclient.objects.ReservedItem) LentItem(de.geeksfactory.opacclient.objects.LentItem) LocalDate(org.joda.time.LocalDate)

Example 8 with NotReachableException

use of de.geeksfactory.opacclient.networking.NotReachableException in project opacclient by opacapp.

the class Zones method login.

private Document login(Account acc) throws IOException, OpacErrorException {
    String html = httpGet(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;
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) Pattern(java.util.regex.Pattern) NotReachableException(de.geeksfactory.opacclient.networking.NotReachableException) Matcher(java.util.regex.Matcher) Element(org.jsoup.nodes.Element) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) Document(org.jsoup.nodes.Document) BasicNameValuePair(org.apache.http.message.BasicNameValuePair)

Example 9 with NotReachableException

use of de.geeksfactory.opacclient.networking.NotReachableException 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 10 with NotReachableException

use of de.geeksfactory.opacclient.networking.NotReachableException in project opacclient by opacapp.

the class ApacheBaseApi method httpPost.

/**
 * Perform a HTTP POST request to a given URL
 *
 * @param url           URL to fetch
 * @param data          POST data to send
 * @param encoding      Expected encoding of the response body
 * @param ignore_errors If true, status codes above 400 do not raise an exception
 * @param cookieStore   If set, the given cookieStore is used instead of the built-in one.
 * @return Answer content
 * @throws NotReachableException Thrown when server returns a HTTP status code greater or equal
 *                               than 400.
 */
public String httpPost(String url, HttpEntity data, String encoding, boolean ignore_errors, CookieStore cookieStore) throws IOException {
    HttpPost httppost = new HttpPost(cleanUrl(url));
    httppost.setEntity(data);
    httppost.setHeader("Accept", "*/*");
    HttpResponse response;
    String html;
    try {
        if (cookieStore != null) {
            // Create local HTTP context
            HttpContext localContext = new BasicHttpContext();
            // Bind custom cookie store to the local context
            localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
            response = http_client.execute(httppost, localContext);
        } else {
            response = http_client.execute(httppost);
        }
        if (!ignore_errors && response.getStatusLine().getStatusCode() >= 400) {
            throw new NotReachableException(response.getStatusLine().getReasonPhrase());
        }
        html = convertStreamToString(response.getEntity().getContent(), encoding);
        HttpUtils.consume(response.getEntity());
    } catch (javax.net.ssl.SSLPeerUnverifiedException e) {
        logHttpError(e);
        throw new SSLSecurityException(e.getMessage());
    } catch (javax.net.ssl.SSLException e) {
        // aborted/interrupted handshake/connection
        if (e.getMessage().contains("timed out") || e.getMessage().contains("reset by")) {
            logHttpError(e);
            throw new NotReachableException(e.getMessage());
        } else {
            logHttpError(e);
            throw new SSLSecurityException(e.getMessage());
        }
    } catch (InterruptedIOException e) {
        logHttpError(e);
        throw new NotReachableException(e.getMessage());
    } catch (UnknownHostException e) {
        throw new NotReachableException(e.getMessage());
    } catch (IOException e) {
        if (e.getMessage() != null && e.getMessage().contains("Request aborted")) {
            logHttpError(e);
            throw new NotReachableException(e.getMessage());
        } else {
            throw e;
        }
    }
    return html;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) InterruptedIOException(java.io.InterruptedIOException) UnknownHostException(java.net.UnknownHostException) NotReachableException(de.geeksfactory.opacclient.networking.NotReachableException) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) SSLSecurityException(de.geeksfactory.opacclient.networking.SSLSecurityException) HttpResponse(org.apache.http.HttpResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException)

Aggregations

NotReachableException (de.geeksfactory.opacclient.networking.NotReachableException)18 Element (org.jsoup.nodes.Element)11 IOException (java.io.IOException)10 Document (org.jsoup.nodes.Document)10 ArrayList (java.util.ArrayList)8 SSLSecurityException (de.geeksfactory.opacclient.networking.SSLSecurityException)7 Matcher (java.util.regex.Matcher)7 Pattern (java.util.regex.Pattern)7 InterruptedIOException (java.io.InterruptedIOException)6 Elements (org.jsoup.select.Elements)6 HttpResponse (org.apache.http.HttpResponse)5 AccountData (de.geeksfactory.opacclient.objects.AccountData)3 LentItem (de.geeksfactory.opacclient.objects.LentItem)3 ReservedItem (de.geeksfactory.opacclient.objects.ReservedItem)3 SearchRequestResult (de.geeksfactory.opacclient.objects.SearchRequestResult)3 SearchResult (de.geeksfactory.opacclient.objects.SearchResult)3 DropdownSearchField (de.geeksfactory.opacclient.searchfields.DropdownSearchField)3 SearchField (de.geeksfactory.opacclient.searchfields.SearchField)3 TextSearchField (de.geeksfactory.opacclient.searchfields.TextSearchField)3 UnknownHostException (java.net.UnknownHostException)3