Search in sources :

Example 21 with IllegalCommandException

use of edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException in project dataverse by IQSS.

the class PublishDataverseCommand method execute.

@Override
public Dataverse execute(CommandContext ctxt) throws CommandException {
    if (dataverse.isReleased()) {
        throw new IllegalCommandException("Dataverse " + dataverse.getAlias() + " has already been published.", this);
    }
    Dataverse parent = dataverse.getOwner();
    // root dataverse doesn't have a parent
    if (parent != null) {
        if (!parent.isReleased()) {
            throw new IllegalCommandException("Dataverse " + dataverse.getAlias() + " may not be published because its host dataverse (" + parent.getAlias() + ") has not been published.", this);
        }
    }
    // Before setting dataverse to released send notifications to users with download file
    List<RoleAssignment> ras = ctxt.roles().directRoleAssignments(dataverse);
    for (RoleAssignment ra : ras) {
        if (ra.getRole().permissions().contains(Permission.DownloadFile)) {
            for (AuthenticatedUser au : ctxt.roleAssignees().getExplicitUsers(ctxt.roleAssignees().getRoleAssignee(ra.getAssigneeIdentifier()))) {
                ctxt.notifications().sendNotification(au, new Timestamp(new Date().getTime()), UserNotification.Type.ASSIGNROLE, dataverse.getId());
            }
        }
    }
    dataverse.setPublicationDate(new Timestamp(new Date().getTime()));
    dataverse.setReleaseUser((AuthenticatedUser) getUser());
    Dataverse savedDataverse = ctxt.dataverses().save(dataverse);
    /**
     * @todo consider also
     * ctxt.solrIndex().indexPermissionsOnSelfAndChildren(savedDataverse.getId());
     */
    /**
     * @todo what should we do with the indexRespose?
     */
    IndexResponse indexResponse = ctxt.solrIndex().indexPermissionsForOneDvObject(savedDataverse);
    return savedDataverse;
}
Also used : IndexResponse(edu.harvard.iq.dataverse.search.IndexResponse) IllegalCommandException(edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException) RoleAssignment(edu.harvard.iq.dataverse.RoleAssignment) Dataverse(edu.harvard.iq.dataverse.Dataverse) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Timestamp(java.sql.Timestamp) Date(java.util.Date)

Example 22 with IllegalCommandException

use of edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException in project dataverse by IQSS.

the class ImportFromFileSystemCommand method execute.

