use of org.restlet.resource.ResourceException in project Xponents by OpenSextant.
the class XlayerClient method process.
/**
*
* @param text
* @return
* @throws IOException
* @throws JSONException
*/
public List<TextMatch> process(String docid, String text) throws IOException, JSONException {
ClientResource client = new ClientResource(serviceContext, serviceURI);
org.json.JSONObject content = new JSONObject();
content.put("text", text);
content.put("docid", docid);
content.put("features", "places,coordinates,countries,persons,orgs,reverse-geocode");
/* Coordinates mainly are XY locations; Reverse Geocode them to find what country the location resides */
StringWriter data = new StringWriter();
try {
Representation repr = new JsonRepresentation(content.toString());
repr.setCharacterSet(CharacterSet.UTF_8);
//log.debug("CLIENT {} {}", serviceAddress, client);
// Process and read response fully.
Representation response = client.post(repr, MediaType.APPLICATION_JSON);
response.write(data);
response.exhaust();
response.release();
JSONObject json = new JSONObject(data.toString());
log.debug("POST: response {}", json.toString(2));
JSONObject meta = json.getJSONObject("response");
JSONArray annots = json.getJSONArray("annotations");
List<TextMatch> matches = new ArrayList<TextMatch>();
for (int x = 0; x < annots.length(); ++x) {
Object m = annots.get(x);
matches.add(Transforms.parseAnnotation(m));
}
return matches;
} catch (ResourceException restErr) {
if (restErr.getCause() instanceof IOException) {
throw (IOException) restErr.getCause();
} else {
throw restErr;
}
} catch (java.net.SocketException err) {
// This never happens. Restlet wraps everything.
throw err;
} finally {
client.release();
}
}
use of org.restlet.resource.ResourceException in project lucene-solr by apache.
the class ManagedResource method storeManagedData.
/**
* Persists managed data to the configured storage IO as a JSON object.
*/
public synchronized void storeManagedData(Object managedData) {
Map<String, Object> toStore = buildMapToStore(managedData);
String resourceId = getResourceId();
try {
storage.store(resourceId, toStore);
// keep track that the managed data has been updated
lastUpdateSinceInitialization = new Date();
} catch (Throwable storeErr) {
// if we've successfully initialized before
if (initializedOn != null) {
try {
reloadFromStorage();
} catch (Exception reloadExc) {
// note: the data we're managing now remains in a dubious state
// however the text analysis component remains unaffected
// (at least until core reload)
log.error("Failed to load data from storage due to: " + reloadExc);
}
}
String errMsg = String.format(Locale.ROOT, "Failed to store data for %s due to: %s", resourceId, storeErr.toString());
log.error(errMsg, storeErr);
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, errMsg, storeErr);
}
}
use of org.restlet.resource.ResourceException in project lucene-solr by apache.
the class ManagedResource method doPut.
/**
* Applies changes to initArgs or managed data.
*/
@SuppressWarnings("unchecked")
public synchronized void doPut(BaseSolrResource endpoint, Representation entity, Object json) {
log.info("Processing update to {}: {} is a " + json.getClass().getName(), getResourceId(), json);
boolean updatedInitArgs = false;
Object managedData = null;
if (json instanceof Map) {
// hmmmm ... not sure how flexible we want to be here?
Map<String, Object> jsonMap = (Map<String, Object>) json;
if (jsonMap.containsKey(INIT_ARGS_JSON_FIELD) || jsonMap.containsKey(MANAGED_JSON_LIST_FIELD) || jsonMap.containsKey(MANAGED_JSON_MAP_FIELD)) {
Map<String, Object> initArgsMap = (Map<String, Object>) jsonMap.get(INIT_ARGS_JSON_FIELD);
updatedInitArgs = updateInitArgs(new NamedList<>(initArgsMap));
if (jsonMap.containsKey(MANAGED_JSON_LIST_FIELD)) {
managedData = jsonMap.get(MANAGED_JSON_LIST_FIELD);
} else if (jsonMap.containsKey(MANAGED_JSON_MAP_FIELD)) {
managedData = jsonMap.get(MANAGED_JSON_MAP_FIELD);
}
} else {
managedData = jsonMap;
}
} else if (json instanceof List) {
managedData = json;
} else {
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Unsupported update format " + json.getClass().getName());
}
Object updated = null;
if (managedData != null) {
updated = applyUpdatesToManagedData(managedData);
}
if (updatedInitArgs || updated != null) {
storeManagedData(updated);
}
// PUT just returns success status code with an empty body
}
use of org.restlet.resource.ResourceException in project lucene-solr by apache.
the class BaseSolrResource method doInit.
/**
* Pulls the SolrQueryRequest constructed in SolrDispatchFilter
* from the SolrRequestInfo thread local, then gets the SolrCore
* and IndexSchema and sets up the response.
* writer.
* <p>
* If an error occurs during initialization, setExisting(false) is
* called and an error status code and message is set; in this case,
* Restlet will not continue servicing the request (by calling the
* method annotated to associate it with GET, etc., but rather will
* send an error response.
*/
@Override
public void doInit() throws ResourceException {
super.doInit();
// Turn off content negotiation for now
setNegotiated(false);
if (isExisting()) {
try {
SolrRequestInfo solrRequestInfo = SolrRequestInfo.getRequestInfo();
if (null == solrRequestInfo) {
final String message = "No handler or core found in " + getRequest().getOriginalRef().getPath();
doError(Status.CLIENT_ERROR_BAD_REQUEST, message);
setExisting(false);
} else {
solrRequest = solrRequestInfo.getReq();
if (null == solrRequest) {
final String message = "No handler or core found in " + getRequest().getOriginalRef().getPath();
doError(Status.CLIENT_ERROR_BAD_REQUEST, message);
setExisting(false);
} else {
solrResponse = solrRequestInfo.getRsp();
solrCore = solrRequest.getCore();
schema = solrRequest.getSchema();
String responseWriterName = solrRequest.getParams().get(CommonParams.WT);
if (null == responseWriterName) {
// Default to json writer
responseWriterName = JSON;
}
String indent = solrRequest.getParams().get("indent");
if (null == indent || !("off".equals(indent) || "false".equals(indent))) {
// indent by default
ModifiableSolrParams newParams = new ModifiableSolrParams(solrRequest.getParams());
newParams.remove(indent);
newParams.add("indent", "on");
solrRequest.setParams(newParams);
}
responseWriter = solrCore.getQueryResponseWriter(responseWriterName);
contentType = responseWriter.getContentType(solrRequest, solrResponse);
final String path = getRequest().getRootRef().getPath();
if (!RestManager.SCHEMA_BASE_PATH.equals(path)) {
// don't set webapp property on the request when context and core/collection are excluded
final int cutoffPoint = path.indexOf("/", 1);
final String firstPathElement = -1 == cutoffPoint ? path : path.substring(0, cutoffPoint);
// Context path
solrRequest.getContext().put("webapp", firstPathElement);
}
SolrCore.preDecorateResponse(solrRequest, solrResponse);
// client application can set a timeout for update requests
Object updateTimeoutSecsParam = getSolrRequest().getParams().get(UPDATE_TIMEOUT_SECS);
if (updateTimeoutSecsParam != null)
updateTimeoutSecs = (updateTimeoutSecsParam instanceof Number) ? ((Number) updateTimeoutSecsParam).intValue() : Integer.parseInt(updateTimeoutSecsParam.toString());
}
}
} catch (Throwable t) {
if (t instanceof OutOfMemoryError) {
throw (OutOfMemoryError) t;
}
setExisting(false);
throw new ResourceException(t);
}
}
}
Aggregations