Search in sources :

Example 1 with Option

use of org.collectionspace.chain.csp.schema.Option in project application by collectionspace.

the class UISpec method actualChooser.

/**
 * The UISpec mark up for Chooser elements
 * @param f
 * @param context
 * @return
 * @throws JSONException
 */
private JSONObject actualChooser(FieldSet fs, UISpecRunContext context, JSONArray decorators) throws JSONException {
    Field f = (Field) fs;
    JSONObject out = new JSONObject();
    JSONObject options = new JSONObject();
    JSONObject selectors = new JSONObject();
    selectors.put("numberField", getSelector(f, context));
    options.put("selectors", selectors);
    JSONObject model = new JSONObject();
    JSONArray ids = new JSONArray();
    JSONArray samples = new JSONArray();
    JSONArray names = new JSONArray();
    for (Option opt : f.getAllOptions()) {
        ids.put(opt.getID());
        samples.put(opt.getSample());
        names.put(opt.getName());
    }
    model.put("list", ids);
    model.put("samples", samples);
    model.put("names", names);
    options.put("model", model);
    JSONObject decorator = getDecorator("fluid", null, "cspace.numberPatternChooser", options, f.isReadOnly());
    if (!f.isRefactored()) {
        if (f.hasContainer()) {
            decorator.put("container", getContainerSelector(f, context));
        }
    }
    if (decorators == null) {
        decorators = new JSONArray();
    }
    decorators.put(decorator);
    out.put(DECORATORS_KEY, decorators);
    if (f.isRefactored()) {
        out.put("valuebinding", actualFieldEntry(f, context));
    }
    return out;
}
Also used : Field(org.collectionspace.chain.csp.schema.Field) JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) Option(org.collectionspace.chain.csp.schema.Option)

Example 2 with Option

use of org.collectionspace.chain.csp.schema.Option in project application by collectionspace.

the class UISpec method actualOptionField.

/**
 * output the option field markup for UISpecs
 * @param f
 * @param context
 * @return
 * @throws JSONException
 */
@Override
protected Object actualOptionField(Field f, UISpecRunContext context) throws JSONException {
    // Dropdown entry
    JSONObject out = new JSONObject();
    if ("radio".equals(f.getUIType())) {
        out.put("selection", displayAsradio(f));
    } else {
        out.put("selection", displayAsplain(f, context));
    }
    JSONArray ids = new JSONArray();
    JSONArray names = new JSONArray();
    boolean hasdefault = false;
    String dfault = null;
    for (Option opt : f.getAllOptions()) {
        if (opt.getID().equals("")) {
            hasdefault = true;
        }
        ids.put(opt.getID());
        names.put(opt.getName());
        if (opt.isDefault()) {
            dfault = opt.getID();
        }
    }
    // need to make sure there is always a blank on search and default is ""
    if (this.spectype.equals("search") && !f.getSearchType().equals("")) {
        out.put("default", "");
        if (!hasdefault) {
            ids.put("");
            names.put(f.enumBlankValue());
        }
        out.put("optionlist", ids);
        out.put("optionnames", names);
    } else {
        // currently only supports single select dropdowns and not multiselect
        if (dfault != null) {
            out.put("default", dfault + "");
        }
        out.put("optionlist", ids);
        out.put("optionnames", names);
    }
    return out;
}
Also used : JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) Option(org.collectionspace.chain.csp.schema.Option)

Example 3 with Option

use of org.collectionspace.chain.csp.schema.Option in project application by collectionspace.

the class WebAutoComplete method doAuthorityAutocomplete.

