]> git.basschouten.com Git - openhab-addons.git/blob
36c26c442995b592a86823024e6c8cce73faa6d6
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13
14 package org.openhab.binding.icalendar.internal.handler;
15
16 import static org.openhab.binding.icalendar.internal.ICalendarBindingConstants.HTTP_TIMEOUT_SECS;
17
18 import java.io.File;
19 import java.io.FileInputStream;
20 import java.io.FileOutputStream;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.net.URI;
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;
29
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;
45
46 /**
47  * The Job for pulling an update of a calendar. Fires
48  * {@link CalendarUpdateListener#onCalendarUpdated()} after successful update.
49  *
50  * @author Michael Wodniok - Initial contribution
51  * @author Michael Wodniok - Added better descriptions for some errors while
52  *         downloading calendar
53  */
54 @NonNullByDefault
55 class PullJob implements Runnable {
56     private static final String TMP_FILE_PREFIX = "icalendardld";
57
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;
65
66     /**
67      * Constructor of PullJob for creating a single pull of a calendar.
68      *
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.
76      */
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);
83         } else {
84             authentication = null;
85         }
86         this.destination = destination;
87         this.listener = listener;
88         this.maxSize = maxSize;
89     }
90
91     @Override
92     public void run() {
93         final Request request = httpClient.newRequest(sourceURI).followRedirects(true).method(HttpMethod.GET);
94         final Authentication.Result currentAuthentication = authentication;
95         if (currentAuthentication != null) {
96             currentAuthentication.apply(request);
97         }
98
99         final InputStreamResponseListener asyncListener = new InputStreamResponseListener();
100         request.send(asyncListener);
101
102         Response response;
103         try {
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());
108             return;
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());
112             return;
113         } catch (ExecutionException e1) {
114             logger.warn("Download of calendar failed.");
115             logger.debug("ExecutionException message is: {}", e1.getCause().getMessage());
116             return;
117         }
118
119         if (response.getStatus() != HttpStatus.OK_200) {
120             logger.warn("Response status for getting \"{}\" was {} instead of 200. Ignoring it.", sourceURI,
121                     response.getStatus());
122             return;
123         }
124
125         final String responseLength = response.getHeaders().get(HttpHeader.CONTENT_LENGTH);
126         if (responseLength != null) {
127             try {
128                 if (Integer.parseInt(responseLength) > maxSize) {
129                     logger.warn(
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());
133                     return;
134                 }
135             } catch (NumberFormatException e) {
136                 logger.debug(
137                         "While requesting calendar Content-Length was set, but is malformed. Falling back to read-loop.",
138                         e);
139             }
140         }
141
142         File tmpTargetFile;
143         try {
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());
147             return;
148         }
149
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) {
158                     logger.warn(
159                             "Calendar is too big (> {} bytes). Stopping receiving calendar. You may change the maximum calendar size in configuration, if appropriate.",
160                             maxSize);
161                     response.abort(new ResponseTooBigException());
162                     return;
163                 }
164                 tmpOutStream.write(buffer, 0, currentReadBytes);
165             }
166         } catch (IOException e) {
167             logger.warn("Not able to write temporary file with downloaded iCal. Error Message is: {}", e.getMessage());
168             return;
169         }
170
171         try (final FileInputStream tmpInput = new FileInputStream(tmpTargetFile)) {
172             AbstractPresentableCalendar.create(tmpInput);
173         } catch (IOException | CalendarException e) {
174             logger.warn(
175                     "Not able to read downloaded iCal. Validation failed or file not readable. Error message is: {}",
176                     e.getMessage());
177             return;
178         }
179
180         try {
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());
184             return;
185         }
186
187         try {
188             listener.onCalendarUpdated();
189         } catch (Exception e) {
190             logger.debug("An Exception was thrown while calling back", e);
191         }
192     }
193
194     /**
195      * Interface for calling back when the update succeed.
196      */
197     public static interface CalendarUpdateListener {
198         /**
199          * Callback when update was successful and result was placed onto target file.
200          */
201         public void onCalendarUpdated();
202     }
203
204     /**
205      * Exception for failure if size of the response is greater than allowed.
206      */
207     private static class ResponseTooBigException extends Exception {
208
209         /**
210          * The only local definition. Rest of implementation is taken from Exception or is default.
211          */
212         private static final long serialVersionUID = 7033851403473533793L;
213     }
214 }