@Override
public JsonObject execute(CommandContext ctxt) throws CommandException {
    JsonObjectBuilder bld = jsonObjectBuilder();
    /**
     * batch import as-individual-datafiles is disabled in this iteration;
     * only the import-as-a-package is allowed. -- L.A. Feb 2 2017
     */
    String fileMode = FileRecordWriter.FILE_MODE_PACKAGE_FILE;
    try {
        /**
         * Current constraints: 1. only supports merge and replace mode 2.
         * valid dataset 3. valid dataset directory 4. valid user & user has
         * edit dataset permission 5. only one dataset version 6. dataset
         * version is draft
         */
        if (!mode.equalsIgnoreCase("MERGE") && !mode.equalsIgnoreCase("REPLACE")) {
            String error = "Import mode: " + mode + " is not currently supported.";
            logger.info(error);
            throw new IllegalCommandException(error, this);
        }
        if (!fileMode.equals(FileRecordWriter.FILE_MODE_INDIVIDUAL_FILES) && !fileMode.equals(FileRecordWriter.FILE_MODE_PACKAGE_FILE)) {
            String error = "File import mode: " + fileMode + " is not supported.";
            logger.info(error);
            throw new IllegalCommandException(error, this);
        }
        File directory = new File(System.getProperty("dataverse.files.directory") + File.separator + dataset.getAuthority() + File.separator + dataset.getIdentifier());
        if (!isValidDirectory(directory)) {
            String error = "Dataset directory is invalid. " + directory;
            logger.info(error);
            throw new IllegalCommandException(error, this);
        }
        if (Strings.isNullOrEmpty(uploadFolder)) {
            String error = "No uploadFolder specified";
            logger.info(error);
            throw new IllegalCommandException(error, this);
        }
        File uploadDirectory = new File(System.getProperty("dataverse.files.directory") + File.separator + dataset.getAuthority() + File.separator + dataset.getIdentifier() + File.separator + uploadFolder);
        if (!isValidDirectory(uploadDirectory)) {
            String error = "Upload folder is not a valid directory.";
            logger.info(error);
            throw new IllegalCommandException(error, this);
        }
        if (dataset.getVersions().size() != 1) {
            String error = "Error creating FilesystemImportJob with dataset with ID: " + dataset.getId() + " - Dataset has more than one version.";
            logger.info(error);
            throw new IllegalCommandException(error, this);
        }
        if (dataset.getLatestVersion().getVersionState() != DatasetVersion.VersionState.DRAFT) {
            String error = "Error creating FilesystemImportJob with dataset with ID: " + dataset.getId() + " - Dataset isn't in DRAFT mode.";
            logger.info(error);
            throw new IllegalCommandException(error, this);
        }
        try {
            long jid;
            Properties props = new Properties();
            props.setProperty("datasetId", dataset.getId().toString());
            props.setProperty("userId", getUser().getIdentifier().replace("@", ""));
            props.setProperty("mode", mode);
            props.setProperty("fileMode", fileMode);
            props.setProperty("uploadFolder", uploadFolder);
            if (totalSize != null && totalSize > 0) {
                props.setProperty("totalSize", totalSize.toString());
            }
            JobOperator jo = BatchRuntime.getJobOperator();
            jid = jo.start("FileSystemImportJob", props);
            if (jid > 0) {
                bld.add("executionId", jid).add("message", "FileSystemImportJob in progress");
                return bld.build();
            } else {
                String error = "Error creating FilesystemImportJob with dataset with ID: " + dataset.getId();
                logger.info(error);
                throw new CommandException(error, this);
            }
        } catch (JobStartException | JobSecurityException ex) {
            String error = "Error creating FilesystemImportJob with dataset with ID: " + dataset.getId() + " - " + ex.getMessage();
            logger.info(error);
            throw new IllegalCommandException(error, this);
        }
    } catch (Exception e) {
        bld.add("message", "Import Exception - " + e.getMessage());
        return bld.build();
    }
}
Also used : JobSecurityException(javax.batch.operations.JobSecurityException) JobStartException(javax.batch.operations.JobStartException) IllegalCommandException(edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException) JobOperator(javax.batch.operations.JobOperator) IllegalCommandException(edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException) JsonObjectBuilder(javax.json.JsonObjectBuilder) Properties(java.util.Properties) File(java.io.File) JobStartException(javax.batch.operations.JobStartException) IllegalCommandException(edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException) JobSecurityException(javax.batch.operations.JobSecurityException) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException)

Example 23 with IllegalCommandException

use of edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException in project dataverse by IQSS.

the class MoveDatasetCommand method executeImpl.