private JSONArray doAuthorityAutocomplete(CSPRequestCache cache, Storage storage, String fieldname, String start, String vocabConstraint, String pageSize, String pageNum) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException, ConfigException {
    FieldSet fs = r.getFieldFullList(fieldname);
    JSONArray out = new JSONArray();
    Instance[] allInstances = null;
    if (fs == null || !(fs instanceof Field)) {
        if (r.hasHierarchyUsed("screen")) {
            // Configures the hierarchy section.
            Structure s = r.getStructure("screen");
            if (s.hasOption(fieldname)) {
                // This is one of the hierarchy fields
                if (vocabConstraint != null) {
                    allInstances = new Instance[1];
                    String fullname = r.getID() + "-" + vocabConstraint;
                    allInstances[0] = r.getSpec().getInstance(fullname);
                } else {
                    Option a = s.getOption(fieldname);
                    String[] data = a.getName().split(",");
                    allInstances = new Instance[data.length];
                    for (int i = 0; i < data.length; i++) {
                        allInstances[i] = (r.getSpec().getInstance(data[i]));
                    }
                }
            } else {
                fs = r.getSpec().getRecord("hierarchy").getFieldFullList(fieldname);
                if (fs instanceof Field) {
                    allInstances = ((Field) fs).getAllAutocompleteInstances();
                }
            }
        }
    } else {
        allInstances = ((Field) fs).getAllAutocompleteInstances();
    }
    if (allInstances == null) {
        // Cannot autocomplete
        return out;
    }
    // support multiassign of autocomplete instances
    for (Instance n : allInstances) {
        try {
            if (n == null) {
            // Field has no autocomplete
            } else {
                String path = n.getRecord().getID() + "/" + n.getTitleRef();
                JSONObject restriction = new JSONObject();
                if (pageSize != null) {
                    restriction.put("pageSize", pageSize);
                }
                if (pageNum != null) {
                    restriction.put("pageNum", pageNum);
                }
                FieldSet dispNameFS = n.getRecord().getDisplayNameField();
                if (dispNameFS == null) {
                    throw new ConfigException("WebAutoComplete for Instance has no displayName configured: " + n.getID());
                }
                String displayNameFieldID = dispNameFS.getID();
                // May be something other than display name
                restriction.put(displayNameFieldID, start);
                JSONObject results = storage.getPathsJSON(path, restriction);
                String[] paths = (String[]) results.get("listItems");
                for (String csid : paths) {
                    JSONObject data = storage.retrieveJSON(path + "/" + csid + "/view", new JSONObject());
                    JSONObject entry = new JSONObject();
                    // TODO - handle multiple name matches
                    String displayNameString = data.getString(displayNameFieldID);
                    JSONArray displayNames = JSONUtils.createJSONArrayFromSeparatedString(displayNameString);
                    String primaryDN = displayNames.getString(0);
                    String refid = data.getString("refid");
                    // HACK - transition period with full instead of base URN value
                    if (refid.endsWith("'" + primaryDN + "'"))
                        refid = refid.substring(0, refid.length() - (primaryDN.length() + 2));
                    entry.put("baseUrn", refid);
                    entry.put("csid", data.getString("csid"));
                    entry.put("type", n.getRecord().getWebURL());
                    entry.put("displayNames", displayNames);
                    // RefName.AuthorityItem item = RefName.AuthorityItem.parse(refid);
                    // entry.put("namespace",item.getParentShortIdentifier());
                    entry.put("namespace", data.getString("namespace"));
                    entry.put("workflow", data.getString("workflow"));
                    out.put(entry);
                }
            }
        } catch (UnderlyingStorageException x) {
            if (x.getStatus() == 403) {
            // permission error - keep calm and carry on
            } else {
                throw x;
            }
        }
    }
    // Instance n=((Field)fs).getAutocompleteInstance();
    return out;
}
Also used : Instance(org.collectionspace.chain.csp.schema.Instance) JSONArray(org.json.JSONArray) ConfigException(org.collectionspace.chain.csp.config.ConfigException) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException) Field(org.collectionspace.chain.csp.schema.Field) FieldSet(org.collectionspace.chain.csp.schema.FieldSet) JSONObject(org.json.JSONObject) Option(org.collectionspace.chain.csp.schema.Option) Structure(org.collectionspace.chain.csp.schema.Structure)

Example 4 with Option

use of org.collectionspace.chain.csp.schema.Option 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 5 with Option

use of org.collectionspace.chain.csp.schema.Option in project application by collectionspace.

the class AuthoritiesVocabulariesInitialize method fillVocab.

