Search in sources :

Example 26 with UIException

use of org.collectionspace.csp.api.ui.UIException in project application by collectionspace.

the class WebReset method reset.

private void reset(Storage storage, UIRequest request, String path) throws UIException {
    // remember to log into the front end before trying to run this
    JSONObject data = new JSONObject();
    TTYOutputter tty = request.getTTYOutputter();
    // Temporary hack to reset db
    try {
        data = storage.getPathsJSON("/", null);
        String[] paths = (String[]) data.get("listItems");
        if (!path.equals("nodelete")) {
            // Delete existing records
            for (String dir : paths) {
                Record r = null;
                log.info(dir);
                if ("direct".equals(dir) || "relations".equals(dir))
                    continue;
                try {
                    r = this.spec.getRecord(dir);
                } catch (Exception e) {
                    continue;
                }
                if (r.isType("procedure")) {
                    if ("termlistitem".equals(dir) || "termlist".equals(dir))
                        continue;
                    // Nothing to do for the pseudo-records
                    if (r.isType("searchall")) {
                        continue;
                    }
                } else if (r.isType("authority")) {
                    continue;
                } else if (r.isType("record")) {
                    if (// Filter out self-renderers, etc
                    "hierarchy".equals(dir) || !r.isRealRecord())
                        continue;
                    log.info("S");
                } else if (r.isType("authorizationdata")) {
                    continue;
                } else if (r.isType("userdata")) {
                    continue;
                } else {
                    // ignore - have no idea what it is
                    continue;
                }
                // if("place".equals(dir) || "vocab".equals(dir) || "contact".equals(dir) || "location".equals(dir) || "person".equals(dir) || "organization".equals(dir) || "taxon".equals(dir)){
                // continue;
                // }
                // ignore authorization
                // if("rolePermission".equals(dir) || "accountrole".equals(dir) || "accountroles".equals(dir)  || "userperm".equals(dir)|| "permrole".equals(dir) || "permission".equals(dir) || "role".equals(dir)|| "userrole".equals(dir) || "users".equals(dir) ){
                // continue;
                // }
                // ignore other - tho we do need to clean these up
                // if("termlistitem".equals(dir) ||"termlist".equals(dir) || "reports".equals(dir) || "reporting".equals(dir) || "output".equals(dir)  )
                // continue;
                // // ignore other - tho we do need to clean these up
                // if("hierarchy".equals(dir) || "dimension".equals(dir) ||"structureddate".equals(dir)  ||"blobs".equals(dir) ||"relations".equals(dir) || "direct".equals(dir) || "id".equals(dir) )
                // continue;
                log.info("Deleteing data associated with : " + dir);
                tty.line("Deleteing data associated with : " + dir);
                JSONObject data2 = storage.getPathsJSON(dir, null);
                String[] paths2 = (String[]) data2.get("listItems");
                for (int i = 0; i < paths2.length; i++) {
                    tty.line("path : " + dir + "/" + paths2[i]);
                    try {
                        storage.deleteJSON(dir + "/" + paths2[i]);
                    } catch (UnimplementedException e) {
                        tty.line("UnimplementedException" + e);
                        tty.line("ux");
                    } catch (UnderlyingStorageException e) {
                        tty.line("UnderlyingStorageEception" + e);
                    }
                    tty.line("ok");
                    tty.flush();
                }
            }
        }
        log.info("Creating records and procedures: this might take some time, go get a cup of tea and be patient");
        tty.line("Creating records and procedures: this might take some time, go get a cup of tea and be patient");
        // Create records anew
        tty.line("Create records anew");
        String schedule = getResource("reset.txt");
        for (String line : schedule.split("\n")) {
            String[] parts = line.split(" +", 2);
            if (!parts[0].equals("")) {
                tty.line("Creating " + parts[0]);
                log.info("Creating " + parts[0]);
                storage.autocreateJSON(parts[0], getJSONResource(parts[1]), null);
                tty.flush();
            }
        }
        log.info("Delete existing vocab/auth entries");
        tty.line("Delete existing vocab/auth entries");
        // Delete existing vocab entries
        JSONObject myjs = new JSONObject();
        myjs.put("pageSize", "10");
        myjs.put("pageNum", "0");
        for (String dir : paths) {
            try {
                if (this.spec.hasRecord(dir)) {
                    if (dir.equalsIgnoreCase("vocab") && path.equalsIgnoreCase("keepVocabs")) {
                        // don't reset the term lists
                        continue;
                    }
                    Record r = this.spec.getRecord(dir);
                    if (r.isType("authority")) {
                        for (Instance n : r.getAllInstances()) {
                            String url = r.getID() + "/" + n.getTitleRef();
                            try {
                                storage.getPathsJSON(url, new JSONObject()).toString();
                            } catch (UnderlyingStorageException x) {
                                JSONObject fields = new JSONObject("{'displayName':'" + n.getTitle() + "','shortIdentifier':'" + n.getWebURL() + "'}");
                                String base = r.getID();
                                storage.autocreateJSON(base, fields, null);
                                log.info("Instance " + n.getID() + " Created");
                                tty.line("Instance " + n.getID() + " Created");
                            }
                            deletall(n, r, url, "Deleting " + url, storage, data, tty, myjs);
                        }
                    }
                }
            } catch (Exception e) {
                log.info("that was weird but probably not an issue " + e.getMessage());
            }
        }
        log.info("Creating Dummy data");
        tty.line("Creating Dummy data");
        tty.flush();
        // Create vocab entries
        String names = getResource("names.txt");
        int i = 0;
        for (String nextName : names.split("\n")) {
            i++;
            JSONObject entry = createTrivialAuthItem(PERSON_TERMLIST_ELEMENT, nextName);
            storage.autocreateJSON("/person/person", entry, null);
            tty.line("Created Person " + entry);
            log.info("Created Person " + entry);
            tty.flush();
            if (quick && i > 20)
                break;
        }
        // Create vocab entries
        String orgs = getResource("orgs.txt");
        i = 0;
        for (String nextName : orgs.split("\n")) {
            i++;
            JSONObject entry = createTrivialAuthItem(ORG_TERMLIST_ELEMENT, nextName);
            storage.autocreateJSON("/organization/organization", entry, null);
            tty.line("Created Organisation " + nextName);
            log.info("Created Organisation " + nextName);
            tty.flush();
            if (quick && i > 20)
                break;
        }
        tty.line("done");
        log.info("done");
    } catch (ExistException e) {
        log.info("ExistException " + e.getLocalizedMessage());
        tty.line("ExistException " + e.getLocalizedMessage());
        throw new UIException("Existence problem", e);
    } catch (UnimplementedException e) {
        log.info("UnimplementedException " + e.getLocalizedMessage());
        tty.line("UnimplementedException " + e.getLocalizedMessage());
        throw new UIException("Unimplemented ", e);
    } catch (UnderlyingStorageException x) {
        log.info("UnderlyingStorageException " + x.getLocalizedMessage());
        tty.line("UnderlyingStorageException " + x.getLocalizedMessage());
        throw new UIException("Problem storing" + x.getLocalizedMessage(), x.getStatus(), x.getUrl(), x);
    } catch (JSONException e) {
        log.info("JSONException " + e.getLocalizedMessage());
        tty.line("JSONException " + e.getLocalizedMessage());
        throw new UIException("Invalid JSON", e);
    } catch (IOException e) {
        log.info("IOException " + e.getLocalizedMessage());
        tty.line("IOException " + e.getLocalizedMessage());
        throw new UIException("IOException", e);
    }
}
Also used : Instance(org.collectionspace.chain.csp.schema.Instance) JSONException(org.json.JSONException) IOException(java.io.IOException) 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) TTYOutputter(org.collectionspace.csp.api.ui.TTYOutputter) Record(org.collectionspace.chain.csp.schema.Record) UnimplementedException(org.collectionspace.csp.api.persistence.UnimplementedException)

