View Javadoc
1   package com.srv4pos.server.api.seller;
2   
3   import com.srv4pos.commons.io.InputStreamConnectionWriter;
4   import com.srv4pos.server.api.infrastructure.EmptyConnectionWriter;
5   import com.srv4pos.server.api.infrastructure.HttpMethod;
6   import com.srv4pos.server.api.infrastructure.StringConnectionWriter;
7   import com.srv4pos.server.api.infrastructure.credentials.Credentials;
8   import com.srv4pos.server.api.infrastructure.exceptions.enums.ForbiddenErrorType;
9   import com.srv4pos.server.api.infrastructure.http.HttpHelper;
10  import com.srv4pos.server.api.infrastructure.http.Transport;
11  import com.srv4pos.server.api.infrastructure.picture.SellerPictureInfo;
12  import com.srv4pos.server.api.infrastructure.request.StreamResponse;
13  import com.srv4pos.server.api.infrastructure.request.StringResponse;
14  import flexjson.JSONDeserializer;
15  
16  import java.io.InputStream;
17  import java.net.URL;
18  import java.util.ArrayList;
19  import java.util.HashMap;
20  import java.util.List;
21  
22  import static com.srv4pos.server.api.infrastructure.EmptyConnectionWriter.EMPTY_CONNECTION_WRITER;
23  import static com.srv4pos.server.api.infrastructure.http.HttpHelper.CONTENT_TYPE_APPLICATION_JSON;
24  import static com.srv4pos.server.api.infrastructure.http.HttpHelper.CONTENT_TYPE_PNG;
25  import static com.srv4pos.server.api.infrastructure.http.HttpHelper.encodePictureFilename;
26  import static com.srv4pos.server.api.infrastructure.request.RequestHelper.requestStream;
27  import static com.srv4pos.server.api.infrastructure.request.RequestHelper.requestString;
28  import static com.srv4pos.server.api.infrastructure.request.RequestHelper.requestVoid;
29  import static java.lang.String.format;
30  
31  /**
32   * Exchange information for Seller entity.
33   * User: Kirill
34   * Date: 25.07.13 11:14
35   */
36  public class SellerService {
37      private URL url;
38      private Credentials credentials;
39      private Transport transport;
40  
41      /**
42       * Constructs the service.
43       *
44       * @param url         of the server
45       * @param credentials to work with the server
46       * @param transport   to know the method to reach the server
47       */
48      public SellerService(URL url, Credentials credentials, Transport transport) {
49          this.url = url;
50          this.credentials = credentials;
51          this.transport = transport;
52      }
53  
54      /**
55       * Get latest information about seller from the server.
56       *
57       * @param version put value from {@link #getThisVersion()}. if you don't have any {@link SellerInfo} instance, then pass null to return the data anyway
58       * @return null if not modified or fresh version of info
59       * @see SellerServiceSample
60       */
61      public SellerInfo get(Integer version) {
62          StringResponse response = requestString(
63                  credentials.getSellerId(),
64                  HttpMethod.GET,
65                  url,
66                  credentials.toAuthentication(),
67                  HttpHelper.integerToETag(version),
68                  null,
69                  EMPTY_CONNECTION_WRITER,
70                  CONTENT_TYPE_APPLICATION_JSON,
71                  transport
72          );
73          return response == null ? null : SellerInfo.fromJsonToSellerInfo(response.getContent());
74      }
75  
76      /**
77       * Gets {@link PublicSellerInfo} for seller. This method performs anonymously.
78       *
79       * @return {@code null} if not found or entity
80       * @see SellerServiceSample
81       */
82      public PublicSellerInfo getPublic() {
83          StringResponse response = requestString(
84                  format("sellers/%s", credentials.getSellerId()),
85                  HttpMethod.GET,
86                  url,
87                  null,
88                  null,
89                  null,
90                  EMPTY_CONNECTION_WRITER,
91                  CONTENT_TYPE_APPLICATION_JSON,
92                  transport
93          );
94          return response == null ? null : PublicSellerInfo.fromJsonToPublicSellerInfo(response.getContent());
95      }
96  
97      /**
98       * Send information about seller to the server to store it.
99       *
100      * @param sellerInfo the data
101      * @param version    put value from {@link #getThisVersion()}
102      * @throws com.srv4pos.server.api.exceptions.VersionConflictJsonException if server has newer data sent from other client before
103      * @see SellerServiceSample
104      */
105     public void put(int version, SellerInfo sellerInfo) {
106         requestVoid(
107                 credentials.getSellerId(),
108                 HttpMethod.PUT,
109                 url,
110                 credentials.toAuthentication(),
111                 HttpHelper.integerToETag(version),
112                 null,
113                 new StringConnectionWriter(sellerInfo.toJson()),
114                 CONTENT_TYPE_APPLICATION_JSON,
115                 transport
116         );
117     }
118 
119     /**
120      * Remove seller and all information that concerns seller.
121      *
122      * @param sellerId identifier of seller
123      */
124     public void remove(String sellerId) {
125         requestVoid(
126                 sellerId,
127                 HttpMethod.DELETE,
128                 url,
129                 credentials.toAuthentication(),
130                 null,
131                 null,
132                 EMPTY_CONNECTION_WRITER,
133                 CONTENT_TYPE_APPLICATION_JSON,
134                 transport);
135     }
136 
137     /**
138      * Returns list of entities which have publicAccess == true.
139      *
140      * @param firstResult when pagination starts or null
141      * @param maxResults  amount of items per page or null
142      * @param like        search string filter or null
143      * @param orderBy     field to order by, possible values are "identifier", "name", "vat"
144      * @param orderDesc   field to direction of ordering
145      * @return list of entities which exists on current seller or null if list of entities is not modified since version
146      */
147     public List<PublicSellerInfo> list(Integer firstResult,
148                                        Integer maxResults,
149                                        String like,
150                                        PublicSellerInfo.Fields orderBy,
151                                        Boolean orderDesc) {
152         HashMap<String, String> params = new HashMap<String, String>();
153         if (orderBy != null) {
154             params.put("orderBy", orderBy.name());
155         }
156         if (orderDesc != null) {
157             params.put("orderDesc", orderDesc.toString());
158         }
159         if (firstResult != null) {
160             params.put("firstResult", Integer.toString(firstResult));
161         }
162         if (maxResults != null) {
163             params.put("maxResults", Integer.toString(maxResults));
164         }
165         if (like != null) {
166             params.put("like", like);
167         }
168 
169         StringResponse response = requestString(
170                 "sellers",
171                 HttpMethod.GET,
172                 url,
173                 null,
174                 null,
175                 params,
176                 EMPTY_CONNECTION_WRITER,
177                 CONTENT_TYPE_APPLICATION_JSON,
178                 transport
179         );
180         return response == null ? null : (List<PublicSellerInfo>) PublicSellerInfo.fromJsonArrayToPublicSellerInfoes(response.getContent());
181     }
182 
183     /**
184      * Returns latest version of this seller.
185      *
186      * @return version number
187      * @see SellerServiceSample
188      */
189     public SellerVersion getThisVersion() {
190         return SellerVersion.fromJsonToSellerVersion(
191                 requestString(
192                         format("%s/version", credentials.getSellerId()),
193                         HttpMethod.GET,
194                         url,
195                         credentials.toAuthentication(),
196                         null,
197                         null,
198                         EMPTY_CONNECTION_WRITER,
199                         CONTENT_TYPE_APPLICATION_JSON,
200                         transport
201                 ).getContent()
202         );
203     }
204 
205     /**
206      * Returns latest version of this public seller.
207      *
208      * @param sellerId id of the seller
209      * @return version number
210      * @throws com.srv4pos.server.api.exceptions.ForbiddenJsonException see:
211      *                                                                  {@link ForbiddenErrorType#INSUFFICIENT_ACCESS_RIGHTS}
212      * @see SellerServiceSample
213      */
214     public SellerVersion getThisVersionPublic(String sellerId) {
215         return SellerVersion.fromJsonToSellerVersion(
216                 requestString(
217                         format("%s/version", sellerId),
218                         HttpMethod.GET,
219                         url,
220                         null,
221                         null,
222                         null,
223                         EMPTY_CONNECTION_WRITER,
224                         CONTENT_TYPE_APPLICATION_JSON,
225                         transport
226                 ).getContent()
227         );
228     }
229 
230     /**
231      * Gets an information about availability of local control units, expiration of activation.
232      *
233      * @return seller stats
234      */
235     public SellerStatsInfo getStats() {
236         return SellerStatsInfo.fromJsonToSellerStatsInfo(
237                 requestString(format("%s/stats",
238                         credentials.getSellerId()),
239                         HttpMethod.GET,
240                         url,
241                         credentials.toAuthentication(),
242                         null,
243                         null,
244                         EMPTY_CONNECTION_WRITER,
245                         CONTENT_TYPE_APPLICATION_JSON,
246                         transport).getContent());
247     }
248 
249     /**
250      * Returns list of seller pictures changes between two versions.
251      *
252      * @param versionFrom version from included
253      * @param versionTo   version to included
254      * @return list of items to be added, edited or deleted
255      * @see SellerServiceSample
256      */
257     public List<SellerPictureInfo> listDiffPicture(int versionFrom, int versionTo) {
258         StringResponse response = requestString(
259                 format("%s/seller-images-diff/%s/%s", credentials.getSellerId(), versionFrom, versionTo),
260                 HttpMethod.GET,
261                 url,
262                 credentials.toAuthentication(),
263                 null,
264                 null,
265                 EmptyConnectionWriter.EMPTY_CONNECTION_WRITER,
266                 HttpHelper.CONTENT_TYPE_APPLICATION_JSON,
267                 transport
268         );
269         return (List<SellerPictureInfo>) SellerPictureInfo.fromJsonArrayToSellerPictureInfoes(response.getContent());
270     }
271 
272     /**
273      * Returns body of the picture.
274      *
275      * @param version         picture version or null if fresh content needed
276      * @param pictureFilename just a normal windows filename according to {@link com.srv4pos.server.api.infrastructure.Constraints#WINDOWS_FILENAME_REGEX}
277      * @return body in bytes or null if not modified (if version parameter is not null and seller has the same version as specified)
278      * @throws com.srv4pos.server.api.exceptions.NotFoundJsonException          if image is not found
279      * @throws com.srv4pos.server.api.exceptions.ReferenceNotFoundJsonException if seller is not found
280      * @see SellerServiceSample
281      */
282     public InputStream getPicture(Integer version, String pictureFilename) {
283         final StreamResponse img = requestStream(
284                 formatPictureUrl(pictureFilename, null),
285                 HttpMethod.GET,
286                 url,
287                 credentials == null ? null : credentials.toAuthentication(),
288                 HttpHelper.integerToETag(version),
289                 null,
290                 EmptyConnectionWriter.EMPTY_CONNECTION_WRITER,
291                 CONTENT_TYPE_PNG,
292                 transport
293         );
294         return img == null ? null : img.getContent();
295     }
296 
297     /**
298      * Returns list of picture relative paths .
299      *
300      * @param version picture version or null if fresh content needed
301      * @return list of paths or null if not modified (if version parameter is not null and seller has the same version as specified)
302      * @throws com.srv4pos.server.api.exceptions.ReferenceNotFoundJsonException if seller is not found
303      * @see SellerServiceSample
304      */
305     public List<String> getPicturePath(Integer version) {
306         final StringResponse response = requestString(
307                 format("%s/images", credentials.getSellerId()),
308                 HttpMethod.GET,
309                 url,
310                 credentials.toAuthentication(),
311                 HttpHelper.integerToETag(version),
312                 null,
313                 EmptyConnectionWriter.EMPTY_CONNECTION_WRITER,
314                 CONTENT_TYPE_APPLICATION_JSON,
315                 transport
316         );
317 
318         return new JSONDeserializer<List<String>>().use("values", String.class).deserialize(response.getContent());
319     }
320 
321     /**
322      * Returns body of the picture for particular version number.
323      *
324      * @param pictureVersion  particular version of picture
325      * @param pictureFilename just a normal windows filename according to {@link com.srv4pos.server.api.infrastructure.Constraints#WINDOWS_FILENAME_REGEX}
326      * @return body of the picture
327      * @throws com.srv4pos.server.api.exceptions.NotFoundJsonException          if image is not found
328      * @throws com.srv4pos.server.api.exceptions.ReferenceNotFoundJsonException if seller is not found
329      * @see SellerServiceSample
330      */
331     public InputStream getPictureFromHistory(Integer pictureVersion, String pictureFilename) {
332         final StreamResponse img = requestStream(
333                 formatPictureUrl(pictureFilename, pictureVersion),
334                 HttpMethod.GET,
335                 url,
336                 credentials == null ? null : credentials.toAuthentication(),
337                 null,
338                 null,
339                 EmptyConnectionWriter.EMPTY_CONNECTION_WRITER,
340                 HttpHelper.CONTENT_TYPE_PNG,
341                 transport
342         );
343         return img == null ? null : img.getContent();
344     }
345 
346     /**
347      * Send picture to the server.
348      *
349      * @param version         expected latest version of seller
350      * @param pictureFilename picture filename. must match to {@link com.srv4pos.server.api.infrastructure.Constraints#WINDOWS_FILENAME_REGEX}
351      * @param picture         body of the picture. method doesn't close the stream
352      * @param contentType     content type of the image
353      * @throws com.srv4pos.server.api.exceptions.ReferenceNotFoundJsonException if seller is not found
354      * @throws com.srv4pos.server.api.exceptions.VersionConflictJsonException   if version doesn't match to seller version
355      * @see SellerServiceSample
356      */
357     public void putPicture(int version, String pictureFilename, InputStream picture, String contentType) {
358         requestVoid(
359                 formatPictureUrl(pictureFilename, null),
360                 HttpMethod.PUT,
361                 url,
362                 credentials.toAuthentication(),
363                 HttpHelper.integerToETag(version),
364                 null,
365                 new InputStreamConnectionWriter(picture),
366                 contentType,
367                 transport
368         );
369     }
370 
371     private String formatPictureUrl(String pictureFilename, Integer version) {
372         final String v = version == null ? "current" : version.toString();
373         return format("%s/images/%s/%s", credentials.getSellerId(), v, encodePictureFilename(pictureFilename));
374     }
375 
376     /**
377      * Deletes specified picture.
378      *
379      * @param version         version of seller, if mismatch {@link com.srv4pos.server.api.exceptions.VersionConflictJsonException} will be thrown
380      * @param pictureFilename picture filename. must match to {@link com.srv4pos.server.api.infrastructure.Constraints#WINDOWS_FILENAME_REGEX}
381      * @throws com.srv4pos.server.api.exceptions.ReferenceNotFoundJsonException if seller is not found
382      * @throws com.srv4pos.server.api.exceptions.VersionConflictJsonException   if version doesn't match to seller version
383      * @see SellerServiceSample
384      */
385     public void deletePicture(int version, String pictureFilename) {
386         requestVoid(
387                 formatPictureUrl(pictureFilename, null),
388                 HttpMethod.DELETE,
389                 url,
390                 credentials.toAuthentication(),
391                 HttpHelper.integerToETag(version),
392                 null,
393                 EmptyConnectionWriter.EMPTY_CONNECTION_WRITER,
394                 HttpHelper.CONTENT_TYPE_APPLICATION_JSON,
395                 transport
396         );
397     }
398 
399     /**
400      * Gets list of seller modifications.
401      *
402      * @param versionFrom version from included
403      * @param versionTo   version to included
404      * @param orderDesc   field to direction of ordering
405      * @return list of items to be added, edited or deleted
406      */
407     public List<SellerModificationInfo> getModifications(int versionFrom,
408                                                          int versionTo,
409                                                          Boolean orderDesc) {
410         HashMap<String, String> params = new HashMap<String, String>();
411 
412         if (orderDesc != null) {
413             params.put("orderDesc", orderDesc.toString());
414         }
415 
416         params.put("from", Integer.toString(versionFrom));
417         params.put("to", Integer.toString(versionTo));
418 
419         StringResponse response = requestString(
420                 format("%s/modifications", credentials.getSellerId()),
421                 HttpMethod.GET,
422                 url,
423                 credentials.toAuthentication(),
424                 null,
425                 params,
426                 EMPTY_CONNECTION_WRITER,
427                 CONTENT_TYPE_APPLICATION_JSON,
428                 transport
429         );
430 
431         if (response == null) {
432             return null;
433         }
434 
435         List<SellerModificationInfo> sellerModificationInfoes = new ArrayList<SellerModificationInfo>();
436 
437         for (SellerModificationInternalInfo sellerModificationInternalInfo :
438                 SellerModificationInternalInfo.fromJsonArrayToSellerModificationInternalInfoes(response.getContent())) {
439             sellerModificationInfoes.add(sellerModificationInternalInfo.toSellerModificationInfo());
440         }
441 
442         return sellerModificationInfoes;
443     }
444 }