@Override
public void executeImpl(CommandContext ctxt) throws CommandException {
    // first check if  user is a superuser
    if ((!(getUser() instanceof AuthenticatedUser) || !getUser().isSuperuser())) {
        throw new PermissionException("Move Dataset can only be called by superusers.", this, Collections.singleton(Permission.DeleteDatasetDraft), moved);
    }
    // validate the move makes sense
    if (moved.getOwner().equals(destination)) {
        throw new IllegalCommandException("Dataset already in this Dataverse ", this);
    }
    if (moved.isReleased() && !destination.isReleased()) {
        throw new IllegalCommandException("Published Dataset may not be moved to unpublished Dataverse. You may publish " + destination.getDisplayName() + " and re-try the move.", this);
    }
    // if the datasets guestbook is not contained in the new dataverse then remove it
    if (moved.getGuestbook() != null) {
        Guestbook gb = moved.getGuestbook();
        List<Guestbook> gbs = destination.getGuestbooks();
        boolean inheritGuestbooksValue = !destination.isGuestbookRoot();
        if (inheritGuestbooksValue && destination.getOwner() != null) {
            for (Guestbook pg : destination.getParentGuestbooks()) {
                gbs.add(pg);
            }
        }
        if (gbs == null || !gbs.contains(gb)) {
            if (force == null || !force) {
                throw new IllegalCommandException("Dataset guestbook is not in target dataverse. Please use the parameter ?forceMove=true to complete the move. This will delete the guestbook from the Dataset", this);
            }
            moved.setGuestbook(null);
        }
    }
    // OK, move
    moved.setOwner(destination);
    ctxt.em().merge(moved);
    try {
        boolean doNormalSolrDocCleanUp = true;
        ctxt.index().indexDataset(moved, doNormalSolrDocCleanUp);
    } catch (Exception e) {
        // RuntimeException e ) {
        // , e);
        logger.log(Level.WARNING, "Exception while indexing:" + e.getMessage());
        throw new CommandException("Dataset could not be moved. Indexing failed", this);
    }
}
Also used : PermissionException(edu.harvard.iq.dataverse.engine.command.exception.PermissionException) Guestbook(edu.harvard.iq.dataverse.Guestbook) IllegalCommandException(edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException) IllegalCommandException(edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) PermissionException(edu.harvard.iq.dataverse.engine.command.exception.PermissionException) IllegalCommandException(edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException)

Example 24 with IllegalCommandException

use of edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException in project dataverse by IQSS.

the class CreateDatasetVersionCommand method execute.

@Override
public DatasetVersion execute(CommandContext ctxt) throws CommandException {
    DatasetVersion latest = dataset.getLatestVersion();
    if (latest.isWorkingCopy()) {
        // before throwing an Exception
        if (newVersion.getVersionState().equals(VersionState.DRAFT)) {
            throw new IllegalCommandException("Latest version is already a draft. Cannot add another draft", this);
        }
    }
    newVersion.setDataset(dataset);
    newVersion.setDatasetFields(newVersion.initDatasetFields());
    Set<ConstraintViolation> constraintViolations = newVersion.validate();
    if (!constraintViolations.isEmpty()) {
        String validationFailedString = "Validation failed:";
        for (ConstraintViolation constraintViolation : constraintViolations) {
            validationFailedString += " " + constraintViolation.getMessage();
        }
        throw new IllegalCommandException(validationFailedString, this);
    }
    Iterator<DatasetField> dsfIt = newVersion.getDatasetFields().iterator();
    while (dsfIt.hasNext()) {
        if (dsfIt.next().removeBlankDatasetFieldValues()) {
            dsfIt.remove();
        }
    }
    Iterator<DatasetField> dsfItSort = newVersion.getDatasetFields().iterator();
    while (dsfItSort.hasNext()) {
        dsfItSort.next().setValueDisplayOrder();
    }
    List<FileMetadata> newVersionMetadatum = new ArrayList<>(latest.getFileMetadatas().size());
    for (FileMetadata fmd : latest.getFileMetadatas()) {
        FileMetadata fmdCopy = fmd.createCopy();
        fmdCopy.setDatasetVersion(newVersion);
        newVersionMetadatum.add(fmdCopy);
    }
    newVersion.setFileMetadatas(newVersionMetadatum);
    Timestamp now = new Timestamp(new Date().getTime());
    newVersion.setCreateTime(now);
    newVersion.setLastUpdateTime(now);
    dataset.setModificationTime(now);
    newVersion.setDataset(dataset);
    final List<DatasetVersion> currentVersions = dataset.getVersions();
    ArrayList<DatasetVersion> dsvs = new ArrayList<>(currentVersions.size());
    dsvs.addAll(currentVersions);
    dsvs.add(0, newVersion);
    dataset.setVersions(dsvs);
    // ctxt.index().indexDataset(dataset);
    return ctxt.datasets().storeVersion(newVersion);
}
Also used : DatasetField(edu.harvard.iq.dataverse.DatasetField) IllegalCommandException(edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException) FileMetadata(edu.harvard.iq.dataverse.FileMetadata) ArrayList(java.util.ArrayList) DatasetVersion(edu.harvard.iq.dataverse.DatasetVersion) Timestamp(java.sql.Timestamp) Date(java.util.Date) ConstraintViolation(javax.validation.ConstraintViolation)