Example 27 with UIException

use of org.collectionspace.csp.api.ui.UIException in project application by collectionspace.

the class WebReset method deletall.

private JSONObject deletall(Instance n, Record thisr, String path, String msg, Storage storage, JSONObject data, TTYOutputter tty, JSONObject myjs) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException, UIException {
    int resultsize;
    int check;
    String checkpagination;
    resultsize = 1;
    check = 0;
    checkpagination = "";
    while (resultsize > 0) {
        myjs.put("pageNum", check);
        // String url = thisr.getID()+"/"+n.getTitleRef();
        if (thisr == null || n == null) {
            String[] bits = path.split("/");
            thisr = this.spec.getRecordByWebUrl(bits[1]);
            n = thisr.getInstance(bits[1] + "-" + bits[2]);
        }
        try {
            data = storage.getPathsJSON(path, myjs);
        } catch (UnderlyingStorageException x) {
            JSONObject fields = new JSONObject("{'displayName':'" + n.getTitle() + "','shortIdentifier':'" + n.getWebURL() + "'}");
            if (thisr.getFieldFullList("termStatus") instanceof Field) {
                fields.put("termStatus", ((Field) thisr.getFieldFullList("termStatus")).getOptionDefault());
            }
            String base = thisr.getID();
            storage.autocreateJSON(base, fields, null);
        // data = storage.getPathsJSON(url,restriction);
        }
        String[] res = (String[]) data.get("listItems");
        if (res.length == 0 || checkpagination.equals(res[0])) {
            resultsize = 0;
            break;
        // testing whether we have actually returned the same page or the next page - all csid returned should be unique
        } else {
            checkpagination = res[0];
        }
        resultsize = res.length;
        for (String urn : res) {
            try {
                storage.deleteJSON(path + "/" + urn);
                tty.line(msg + urn);
                log.info(msg + urn);
            } catch (Exception e) {
            /* Sometimes records are wdged */
            }
            tty.flush();
        }
    }
    return data;
}
Also used : Field(org.collectionspace.chain.csp.schema.Field) JSONObject(org.json.JSONObject) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) 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)

