Search in sources :

Example 1 with ConnectionException

use of org.collectionspace.chain.csp.persistence.services.connection.ConnectionException in project application by collectionspace.

the class WebReset method initialiseAll.

/*
	 * Vocab and Auth initialization is now done when the Services layer starts up -see JIRA issue DRYD-177
	 */
@Deprecated
private boolean initialiseAll(Storage storage, UIRequest request, String path, boolean modifyResponse) throws UIException {
    StringBuffer responseMessage = new StringBuffer();
    boolean initializationFailed = false;
    boolean initializationUnknown = false;
    try {
        logInitMessage(responseMessage, "Initializing vocab/auth entries...", modifyResponse);
        JSONObject myjs = new JSONObject();
        myjs.put("pageSize", "10");
        myjs.put("pageNum", "0");
        JSONObject data = storage.getPathsJSON("/", null);
        String[] paths = (String[]) data.get("listItems");
        for (String dir : paths) {
            try {
                if (this.spec.hasRecord(dir)) {
                    Record record = this.spec.getRecord(dir);
                    if (record.isType("authority") == true) {
                        for (Instance instance : record.getAllInstances()) {
                            if (instance.getCreateUnreferenced() || isInstanceReferenced(instance)) {
                                avi = new AuthoritiesVocabulariesInitialize(instance, populate, modifyResponse);
                                Option[] allOpts = instance.getAllOptions();
                                boolean creatingTerm = false;
                                try {
                                    if (avi.createIfMissingAuthority(storage, responseMessage, record, instance) == -1) {
                                        log.warn(String.format("The currently authenticated user does not have sufficient permission to determine if the '%s' authority/term-list is properly initialized.", instance.getID()));
                                        // since the logged in user doesn't have the correct perms, we can't verify that the authorities and term lists have been properly initialized
                                        initializationUnknown = true;
                                    } else {
                                        // 
                                        // Create the missing items.
                                        // 
                                        creatingTerm = true;
                                        avi.fillVocab(storage, record, instance, responseMessage, allOpts, true);
                                    }
                                } catch (UnderlyingStorageException e) {
                                    if (e.getStatus() == HttpStatus.SC_CONFLICT) {
                                        // This means the authority/vocabulary instance already exists in the backend, so move on to the next instance.
                                        log.warn(String.format("A short ID for the authority/vocabulary instance '%s' already exists.", instance.getID()));
                                        // Not a fatal error.
                                        continue;
                                    } else {
                                        throw e;
                                    }
                                } catch (Exception e) {
                                    if (avi.success() == false) {
                                        initializationFailed = true;
                                    }
                                    throw e;
                                }
                            } else {
                                logInitMessage(responseMessage, "Instance " + instance.getID() + " is defined by not referenced.", modifyResponse);
                            }
                        }
                    }
                }
            } catch (UnderlyingStorageException e) {
                // 
                if (e.getCause() instanceof ConnectionException) {
                    if (initializationFailed == true) {
                        modifyResponse = true;
                        if (e.getStatus() == HttpStatus.SC_UNAUTHORIZED || e.getStatus() == HttpStatus.SC_FORBIDDEN) {
                            logInitMessage(responseMessage, "\nSummary:\n\t*** ERROR *** CollectionSpace has not been properly initialized: The CollectionSpace administrator needs to login to the correct tenant and initialize the default term lists and authorities.\n\n", modifyResponse);
                        } else {
                            logInitMessage(responseMessage, "\nSummary:\n\t*** ERROR *** CollectionSpace has not been properly initialized: Ask the CollectionSpace administrator to login to the correct tenant and initialize the default term lists and authorities.\n\n", modifyResponse);
                        }
                    } else if (initializationUnknown == true) {
                        log.warn("The currently logged in user does not have the correct permissions to determin whether or not the default authorities and term lists have been properly initialized.");
                    } else {
                        // Should never get here unless we've got a bug in our code
                        throw e;
                    }
                }
                logException(e, responseMessage, modifyResponse);
                // no need to continue if the user hasn't authenticated or has incorrect permissions
                break;
            }
        }
    } catch (ExistException e) {
        logInitMessage(responseMessage, "ExistException " + e.getLocalizedMessage(), modifyResponse);
        throw new UIException("Existence problem", e);
    } catch (UnimplementedException e) {
        logInitMessage(responseMessage, "UnimplementedException " + e.getLocalizedMessage(), modifyResponse);
        throw new UIException("Unimplemented ", e);
    } catch (UnderlyingStorageException x) {
        if (x.getStatus() == HttpStatus.SC_UNAUTHORIZED) {
            initializationFailed = true;
            logInitMessage(responseMessage, "\n*** ERROR *** You need to be logged in to the correct tenant with the proper credentials before attempting to initialize the default term lists and authorities.\n", modifyResponse);
            logException(x, responseMessage, modifyResponse);
        } else {
            logInitMessage(responseMessage, "UnderlyingStorageException " + x.getLocalizedMessage(), modifyResponse);
            throw new UIException("Problem storing:" + x.getLocalizedMessage(), x.getStatus(), x.getUrl(), x);
        }
    } catch (JSONException e) {
        logInitMessage(responseMessage, "JSONException " + e.getLocalizedMessage(), modifyResponse);
        throw new UIException("Invalid JSON", e);
    }
    // 
    if (modifyResponse == true && request != null) {
        TTYOutputter tty = request.getTTYOutputter();
        tty.line(responseMessage.toString());
    }
    // report success if we didn't see a failure
    return !initializationFailed;
}
Also used : Instance(org.collectionspace.chain.csp.schema.Instance) JSONException(org.json.JSONException) AuthoritiesVocabulariesInitialize(org.collectionspace.chain.csp.webui.authorities.AuthoritiesVocabulariesInitialize) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) ExistException(org.collectionspace.csp.api.persistence.ExistException) UnimplementedException(org.collectionspace.csp.api.persistence.UnimplementedException) JSONException(org.json.JSONException) UIException(org.collectionspace.csp.api.ui.UIException) ExistException(org.collectionspace.csp.api.persistence.ExistException) ConnectionException(org.collectionspace.chain.csp.persistence.services.connection.ConnectionException) IOException(java.io.IOException) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) ConfigException(org.collectionspace.chain.csp.config.ConfigException) JSONObject(org.json.JSONObject) UIException(org.collectionspace.csp.api.ui.UIException) Record(org.collectionspace.chain.csp.schema.Record) Option(org.collectionspace.chain.csp.schema.Option) TTYOutputter(org.collectionspace.csp.api.ui.TTYOutputter) UnimplementedException(org.collectionspace.csp.api.persistence.UnimplementedException) ConnectionException(org.collectionspace.chain.csp.persistence.services.connection.ConnectionException)

