Search in sources :

Example 41 with ResourceException

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();
    }
}
Also used : JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) Representation(org.restlet.representation.Representation) JsonRepresentation(org.restlet.ext.json.JsonRepresentation) TextMatch(org.opensextant.extraction.TextMatch) IOException(java.io.IOException) JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) StringWriter(java.io.StringWriter) ClientResource(org.restlet.resource.ClientResource) JSONObject(org.json.JSONObject) ResourceException(org.restlet.resource.ResourceException) JsonRepresentation(org.restlet.ext.json.JsonRepresentation)

Example 42 with ResourceException

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);
    }
}
Also used : ResourceException(org.restlet.resource.ResourceException) Date(java.util.Date) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) SolrException(org.apache.solr.common.SolrException) ResourceException(org.restlet.resource.ResourceException)

Example 43 with ResourceException

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
}
Also used : NamedList(org.apache.solr.common.util.NamedList) NamedList(org.apache.solr.common.util.NamedList) List(java.util.List) ResourceException(org.restlet.resource.ResourceException) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 44 with ResourceException

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);
        }
    }
}
Also used : SolrRequestInfo(org.apache.solr.request.SolrRequestInfo) ResourceException(org.restlet.resource.ResourceException) ModifiableSolrParams(org.apache.solr.common.params.ModifiableSolrParams)

Aggregations

ResourceException (org.restlet.resource.ResourceException)44 Representation (org.restlet.representation.Representation)15 IOException (java.io.IOException)13 Reference (org.restlet.data.Reference)8 Writer (java.io.Writer)7 WriterRepresentation (org.restlet.representation.WriterRepresentation)7 ArrayList (java.util.ArrayList)6 Response (org.restlet.Response)6 StringRepresentation (org.restlet.representation.StringRepresentation)6 EmptyRepresentation (org.restlet.representation.EmptyRepresentation)5 EntitlementException (com.sun.identity.entitlement.EntitlementException)4 HashMap (java.util.HashMap)4 Map (java.util.Map)4 EntityReference (org.qi4j.api.entity.EntityReference)4 EntityTypeNotFoundException (org.qi4j.api.unitofwork.EntityTypeNotFoundException)4 NoSuchEntityException (org.qi4j.api.unitofwork.NoSuchEntityException)4 Form (org.restlet.data.Form)4 MediaType (org.restlet.data.MediaType)4 SSOException (com.iplanet.sso.SSOException)3 IdRepoException (com.sun.identity.idm.IdRepoException)3