Example 28 with UIException

use of org.collectionspace.csp.api.ui.UIException 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 29 with UIException

use of org.collectionspace.csp.api.ui.UIException in project application by collectionspace.

the class UserDetailsCreateUpdate method store_set.

private void store_set(Storage storage, UIRequest request, String path) throws UIException {
    JSONObject data = null;
    data = request.getJSONBody();
    boolean notfailed = true;
    String msg = "";
    try {
        boolean currentUserPasswordChange = false;
        String newPassword = null;
        boolean absorbedSvcsError = false;
        if (create) {
            path = sendJSON(storage, null, data);
        // assign to default role.
        } else {
            // Check for password update. If doing that, absorb 403 errors and redirect
            // as though we are doing a logout.
            JSONObject fields = data.optJSONObject("fields");
            if (fields != null && fields.has(PASSWORD_FIELD)) {
                String passwd = fields.getString(PASSWORD_FIELD);
                if (passwd != null) {
                    if (passwd.isEmpty()) {
                        // Preclude removl of a password
                        fields.remove(PASSWORD_FIELD);
                    } else {
                        String editedUserId = fields.getString(USER_ID_FIELD);
                        UISession session = request.getSession();
                        if (session != null) {
                            Object currentUserId = session.getValue(UISession.USERID);
                            if (currentUserId != null && currentUserId.equals(editedUserId)) {
                                newPassword = passwd;
                                currentUserPasswordChange = true;
                            }
                        }
                    }
                }
            }
            path = sendJSON(storage, path, data);
            // credentials
            if (currentUserPasswordChange) {
                request.getSession().setValue(UISession.PASSWORD, newPassword);
            }
        }
        if (path == null) {
            throw new UIException("Insufficient data for create (no fields?)");
        }
        data.put("csid", path);
        try {
            assignRole(storage, path, data);
        } catch (UnderlyingStorageException usex) {
            Integer status = usex.getStatus();
            if (status != null && (status == HttpStatus.SC_FORBIDDEN || status == HttpStatus.SC_UNAUTHORIZED)) {
                absorbedSvcsError = true;
                msg = "Cannot update roles for this account.";
                log.warn("UserDetailsCreateUpdate changing roles, and absorbing error returned: " + usex.getStatus());
            } else {
                // Propagate
                throw usex;
            }
        }
        boolean isError = !notfailed;
        data.put("isError", isError);
        JSONObject messages = new JSONObject();
        messages.put("message", msg);
        messages.put("severity", "info");
        JSONArray arr = new JSONArray();
        arr.put(messages);
        data.put("messages", arr);
        // Elide the value of the password field before returning a response
        data.optJSONObject("fields").remove(PASSWORD_FIELD);
        request.sendJSONResponse(data);
        request.setOperationPerformed(create ? Operation.CREATE : Operation.UPDATE);
        if (create && notfailed)
            request.setSecondaryRedirectPath(new String[] { url_base, path });
    } catch (JSONException x) {
        throw new UIException("Failed to parse json: ", x);
    } catch (ExistException x) {
        throw new UIException("Existence exception: ", x);
    } catch (UnimplementedException x) {
        throw new UIException("Unimplemented exception: ", x);
    } catch (UnderlyingStorageException x) {
        UIException uiexception = new UIException(x.getMessage(), x.getStatus(), x.getUrl(), x);
        request.sendJSONResponse(uiexception.getJSON());
    }
}
Also used : JSONObject(org.json.JSONObject) UISession(org.collectionspace.csp.api.ui.UISession) JSONArray(org.json.JSONArray) UIException(org.collectionspace.csp.api.ui.UIException) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) ExistException(org.collectionspace.csp.api.persistence.ExistException) UnimplementedException(org.collectionspace.csp.api.persistence.UnimplementedException)

