1 package org
.argeo
.slc
.server
.client
;
3 import java
.io
.IOException
;
4 import java
.io
.InputStream
;
5 import java
.net
.HttpURLConnection
;
9 import javax
.xml
.transform
.stream
.StreamSource
;
11 import org
.apache
.commons
.io
.IOUtils
;
12 import org
.apache
.commons
.logging
.Log
;
13 import org
.apache
.commons
.logging
.LogFactory
;
14 import org
.argeo
.slc
.SlcException
;
15 import org
.springframework
.oxm
.Unmarshaller
;
16 import org
.springframework
.util
.Assert
;
18 public class SlcServerHttpClient
{
19 private final static Log log
= LogFactory
.getLog(SlcServerHttpClient
.class);
21 private Unmarshaller unmarshaller
;
22 private String baseUrl
;
24 private Long retryPeriod
= 1000l;
26 @SuppressWarnings(value
= { "unchecked" })
27 public <T
> T
callService(String path
, Map
<String
, String
> parameters
) {
29 return (T
) callServiceLowLevel(path
, parameters
);
30 } catch (Exception e
) {
31 throw new SlcException("Cannot call service " + path
+ " on "
36 @SuppressWarnings(value
= { "unchecked" })
37 public <T
> T
callServiceSafe(String path
, Map
<String
, String
> parameters
,
39 long begin
= System
.currentTimeMillis();
42 long duration
= System
.currentTimeMillis() - begin
;
43 while (duration
< timeout
) {
45 obj
= callServiceLowLevel(path
, parameters
);
46 } catch (IOException e
) {
47 if (log
.isTraceEnabled())
48 log
.trace("Exception when calling service " + path
49 + " on " + baseUrl
, e
);
57 Thread
.sleep(retryPeriod
);
58 } catch (InterruptedException e
) {
64 throw new SlcException(
69 + " did not return an answer after calling it safely for "
72 } catch (Exception e
) {
73 throw new SlcException(
74 "Unexpected exception when safely calling service " + path
75 + " on " + baseUrl
, e
);
79 protected Object
callServiceLowLevel(String path
,
80 Map
<String
, String
> parameters
) throws IOException
{
81 Assert
.notNull(baseUrl
, "base url");
82 InputStream in
= null;
84 URL url
= new URL(baseUrl
+ path
);
85 HttpURLConnection connection
= (HttpURLConnection
) url
87 if (parameters
!= null) {
88 for (String key
: parameters
.keySet()) {
89 connection
.addRequestProperty(key
, parameters
.get(key
));
95 in
= connection
.getInputStream();
96 StreamSource source
= new StreamSource(in
);
97 Object obj
= unmarshaller
.unmarshal(source
);
100 IOUtils
.closeQuietly(in
);
104 public void setUnmarshaller(Unmarshaller unmarshaller
) {
105 this.unmarshaller
= unmarshaller
;
108 public void setBaseUrl(String baseUrl
) {
109 this.baseUrl
= baseUrl
;
112 public Long
getRetryPeriod() {
116 /** Retry period in ms when accessing service safely. Default is 1000 ms. */
117 public void setRetryPeriod(Long retryPeriod
) {
118 this.retryPeriod
= retryPeriod
;