Example 25 with IllegalCommandException

use of edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException in project dataverse by IQSS.

the class CreatePrivateUrlCommand method execute.

@Override
public PrivateUrl execute(CommandContext ctxt) throws CommandException {
    logger.fine("Executing CreatePrivateUrlCommand...");
    if (dataset == null) {
        /**
         * @todo Internationalize this.
         */
        String message = "Can't create Private URL. Dataset is null.";
        logger.info(message);
        throw new IllegalCommandException(message, this);
    }
    PrivateUrl existing = ctxt.privateUrl().getPrivateUrlFromDatasetId(dataset.getId());
    if (existing != null) {
        /**
         * @todo Internationalize this.
         */
        String message = "Private URL already exists for dataset id " + dataset.getId() + ".";
        logger.info(message);
        throw new IllegalCommandException(message, this);
    }
    DatasetVersion latestVersion = dataset.getLatestVersion();
    if (!latestVersion.isDraft()) {
        /**
         * @todo Internationalize this.
         */
        String message = "Can't create Private URL because the latest version of dataset id " + dataset.getId() + " is not a draft.";
        logger.info(message);
        throw new IllegalCommandException(message, this);
    }
    PrivateUrlUser privateUrlUser = new PrivateUrlUser(dataset.getId());
    DataverseRole memberRole = ctxt.roles().findBuiltinRoleByAlias(DataverseRole.MEMBER);
    final String privateUrlToken = UUID.randomUUID().toString();
    RoleAssignment roleAssignment = ctxt.engine().submit(new AssignRoleCommand(privateUrlUser, memberRole, dataset, getRequest(), privateUrlToken));
    PrivateUrl privateUrl = new PrivateUrl(roleAssignment, dataset, ctxt.systemConfig().getDataverseSiteUrl());
    return privateUrl;
}
Also used : PrivateUrl(edu.harvard.iq.dataverse.privateurl.PrivateUrl) IllegalCommandException(edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException) PrivateUrlUser(edu.harvard.iq.dataverse.authorization.users.PrivateUrlUser) RoleAssignment(edu.harvard.iq.dataverse.RoleAssignment) DatasetVersion(edu.harvard.iq.dataverse.DatasetVersion) DataverseRole(edu.harvard.iq.dataverse.authorization.DataverseRole)

Aggregations

IllegalCommandException (edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException)25 Dataset (edu.harvard.iq.dataverse.Dataset)6 RoleAssignment (edu.harvard.iq.dataverse.RoleAssignment)6 AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)6 CommandException (edu.harvard.iq.dataverse.engine.command.exception.CommandException)6 Timestamp (java.sql.Timestamp)6 Date (java.util.Date)6 DatasetVersion (edu.harvard.iq.dataverse.DatasetVersion)4 ConstraintViolation (javax.validation.ConstraintViolation)4 DataFile (edu.harvard.iq.dataverse.DataFile)3 Dataverse (edu.harvard.iq.dataverse.Dataverse)3 DataverseRole (edu.harvard.iq.dataverse.authorization.DataverseRole)3 PrivateUrlUser (edu.harvard.iq.dataverse.authorization.users.PrivateUrlUser)3 DatasetField (edu.harvard.iq.dataverse.DatasetField)2 DataverseFieldTypeInputLevel (edu.harvard.iq.dataverse.DataverseFieldTypeInputLevel)2 FileMetadata (edu.harvard.iq.dataverse.FileMetadata)2 User (edu.harvard.iq.dataverse.authorization.users.User)2 PermissionException (edu.harvard.iq.dataverse.engine.command.exception.PermissionException)2 CreateDatasetCommand (edu.harvard.iq.dataverse.engine.command.impl.CreateDatasetCommand)2 UpdateDatasetCommand (edu.harvard.iq.dataverse.engine.command.impl.UpdateDatasetCommand)2