Example 30 with UIException

use of org.collectionspace.csp.api.ui.UIException in project application by collectionspace.

the class UserDetailsRead method store_get.

private void store_get(Storage storage, UIRequest request, String path) throws UIException {
    // Get the data
    JSONObject outputJSON = getJSON(storage, path);
    try {
        outputJSON.put("csid", path);
    } catch (JSONException e1) {
        throw new UIException("Cannot add csid", e1);
    }
    // Write the requested JSON out
    request.sendJSONResponse(outputJSON);
}
Also used : JSONObject(org.json.JSONObject) JSONException(org.json.JSONException) UIException(org.collectionspace.csp.api.ui.UIException)

Aggregations

UIException (org.collectionspace.csp.api.ui.UIException)72 JSONObject (org.json.JSONObject)51 JSONException (org.json.JSONException)50 ExistException (org.collectionspace.csp.api.persistence.ExistException)39 UnderlyingStorageException (org.collectionspace.csp.api.persistence.UnderlyingStorageException)39 UnimplementedException (org.collectionspace.csp.api.persistence.UnimplementedException)39 JSONArray (org.json.JSONArray)19 IOException (java.io.IOException)10 Record (org.collectionspace.chain.csp.schema.Record)7 Instance (org.collectionspace.chain.csp.schema.Instance)6 ConfigException (org.collectionspace.chain.csp.config.ConfigException)5 Field (org.collectionspace.chain.csp.schema.Field)4 FieldSet (org.collectionspace.chain.csp.schema.FieldSet)4 UIRequest (org.collectionspace.csp.api.ui.UIRequest)4 MessageDigest (java.security.MessageDigest)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 ConnectionException (org.collectionspace.chain.csp.persistence.services.connection.ConnectionException)3 AdminData (org.collectionspace.chain.csp.schema.AdminData)3 Structure (org.collectionspace.chain.csp.schema.Structure)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2