source: vlo/branches/vlo-3.1/vlo-web-app/src/main/java/eu/clarin/cmdi/vlo/service/handle/impl/HandleRestApiClient.java @ 6029

Last change on this file since 6029 was 6029, checked in by Twan Goosen, 9 years ago

merged changes from trunk

File size: 5.5 KB
Line 
1/*
2 * Copyright (C) 2014 CLARIN
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 */
17package eu.clarin.cmdi.vlo.service.handle.impl;
18
19import com.sun.jersey.api.client.Client;
20import com.sun.jersey.api.client.ClientHandlerException;
21import com.sun.jersey.api.client.ClientResponse;
22import com.sun.jersey.api.client.UniformInterfaceException;
23import com.sun.jersey.api.client.WebResource;
24import eu.clarin.cmdi.vlo.service.handle.HandleClient;
25import javax.ws.rs.core.MediaType;
26import org.apache.wicket.ajax.json.JSONArray;
27import org.apache.wicket.ajax.json.JSONException;
28import org.apache.wicket.ajax.json.JSONObject;
29import org.slf4j.Logger;
30import org.slf4j.LoggerFactory;
31
32/**
33 * Service that connects to the handle.net REST API and retrieves the URL for a
34 * given handle.
35 *
36 * Consider re-implementing using the handle API
37 *
38 * @author twagoo
39 */
40public class HandleRestApiClient implements HandleClient {
41
42    private final static Logger logger = LoggerFactory.getLogger(HandleRestApiClient.class);
43
44    private final String handleApiBaseUrl;
45
46    /**
47     * constructs a client with the default handle REST API base URL
48     */
49    public HandleRestApiClient() {
50        //TODO: get from config
51        this("http://hdl.handle.net/api/handles/");
52    }
53
54    /**
55     *
56     * @param handleApiBaseUrl base URL of the handle REST API (handle will be
57     * directly appended to this)
58     */
59    public HandleRestApiClient(String handleApiBaseUrl) {
60        this.handleApiBaseUrl = handleApiBaseUrl;
61    }
62
63    /**
64     *
65     * @param handle handle to resolve
66     * @return the ULR provided by the handle server or null if it could not be
67     * retrieved or is not available
68     */
69    @Override
70    public String getUrl(String handle) {
71        final String requestUrl = handleApiBaseUrl + handle;
72        logger.debug("Making request to {}", requestUrl);
73
74        final Client client = Client.create();
75        final WebResource resource = client.resource(requestUrl);
76
77        try {
78            final ClientResponse response = resource
79                    .accept(MediaType.APPLICATION_JSON_TYPE)
80                    .get(ClientResponse.class);
81
82            if (response.getClientResponseStatus() != ClientResponse.Status.OK) {
83                logger.error("Unexpected response status {} for {}", response.getClientResponseStatus(), requestUrl);
84            } else {
85                final String responseString = response.getEntity(String.class);
86                return getUrlFromJson(responseString);
87            }
88        } catch (UniformInterfaceException ex) {
89            logger.error("Could not communicate with Handle API", ex);
90        } catch (ClientHandlerException ex) {
91            logger.error("Could not communicate with Handle API", ex);
92        } catch (JSONException ex) {
93            logger.error("Could not parse Handle API response", ex);
94        }
95        return null;
96    }
97
98    public String getUrlFromJson(final String jsonString) throws JSONException {
99        // The handle API returns a JSON structure with a number of handle
100        // record fields. We are only interested in the value at
101        // values[x].data.value where values[x].type == 'URL'
102
103        final JSONObject jsonResponse = new JSONObject(jsonString);
104        final JSONArray valuesArray = jsonResponse.getJSONArray("values");
105        for (int i = 0; i < valuesArray.length(); i++) {
106            final JSONObject object = valuesArray.getJSONObject(i);
107            final String type = object.getString("type");
108            if ("URL".equals(type) && object.has("data")) {
109                final JSONObject data = object.getJSONObject("data");
110                if (data.has("value")) {
111                    // the field we were looking for
112                    return data.getString("value");
113                }
114            }
115        }
116        // no URL field??
117        logger.error("Handle API response did not incude a URL field");
118        return null;
119    }
120
121    /**
122     * {
123     * "responseCode":1, "handle":"1839/00-0000-0000-0000-0000-4", "values": [{
124     * "index":6, "type":"FILETIME", "data":"2014-03-25 08:35:11.0",
125     * "ttl":86400, "timestamp":"1970-01-01T00:00:00Z" }, { "index":5,
126     * "type":"CHECKSUM", "data":"696d818e19744f9f0290125e6385fa77",
127     * "ttl":86400, "timestamp":"1970-01-01T00:00:00Z" }, { "index":4,
128     * "type":"ONSITE", "data":"true", "ttl":86400,
129     * "timestamp":"1970-01-01T00:00:00Z" }, { "index":3, "type":"FILESIZE",
130     * "data":"6550", "ttl":86400, "timestamp":"1970-01-01T00:00:00Z"},
131     * {"index":2,"type":"CRAWLTIME","data":"2014-03-25
132     * 08:35:11.39","ttl":86400,"timestamp":"1970-01-01T00:00:00Z"},
133     * {"index":1,"type":"URL","data":"http://corpus1.mpi.nl/IMDI/metadata/IMDI.imdi","ttl":86400,"timestamp":"1970-01-01T00:00:00Z"},
134     * {"index":100,"type":"HS_ADMIN","data":{"format":"admin","value":{"handle":"0.NA/1839","index":200,"permissions":"010001110000"}},"ttl":86400,"timestamp":"1970-01-01T00:00:00Z"}
135     * ] }
136     */
137}
Note: See TracBrowser for help on using the repository browser.