Example 2 with ConnectionException

use of org.collectionspace.chain.csp.persistence.services.connection.ConnectionException in project application by collectionspace.

the class ServicesRelationStorage method getPathsJSON.

@Override
@SuppressWarnings("unchecked")
public JSONObject getPathsJSON(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache, String rootPath, JSONObject restrictions) throws ExistException, UnimplementedException, UnderlyingStorageException {
    JSONObject out = new JSONObject();
    Boolean isHierarchical = false;
    if (isPathType(rootPath, new String[] { "main" }, 0)) {
        extractPaths(rootPath, new String[] { "main" }, 0);
    } else if (isPathType(rootPath, new String[] { "hierarchical" }, 0)) {
        extractPaths(rootPath, new String[] { "hierarchical" }, 0);
        isHierarchical = true;
    }
    try {
        JSONObject moredata = new JSONObject();
        List<String> list = new ArrayList<String>();
        ReturnedDocument data = conn.getXMLDocument(RequestMethod.GET, "/relations?" + searchPath(restrictions), null, creds, cache);
        Document doc = data.getDocument();
        if (doc == null)
            throw new UnderlyingStorageException("Could not retrieve relation, missing relations_common");
        JSONObject pagination = new JSONObject();
        String xmlroot = "relations-common-list";
        List<Node> nodes = doc.getDocument().selectNodes("/" + xmlroot + "/*");
        for (Node node : nodes) {
            if ("relation-list-item".equals(node.getName())) {
                // if(post_filter(creds,cache,restrictions,node))
                list.add(node.selectSingleNode("csid").getText());
                if (isHierarchical) {
                    JSONObject hdata = new JSONObject();
                    Node subjectNode = node.selectSingleNode("subject");
                    Node objectNode = node.selectSingleNode("object");
                    hdata.put("subjecturi", subjectNode.selectSingleNode("uri").getText());
                    hdata.put("objecturi", objectNode.selectSingleNode("uri").getText());
                    hdata.put("subjectcsid", subjectNode.selectSingleNode("csid").getText());
                    hdata.put("objectcsid", objectNode.selectSingleNode("csid").getText());
                    findNameUnderNode(hdata, "subjectname", "subjectrefname", subjectNode);
                    findNameUnderNode(hdata, "objectname", "objectrefname", objectNode);
                    hdata.put("type", node.selectSingleNode("predicate").getText());
                    hdata.put("csid", node.selectSingleNode("csid").getText());
                    moredata.put(node.selectSingleNode("csid").getText(), hdata);
                }
            } else {
                pagination.put(node.getName(), node.getText());
            }
        }
        out.put("pagination", pagination);
        out.put("listItems", list.toArray(new String[0]));
        out.put("moredata", moredata);
        return out;
    } catch (ConnectionException e) {
        throw new UnderlyingStorageException("Could not retrieve relation" + e.getLocalizedMessage(), e.getStatus(), e.getUrl());
    } catch (JSONException e) {
        throw new UnderlyingStorageException("Could not retrieve relation", e);
    }
}
Also used : JSONObject(org.json.JSONObject) Node(org.dom4j.Node) ArrayList(java.util.ArrayList) JSONException(org.json.JSONException) Document(org.dom4j.Document) ReturnedMultipartDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument) ReturnedDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) ReturnedDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument) ConnectionException(org.collectionspace.chain.csp.persistence.services.connection.ConnectionException)