public void fillVocab(Storage storage, Record thisr, Instance instance, StringBuffer tty, Option[] allOpts, Boolean appendit) throws UIException, ExistException, UnimplementedException, UnderlyingStorageException, JSONException {
    // 
    if (allOpts != null && allOpts.length > 0) {
        // get list from Service layer
        JSONObject results = new JSONObject();
        Integer pageNum = 0;
        // Setting the pageSize to 0 means the Services layer will return ALL the terms in one request.
        Integer pageSize = 0;
        // The "paging" code here is broken.  It's made some false assumptions about the order in which terms are returned from the Services layer.
        // In short, setting the pageSize to 0 is a workaround to the bugs in the paging code.
        JSONObject fulldata = list_vocab(results, instance, storage, null, pageSize, pageNum, thisr);
        while (!fulldata.isNull("pagination")) {
            Integer total = fulldata.getJSONObject("pagination").getInt("totalItems");
            pageSize = fulldata.getJSONObject("pagination").getInt("pageSize");
            Integer itemsInPage = fulldata.getJSONObject("pagination").getInt("itemsInPage");
            pageNum = fulldata.getJSONObject("pagination").getInt("pageNum");
            results = fulldata.getJSONObject("shortIdentifiers");
            pageNum++;
            // are there more results
            if (total > (pageSize * (pageNum))) {
                fulldata = list_vocab(results, instance, storage, null, pageSize, pageNum, thisr);
            } else {
                break;
            }
        }
        // compare
        results = fulldata.getJSONObject("shortIdentifiers");
        for (Option opt : allOpts) {
            String name = opt.getName();
            String shortIdentifier = opt.getID();
            if (shortIdentifier == null || shortIdentifier.equals("")) {
                shortIdentifier = name.trim().replaceAll("\\W", "").toLowerCase();
            }
            if (!results.has(shortIdentifier)) {
                // create it if term is not already present
                JSONObject data = new JSONObject();
                data.put("displayName", name);
                data.put("description", opt.getDesc());
                data.put("shortIdentifier", shortIdentifier);
                if (thisr.getFieldFullList("termStatus") instanceof Field) {
                    data.put("termStatus", ((Field) thisr.getFieldFullList("termStatus")).getOptionDefault());
                }
                String url = thisr.getID() + "/" + instance.getTitleRef();
                // assume we're going to fail and an exception will be thrown
                failedPosts++;
                try {
                    storage.autocreateJSON(url, data, null);
                    // we succeeded so we can remove our assumed failure
                    failedPosts--;
                    if (tty != null) {
                        String msg = String.format("Added term %s:'%s' with short ID='%s'.", instance.getTitleRef(), name, shortIdentifier);
                        tty.append(msg + '\n');
                        log.info(msg);
                    }
                } catch (UnderlyingStorageException e) {
                    if (e.getStatus() == HttpStatus.SC_CONFLICT) {
                        log.error("Terms must have unique short identifiers. The CollectionSpace administrator needs to change the non-unique short identifier and restart CollectionSpace.");
                        String msg = String.format("CollectionSpace attempted to create the term %s:'%s' using a non-unique short identifier of '%s'.", instance.getTitleRef(), name, shortIdentifier);
                        log.error(msg);
                        log.error(String.format("Failed JSON payload:%s", data.toString()));
                    } else {
                        throw e;
                    }
                }
            } else {
                // remove from results so can delete everything else if
                // necessary in next stage
                // though has issues with duplicates
                results.remove(shortIdentifier);
                String msg = String.format("Tried to create term %s:'%s' with short ID='%s', but a term with that short ID already exists.", instance.getTitleRef(), name, shortIdentifier);
                log.debug(msg);
            }
        }
        if (!appendit) {
            // delete everything that is not in options
            Iterator<String> rit = results.keys();
            while (rit.hasNext()) {
                String key = rit.next();
                String csid = results.getString(key);
                // assume we're going to fail and an exception will be thrown
                failedPosts++;
                storage.deleteJSON(thisr.getID() + "/" + instance.getTitleRef() + "/" + csid);
                // we succeeded so remove our assumed failure
                failedPosts--;
                if (tty != null) {
                    log.info("Deleting term " + key);
                    tty.append("Deleting term " + key + '\n');
                }
            }
        }
    }
}
Also used : Field(org.collectionspace.chain.csp.schema.Field) JSONObject(org.json.JSONObject) Option(org.collectionspace.chain.csp.schema.Option) UnderlyingStorageException(org.collectionspace.csp.api.persistence.UnderlyingStorageException)

Aggregations

Option (org.collectionspace.chain.csp.schema.Option)9 JSONObject (org.json.JSONObject)7 Field (org.collectionspace.chain.csp.schema.Field)4 JSONArray (org.json.JSONArray)4 Instance (org.collectionspace.chain.csp.schema.Instance)3 UnderlyingStorageException (org.collectionspace.csp.api.persistence.UnderlyingStorageException)3 IOException (java.io.IOException)2 ConfigException (org.collectionspace.chain.csp.config.ConfigException)2 FieldSet (org.collectionspace.chain.csp.schema.FieldSet)2 Structure (org.collectionspace.chain.csp.schema.Structure)2 TTYOutputter (org.collectionspace.csp.api.ui.TTYOutputter)2 UIException (org.collectionspace.csp.api.ui.UIException)2 ConnectionException (org.collectionspace.chain.csp.persistence.services.connection.ConnectionException)1 Record (org.collectionspace.chain.csp.schema.Record)1 AuthoritiesVocabulariesInitialize (org.collectionspace.chain.csp.webui.authorities.AuthoritiesVocabulariesInitialize)1 ExistException (org.collectionspace.csp.api.persistence.ExistException)1 UnimplementedException (org.collectionspace.csp.api.persistence.UnimplementedException)1 Element (org.dom4j.Element)1 QName (org.dom4j.QName)1 JSONException (org.json.JSONException)1