2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
14 package org.openhab.binding.icalendar.internal.handler;
16 import static org.openhab.binding.icalendar.internal.ICalendarBindingConstants.HTTP_TIMEOUT_SECS;
19 import java.io.FileInputStream;
20 import java.io.FileOutputStream;
21 import java.io.IOException;
22 import java.io.InputStream;
24 import java.nio.file.Files;
25 import java.nio.file.StandardCopyOption;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.TimeUnit;
28 import java.util.concurrent.TimeoutException;
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.eclipse.jetty.client.HttpClient;
33 import org.eclipse.jetty.client.api.Authentication;
34 import org.eclipse.jetty.client.api.Request;
35 import org.eclipse.jetty.client.api.Response;
36 import org.eclipse.jetty.client.util.BasicAuthentication;
37 import org.eclipse.jetty.client.util.InputStreamResponseListener;
38 import org.eclipse.jetty.http.HttpHeader;
39 import org.eclipse.jetty.http.HttpMethod;
40 import org.eclipse.jetty.http.HttpStatus;
41 import org.openhab.binding.icalendar.internal.logic.AbstractPresentableCalendar;
42 import org.openhab.binding.icalendar.internal.logic.CalendarException;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
47 * The Job for pulling an update of a calendar. Fires
48 * {@link CalendarUpdateListener#onCalendarUpdated()} after successful update.
50 * @author Michael Wodniok - Initial contribution
51 * @author Michael Wodniok - Added better descriptions for some errors while
52 * downloading calendar
55 class PullJob implements Runnable {
56 private final static String TMP_FILE_PREFIX = "icalendardld";
58 private final Authentication.@Nullable Result authentication;
59 private final File destination;
60 private final HttpClient httpClient;
61 private final CalendarUpdateListener listener;
62 private final Logger logger = LoggerFactory.getLogger(PullJob.class);
63 private final int maxSize;
64 private final URI sourceURI;
67 * Constructor of PullJob for creating a single pull of a calendar.
69 * @param httpClient A HttpClient for getting the source
70 * @param sourceURI The source as URI
71 * @param username Optional username for basic auth. Must be set together with a password.
72 * @param password Optional password for basic auth. Must be set together with an username.
73 * @param destination The destination the downloaded calendar should be saved to.
74 * @param maxSize The maximum size of the downloaded calendar in bytes.
75 * @param listener The listener that should be fired when update succeed.
77 public PullJob(HttpClient httpClient, URI sourceURI, @Nullable String username, @Nullable String password,
78 File destination, int maxSize, CalendarUpdateListener listener) {
79 this.httpClient = httpClient;
80 this.sourceURI = sourceURI;
81 if (username != null && password != null) {
82 authentication = new BasicAuthentication.BasicResult(this.sourceURI, username, password);
84 authentication = null;
86 this.destination = destination;
87 this.listener = listener;
88 this.maxSize = maxSize;
93 final Request request = httpClient.newRequest(sourceURI).followRedirects(true).method(HttpMethod.GET);
94 final Authentication.@Nullable Result currentAuthentication = authentication;
95 if (currentAuthentication != null) {
96 currentAuthentication.apply(request);
99 final InputStreamResponseListener asyncListener = new InputStreamResponseListener();
100 request.send(asyncListener);
104 response = asyncListener.get(HTTP_TIMEOUT_SECS, TimeUnit.SECONDS);
105 } catch (InterruptedException e1) {
106 logger.warn("Download of calendar was interrupted.");
107 logger.debug("InterruptedException message is: {}", e1.getMessage());
109 } catch (TimeoutException e1) {
110 logger.warn("Download of calendar timed out (waited too long for headers).");
111 logger.debug("TimeoutException message is: {}", e1.getMessage());
113 } catch (ExecutionException e1) {
114 logger.warn("Download of calendar failed.");
115 logger.debug("ExecutionException message is: {}", e1.getCause().getMessage());
119 if (response.getStatus() != HttpStatus.OK_200) {
120 logger.warn("Response status for getting \"{}\" was {} instead of 200. Ignoring it.", sourceURI,
121 response.getStatus());
125 final String responseLength = response.getHeaders().get(HttpHeader.CONTENT_LENGTH);
126 if (responseLength != null) {
128 if (Integer.parseInt(responseLength) > maxSize) {
130 "Calendar is too big ({} bytes > {} bytes), aborting request. You may change the maximum calendar size in configuration, if appropriate.",
131 responseLength, maxSize);
132 response.abort(new ResponseTooBigException());
135 } catch (NumberFormatException e) {
137 "While requesting calendar Content-Length was set, but is malformed. Falling back to read-loop.",
144 tmpTargetFile = File.createTempFile(TMP_FILE_PREFIX, null);
145 } catch (IOException e) {
146 logger.warn("Not able to create temporary file for downloading iCal. Error message is: {}", e.getMessage());
150 try (final FileOutputStream tmpOutStream = new FileOutputStream(tmpTargetFile);
151 final InputStream httpInputStream = asyncListener.getInputStream()) {
152 final byte[] buffer = new byte[1024];
153 int readBytesTotal = 0;
154 int currentReadBytes = -1;
155 while ((currentReadBytes = httpInputStream.read(buffer)) > -1) {
156 readBytesTotal += currentReadBytes;
157 if (readBytesTotal > maxSize) {
159 "Calendar is too big (> {} bytes). Stopping receiving calendar. You may change the maximum calendar size in configuration, if appropriate.",
161 response.abort(new ResponseTooBigException());
164 tmpOutStream.write(buffer, 0, currentReadBytes);
166 } catch (IOException e) {
167 logger.warn("Not able to write temporary file with downloaded iCal. Error Message is: {}", e.getMessage());
171 try (final FileInputStream tmpInput = new FileInputStream(tmpTargetFile)) {
172 AbstractPresentableCalendar.create(tmpInput);
173 } catch (IOException | CalendarException e) {
175 "Not able to read downloaded iCal. Validation failed or file not readable. Error message is: {}",
181 Files.move(tmpTargetFile.toPath(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING);
182 } catch (IOException e) {
183 logger.warn("Failed to replace iCal file. Error message is: {}", e.getMessage());
188 listener.onCalendarUpdated();
189 } catch (Exception e) {
190 logger.debug("An Exception was thrown while calling back", e);
195 * Interface for calling back when the update succeed.
197 public static interface CalendarUpdateListener {
199 * Callback when update was successful and result was placed onto target file.
201 public void onCalendarUpdated();
205 * Exception for failure if size of the response is greater than allowed.
207 private static class ResponseTooBigException extends Exception {
210 * The only local definition. Rest of implementation is taken from Exception or is default.
212 private static final long serialVersionUID = 7033851403473533793L;