Example 3 with ConnectionException

use of org.collectionspace.chain.csp.persistence.services.connection.ConnectionException in project application by collectionspace.

the class ServicesRelationStorage method updateJSON.

@Override
public void updateJSON(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache, String filePath, JSONObject data, JSONObject restrictions) throws ExistException, UnimplementedException, UnderlyingStorageException {
    try {
        String[] parts = extractPaths(filePath, new String[] { "main" }, 1);
        Map<String, Document> in = new HashMap<String, Document>();
        Document datapath = dataToRelation(cache, parts[0], data).toDocument();
        in.put("relations_common", datapath);
        // log.info("UPDATE"+datapath.asXML());
        // log.info("UPDATE"+"/relations/"+parts[0]);
        ReturnedMultipartDocument out = conn.getMultipartXMLDocument(RequestMethod.PUT, "/relations/" + parts[0], in, creds, cache);
        if (out.getStatus() == 404)
            throw new ExistException("Not found");
        if (out.getStatus() > 299)
            throw new UnderlyingStorageException("Could not update relation", out.getStatus(), "/relations/" + parts[0]);
    } catch (ConnectionException e) {
        throw new UnderlyingStorageException("Could not update relation" + e.getLocalizedMessage(), e.getStatus(), e.getUrl(), e);
    } catch (JSONException e) {
        throw new UnderlyingStorageException("Could not retrieve data" + e.getLocalizedMessage(), e);
    }
}
Also used : ReturnedMultipartDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument) HashMap(java.util.HashMap) JSONException(org.json.JSONException) Document(org.dom4j.Document) ReturnedMultipartDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument) ReturnedDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument) ExistException(org.collectionspace.csp.api.persistence.ExistException) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) ConnectionException(org.collectionspace.chain.csp.persistence.services.connection.ConnectionException)

Example 4 with ConnectionException

use of org.collectionspace.chain.csp.persistence.services.connection.ConnectionException in project application by collectionspace.

the class ServicesRelationStorage method getPaths.

@Override
@SuppressWarnings("unchecked")
public String[] getPaths(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache, String rootPath, JSONObject restrictions) throws ExistException, UnimplementedException, UnderlyingStorageException {
    extractPaths(rootPath, new String[] { "main" }, 0);
    try {
        List<String> out = new ArrayList<String>();
        ReturnedDocument data = conn.getXMLDocument(RequestMethod.GET, "/relations/" + searchPath(restrictions), null, creds, cache);
        Document doc = data.getDocument();
        if (doc == null)
            throw new UnderlyingStorageException("Could not retrieve relation, missing relations_common");
        List<Node> objects = doc.getDocument().selectNodes("relations-common-list/relation-list-item");
        for (Node object : objects) {
            if (post_filter(creds, cache, restrictions, object))
                out.add(object.selectSingleNode("csid").getText());
        }
        return out.toArray(new String[0]);
    } catch (ConnectionException e) {
        throw new UnderlyingStorageException("Could not retrieve relation" + e.getLocalizedMessage(), e.getStatus(), e.getUrl(), e);
    } catch (JSONException e) {
        throw new UnderlyingStorageException("Could not retrieve relation" + e.getLocalizedMessage());
    }
}
Also used : Node(org.dom4j.Node) ArrayList(java.util.ArrayList) JSONException(org.json.JSONException) Document(org.dom4j.Document) ReturnedMultipartDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument) ReturnedDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) ReturnedDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument) ConnectionException(org.collectionspace.chain.csp.persistence.services.connection.ConnectionException)

