View Javadoc
1   package com.srv4pos.server.api.sale;
2   
3   import com.srv4pos.commons.io.InputStreamConnectionWriter;
4   import com.srv4pos.server.api.category.CategoryServiceSample;
5   import com.srv4pos.server.api.infrastructure.EmptyConnectionWriter;
6   import com.srv4pos.server.api.infrastructure.HttpMethod;
7   import com.srv4pos.server.api.infrastructure.IdentifierInfo;
8   import com.srv4pos.server.api.infrastructure.StringConnectionWriter;
9   import com.srv4pos.server.api.infrastructure.credentials.Credentials;
10  import com.srv4pos.server.api.infrastructure.http.HttpHelper;
11  import com.srv4pos.server.api.infrastructure.http.Transport;
12  import com.srv4pos.server.api.infrastructure.picture.SaleSlotPictureInfo;
13  import com.srv4pos.server.api.infrastructure.request.StreamResponse;
14  import com.srv4pos.server.api.infrastructure.request.StringResponse;
15  import flexjson.JSONDeserializer;
16  
17  import java.io.InputStream;
18  import java.net.URL;
19  import java.util.HashMap;
20  import java.util.List;
21  
22  import static com.srv4pos.server.api.infrastructure.http.HttpHelper.CONTENT_TYPE_APPLICATION_JSON;
23  import static com.srv4pos.server.api.infrastructure.http.HttpHelper.CONTENT_TYPE_PNG;
24  import static com.srv4pos.server.api.infrastructure.http.HttpHelper.encodePictureFilename;
25  import static com.srv4pos.server.api.infrastructure.request.RequestHelper.requestStream;
26  import static com.srv4pos.server.api.infrastructure.request.RequestHelper.requestString;
27  import static com.srv4pos.server.api.infrastructure.request.RequestHelper.requestVoid;
28  import static java.lang.String.format;
29  
30  /**
31   * Created by fasth on 17.09.2014.
32   */
33  public class SaleSlotService {
34      private URL url;
35      private Credentials credentials;
36      private Transport transport;
37  
38      /**
39       * Constructs the service.
40       *
41       * @param url         of the server
42       * @param credentials to work with the server
43       * @param transport   to know the method to reach the server
44       */
45      public SaleSlotService(URL url, Credentials credentials, Transport transport) {
46          this.url = url;
47          this.credentials = credentials;
48          this.transport = transport;
49      }
50  
51      /**
52       * Returns an entity.
53       *
54       * @param version    latest version of seller, may be null (if latest data needed)
55       * @param identifier identifies entity
56       * @return null if not modified since version or entity. if version is null then return value can not be null
57       * @throws com.srv4pos.server.api.exceptions.VersionConflictJsonException if version mismatch
58       * @throws com.srv4pos.server.api.exceptions.NotFoundJsonException        if entity is not found
59       */
60      public SaleSlotInfo get(Integer version, String identifier) {
61          StringResponse response = requestString(
62                  format("%s/sale-slots/%s", credentials.getSellerId(), identifier),
63                  HttpMethod.GET,
64                  url,
65                  credentials.toAuthentication(),
66                  HttpHelper.integerToETag(version),
67                  null,
68                  EmptyConnectionWriter.EMPTY_CONNECTION_WRITER,
69                  HttpHelper.CONTENT_TYPE_APPLICATION_JSON,
70                  transport
71          );
72          return response == null ? null : SaleSlotInfo.fromJsonToSaleSlotInfo(response.getContent());
73      }
74  
75      /**
76       * Put entity to the server.
77       *
78       * @param version      expected latest version of seller
79       * @param saleSlotInfo data to put
80       * @throws com.srv4pos.server.api.exceptions.VersionConflictJsonException if version mismatch
81       */
82      public void put(Integer version, SaleSlotInfo saleSlotInfo) {
83          requestVoid(
84                  format("%s/sale-slots/%s", credentials.getSellerId(), saleSlotInfo.getIdentifier()),
85                  HttpMethod.PUT,
86                  url,
87                  credentials.toAuthentication(),
88                  HttpHelper.integerToETag(version),
89                  null,
90                  new StringConnectionWriter(saleSlotInfo.toJson()),
91                  HttpHelper.CONTENT_TYPE_APPLICATION_JSON,
92                  transport
93          );
94      }
95  
96      /**
97       * Create entity on the server.
98       *
99       * @param version      expected latest version of seller
100      * @param saleSlotInfo data to put
101      * @return generated unique identifier
102      * @throws com.srv4pos.server.api.exceptions.VersionConflictJsonException if version mismatch
103      */
104     public IdentifierInfo create(Integer version, SaleSlotInfo saleSlotInfo) {
105         return IdentifierInfo.fromJsonToIdentifierInfo(
106                 requestString(
107                         format("%s/sale-slots", credentials.getSellerId()),
108                         HttpMethod.POST,
109                         url,
110                         credentials.toAuthentication(),
111                         HttpHelper.integerToETag(version),
112                         null,
113                         new StringConnectionWriter(saleSlotInfo.toJson()),
114                         HttpHelper.CONTENT_TYPE_APPLICATION_JSON,
115                         transport
116                 ).getContent()
117         );
118     }
119 
120     public void delete(int version, String identifier) {
121         requestVoid(
122                 credentials.getSellerId() + "/sale-slots/" + identifier,
123                 HttpMethod.DELETE,
124                 url,
125                 credentials.toAuthentication(),
126                 HttpHelper.integerToETag(version),
127                 null,
128                 EmptyConnectionWriter.EMPTY_CONNECTION_WRITER,
129                 HttpHelper.CONTENT_TYPE_APPLICATION_JSON,
130                 transport
131         );
132     }
133 
134     /**
135      * Returns list of entities.
136      *
137      * @param version version or null if fresh data required
138      * @return list of entities which exists on current seller or null if list of entities is not modified since version
139      */
140     public List<SaleSlotInfo> list(Integer version) {
141         return list(version, null, null, null, null, null);
142     }
143 
144     /**
145      * Returns list of entities.
146      *
147      * @param firstResult when pagination starts or null
148      * @param maxResults  amount of items per page or null
149      * @param like        search string filter or null
150      * @param orderBy     field to order by, possible values are "IDENTIFIER", "NAME", "VAT"
151      * @param orderDesc   field to direction of ordering
152      * @param version     version or null if fresh data required
153      * @return list of entities which exists on current seller or null if list of entities is not modified since version
154      */
155     public List<SaleSlotInfo> list(Integer version,
156                                    Integer firstResult,
157                                    Integer maxResults,
158                                    String like,
159                                    SaleSlotInfo.Fields orderBy,
160                                    Boolean orderDesc) {
161         HashMap<String, String> params = new HashMap<String, String>();
162         if (orderBy != null) {
163             params.put("orderBy", orderBy.name());
164         }
165         if (orderDesc != null) {
166             params.put("orderDesc", orderDesc.toString());
167         }
168         if (firstResult != null) {
169             params.put("firstResult", Integer.toString(firstResult));
170         }
171         if (maxResults != null) {
172             params.put("maxResults", Integer.toString(maxResults));
173         }
174         if (like != null) {
175             params.put("like", like);
176         }
177         StringResponse response = requestString(
178                 format("%s/sale-slots", credentials.getSellerId()),
179                 HttpMethod.GET,
180                 url,
181                 credentials.toAuthentication(),
182                 HttpHelper.integerToETag(version),
183                 params,
184                 EmptyConnectionWriter.EMPTY_CONNECTION_WRITER,
185                 HttpHelper.CONTENT_TYPE_APPLICATION_JSON,
186                 transport
187         );
188         return response == null ? null : (List<SaleSlotInfo>) SaleSlotInfo.fromJsonArrayToSaleSlotInfoes(response.getContent());
189     }
190 
191     /**
192      * Returns list of item changes between two versions.
193      *
194      * @param versionFrom version from included
195      * @param versionTo   version to included
196      * @return list of items to be added, edited or deleted ({@link com.srv4pos.server.api.sale.SaleSlotInfo#deleted} = true)
197      */
198     public List<SaleSlotInfo> listDiff(int versionFrom, int versionTo) {
199         StringResponse response = requestString(
200                 String.format("%s/sale-slots-diff/%s/%s", credentials.getSellerId(), versionFrom, versionTo),
201                 HttpMethod.GET,
202                 url,
203                 credentials.toAuthentication(),
204                 null,
205                 null,
206                 EmptyConnectionWriter.EMPTY_CONNECTION_WRITER,
207                 HttpHelper.CONTENT_TYPE_APPLICATION_JSON,
208                 transport
209         );
210         return (List<SaleSlotInfo>) SaleSlotInfo.fromJsonArrayToSaleSlotInfoes(response.getContent());
211     }
212 
213     /**
214      * Returns list of category pictures changes between two versions.
215      *
216      * @param versionFrom version from included
217      * @param versionTo   version to included
218      * @return list of items to be added, edited or deleted
219      * @see CategoryServiceSample
220      */
221     public List<SaleSlotPictureInfo> listDiffPicture(int versionFrom, int versionTo) {
222         StringResponse response = requestString(
223                 format("%s/saleslot-images-diff/%s/%s", credentials.getSellerId(), versionFrom, versionTo),
224                 HttpMethod.GET,
225                 url,
226                 credentials.toAuthentication(),
227                 null,
228                 null,
229                 EmptyConnectionWriter.EMPTY_CONNECTION_WRITER,
230                 HttpHelper.CONTENT_TYPE_APPLICATION_JSON,
231                 transport
232         );
233         return (List<SaleSlotPictureInfo>) SaleSlotPictureInfo.fromJsonArrayToSaleSlotPictureInfoes(response.getContent());
234     }
235 
236     /**
237      * Returns body of the picture.
238      *
239      * @param version            picture version or null if fresh content needed
240      * @param saleSlotIdentifier category identifier
241      * @param pictureFilename    just a normal windows filename according to {@link com.srv4pos.server.api.infrastructure.Constraints#WINDOWS_FILENAME_REGEX}
242      * @return body in bytes or null if not modified (if version parameter is not null and seller has the same version as specified)
243      * @throws com.srv4pos.server.api.exceptions.NotFoundJsonException          if image is not found
244      * @throws com.srv4pos.server.api.exceptions.ReferenceNotFoundJsonException if category is not found
245      * @see SaleSlotServiceSample
246      */
247     public InputStream getPicture(Integer version, String saleSlotIdentifier, String pictureFilename) {
248         final StreamResponse img = requestStream(
249                 formatPictureUrl(saleSlotIdentifier, pictureFilename, null),
250                 HttpMethod.GET,
251                 url,
252                 credentials == null ? null : credentials.toAuthentication(),
253                 HttpHelper.integerToETag(version),
254                 null,
255                 EmptyConnectionWriter.EMPTY_CONNECTION_WRITER,
256                 CONTENT_TYPE_PNG,
257                 transport
258         );
259         return img == null ? null : img.getContent();
260     }
261 
262     /**
263      * Returns list of picture relative paths .
264      *
265      * @param version            picture version or null if fresh content needed
266      * @param saleSlotIdentifier sale slot identifier
267      * @return list of paths or null if not modified (if version parameter is not null and seller has the same version as specified)
268      * @throws com.srv4pos.server.api.exceptions.ReferenceNotFoundJsonException if seller is not found
269      * @see com.srv4pos.server.api.category.CategoryServiceSample
270      */
271     public List<String> getPicturePath(Integer version, String saleSlotIdentifier) {
272         final StringResponse response = requestString(
273                 format("%s/sale-slots/%s/images", credentials.getSellerId(), saleSlotIdentifier),
274                 HttpMethod.GET,
275                 url,
276                 credentials.toAuthentication(),
277                 HttpHelper.integerToETag(version),
278                 null,
279                 EmptyConnectionWriter.EMPTY_CONNECTION_WRITER,
280                 CONTENT_TYPE_APPLICATION_JSON,
281                 transport
282         );
283 
284         return new JSONDeserializer<List<String>>().use("values", String.class).deserialize(response.getContent());
285     }
286 
287     /**
288      * Returns body of the picture for particular version number.
289      *
290      * @param pictureVersion     particular version of picture
291      * @param saleSlotIdentifier category identifier
292      * @param pictureFilename    just a normal windows filename according to {@link com.srv4pos.server.api.infrastructure.Constraints#WINDOWS_FILENAME_REGEX}
293      * @return body of the picture
294      * @throws com.srv4pos.server.api.exceptions.NotFoundJsonException          if image is not found
295      * @throws com.srv4pos.server.api.exceptions.ReferenceNotFoundJsonException if category is not found
296      * @see CategoryServiceSample
297      */
298     public InputStream getPictureFromHistory(Integer pictureVersion, String saleSlotIdentifier, String pictureFilename) {
299         final StreamResponse img = requestStream(
300                 formatPictureUrl(saleSlotIdentifier, pictureFilename, pictureVersion),
301                 HttpMethod.GET,
302                 url,
303                 credentials == null ? null : credentials.toAuthentication(),
304                 null,
305                 null,
306                 EmptyConnectionWriter.EMPTY_CONNECTION_WRITER,
307                 HttpHelper.CONTENT_TYPE_PNG,
308                 transport
309         );
310         return img == null ? null : img.getContent();
311     }
312 
313     /**
314      * Send picture to the server.
315      *
316      * @param version            expected latest version of seller
317      * @param saleSlotIdentifier identifier of the category. must match to {@link com.srv4pos.server.api.infrastructure.Constraints#WINDOWS_FILENAME_REGEX}
318      * @param pictureFilename    picture filename. must match to {@link com.srv4pos.server.api.infrastructure.Constraints#WINDOWS_FILENAME_REGEX}
319      * @param picture            body of the picture. method doesn't close the stream
320      * @param contentType        content type of the image
321      * @throws com.srv4pos.server.api.exceptions.ReferenceNotFoundJsonException if category is not found
322      * @throws com.srv4pos.server.api.exceptions.VersionConflictJsonException   if version doesn't match to seller version
323      * @see CategoryServiceSample
324      */
325     public void putPicture(int version, String saleSlotIdentifier, String pictureFilename, InputStream picture, String contentType) {
326         requestVoid(
327                 formatPictureUrl(saleSlotIdentifier, pictureFilename, null),
328                 HttpMethod.PUT,
329                 url,
330                 credentials.toAuthentication(),
331                 HttpHelper.integerToETag(version),
332                 null,
333                 new InputStreamConnectionWriter(picture),
334                 contentType,
335                 transport
336         );
337     }
338 
339     private String formatPictureUrl(String productIdentifier, String pictureFilename, Integer version) {
340         final String v = version == null ? "current" : version.toString();
341         return format("%s/sale-slots/%s/images/%s/%s", credentials.getSellerId(), productIdentifier, v, encodePictureFilename(pictureFilename));
342     }
343 
344     /**
345      * Deletes specified picture.
346      *
347      * @param version            version of seller, if mismatch {@link com.srv4pos.server.api.exceptions.VersionConflictJsonException} will be thrown
348      * @param saleSlotIdentifier identifier of the category. must match to {@link com.srv4pos.server.api.infrastructure.Constraints#WINDOWS_FILENAME_REGEX}
349      * @param pictureFilename    picture filename. must match to {@link com.srv4pos.server.api.infrastructure.Constraints#WINDOWS_FILENAME_REGEX}
350      * @throws com.srv4pos.server.api.exceptions.ReferenceNotFoundJsonException if category is not found
351      * @throws com.srv4pos.server.api.exceptions.VersionConflictJsonException   if version doesn't match to seller version
352      * @see CategoryServiceSample
353      */
354     public void deletePicture(int version, String saleSlotIdentifier, String pictureFilename) {
355         requestVoid(
356                 formatPictureUrl(saleSlotIdentifier, pictureFilename, null),
357                 HttpMethod.DELETE,
358                 url,
359                 credentials.toAuthentication(),
360                 HttpHelper.integerToETag(version),
361                 null,
362                 EmptyConnectionWriter.EMPTY_CONNECTION_WRITER,
363                 HttpHelper.CONTENT_TYPE_APPLICATION_JSON,
364                 transport
365         );
366     }
367 }