Example 5 with ConnectionException

use of org.collectionspace.chain.csp.persistence.services.connection.ConnectionException in project application by collectionspace.

the class UserStorage method getPaths.

@Override
@SuppressWarnings("unchecked")
public String[] getPaths(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache, String rootPath, JSONObject restrictions) throws ExistException, UnimplementedException, UnderlyingStorageException {
    try {
        List<String> out = new ArrayList<String>();
        Iterator rit = restrictions.keys();
        StringBuffer args = new StringBuffer();
        while (rit.hasNext()) {
            String key = (String) rit.next();
            FieldSet fs = r.getFieldTopLevel(key);
            if (!(fs instanceof Field))
                continue;
            String filter = ((Field) fs).getServicesFilterParam();
            if (filter == null)
                continue;
            args.append('&');
            args.append(filter);
            args.append('=');
            args.append(URLEncoder.encode(restrictions.getString(key), "UTF-8"));
        }
        // pagination
        String tail = args.toString();
        String path = getRestrictedPath(r.getServicesURL(), restrictions, r.getServicesSearchKeyword(), tail, false, "");
        ReturnedDocument doc = conn.getXMLDocument(RequestMethod.GET, path, null, creds, cache);
        if (doc.getStatus() < 200 || doc.getStatus() > 399)
            throw new UnderlyingStorageException("Cannot retrieve account list", doc.getStatus(), path);
        Document list = doc.getDocument();
        List<Node> objects = list.selectNodes(r.getServicesListPath());
        for (Node object : objects) {
            List<Node> fields = object.selectNodes("*");
            String csid = object.selectSingleNode("csid").getText();
            for (Node field : fields) {
                if ("csid".equals(field.getName())) {
                    int idx = csid.lastIndexOf("/");
                    if (idx != -1)
                        csid = csid.substring(idx + 1);
                    out.add(csid);
                } else if ("uri".equals(field.getName())) {
                // Skip!
                } else {
                    String json_name = view_map.get(field.getName());
                    if (json_name != null) {
                        String value = field.getText();
                        // XXX hack to cope with multi values
                        if (value == null || "".equals(value)) {
                            List<Node> inners = field.selectNodes("*");
                            for (Node n : inners) {
                                value += n.getText();
                            }
                        }
                        setGleanedValue(cache, r.getServicesURL() + "/" + csid, json_name, value);
                    }
                }
            }
        }
        return out.toArray(new String[0]);
    } catch (ConnectionException e) {
        throw new UnderlyingStorageException("Service layer exception" + e.getLocalizedMessage(), e.getStatus(), e.getUrl(), e);
    } catch (UnsupportedEncodingException e) {
        throw new UnderlyingStorageException("Exception building query" + e.getLocalizedMessage(), e);
    } catch (JSONException e) {
        throw new UnderlyingStorageException("Exception building query" + e.getLocalizedMessage(), e);
    }
}
Also used : Node(org.dom4j.Node) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JSONException(org.json.JSONException) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) Document(org.dom4j.Document) ReturnedDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument) Field(org.collectionspace.chain.csp.schema.Field) FieldSet(org.collectionspace.chain.csp.schema.FieldSet) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) ReturnedDocument(org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument) ConnectionException(org.collectionspace.chain.csp.persistence.services.connection.ConnectionException)

Aggregations

ConnectionException (org.collectionspace.chain.csp.persistence.services.connection.ConnectionException)39 UnderlyingStorageException (org.collectionspace.csp.api.persistence.UnderlyingStorageException)37 JSONException (org.json.JSONException)28 ReturnedDocument (org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument)26 Document (org.dom4j.Document)24 JSONObject (org.json.JSONObject)23 ReturnedMultipartDocument (org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument)21 UnsupportedEncodingException (java.io.UnsupportedEncodingException)14 ArrayList (java.util.ArrayList)11 Node (org.dom4j.Node)11 FieldSet (org.collectionspace.chain.csp.schema.FieldSet)10 HashMap (java.util.HashMap)8 Field (org.collectionspace.chain.csp.schema.Field)8 Record (org.collectionspace.chain.csp.schema.Record)8 ExistException (org.collectionspace.csp.api.persistence.ExistException)8 UnimplementedException (org.collectionspace.csp.api.persistence.UnimplementedException)8 JSONArray (org.json.JSONArray)8 ReturnedURL (org.collectionspace.chain.csp.persistence.services.connection.ReturnedURL)6 Group (org.collectionspace.chain.csp.schema.Group)6 IOException (java.io.IOException)3