Search in sources :

Example 1 with AddReplaceFileHelper

use of edu.harvard.iq.dataverse.datasetutility.AddReplaceFileHelper in project dataverse by IQSS.

the class Datasets method addFileToDataset.

/**
 * Add a File to an existing Dataset
 *
 * @param idSupplied
 * @param jsonData
 * @param fileInputStream
 * @param contentDispositionHeader
 * @param formDataBodyPart
 * @return
 */
@POST
@Path("{id}/add")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response addFileToDataset(@PathParam("id") String idSupplied, @FormDataParam("jsonData") String jsonData, @FormDataParam("file") InputStream fileInputStream, @FormDataParam("file") FormDataContentDisposition contentDispositionHeader, @FormDataParam("file") final FormDataBodyPart formDataBodyPart) {
    // -------------------------------------
    // (1) Get the user from the API key
    // -------------------------------------
    User authUser;
    try {
        authUser = findUserOrDie();
    } catch (WrappedResponse ex) {
        return error(Response.Status.FORBIDDEN, ResourceBundle.getBundle("Bundle").getString("file.addreplace.error.auth"));
    }
    if (DataCaptureModuleUtil.rsyncSupportEnabled(settingsSvc.getValueForKey(SettingsServiceBean.Key.UploadMethods))) {
        return error(Response.Status.METHOD_NOT_ALLOWED, SettingsServiceBean.Key.UploadMethods + " contains " + SystemConfig.FileUploadMethods.RSYNC + ". Please use rsync file upload.");
    }
    // -------------------------------------
    // (2) Get the Dataset Id
    // 
    // -------------------------------------
    Dataset dataset;
    Long datasetId;
    try {
        dataset = findDatasetOrDie(idSupplied);
    } catch (WrappedResponse wr) {
        return wr.getResponse();
    }
    // -------------------------------------
    // (3) Get the file name and content type
    // -------------------------------------
    String newFilename = contentDispositionHeader.getFileName();
    String newFileContentType = formDataBodyPart.getMediaType().toString();
    // (2a) Load up optional params via JSON
    // ---------------------------------------
    OptionalFileParams optionalFileParams = null;
    msgt("(api) jsonData: " + jsonData);
    try {
        optionalFileParams = new OptionalFileParams(jsonData);
    } catch (DataFileTagException ex) {
        return error(Response.Status.BAD_REQUEST, ex.getMessage());
    }
    // -------------------
    // (3) Create the AddReplaceFileHelper object
    // -------------------
    msg("ADD!");
    DataverseRequest dvRequest2 = createDataverseRequest(authUser);
    AddReplaceFileHelper addFileHelper = new AddReplaceFileHelper(dvRequest2, ingestService, datasetService, fileService, permissionSvc, commandEngine, systemConfig);
    // -------------------
    // (4) Run "runAddFileByDatasetId"
    // -------------------
    addFileHelper.runAddFileByDataset(dataset, newFilename, newFileContentType, fileInputStream, optionalFileParams);
    if (addFileHelper.hasError()) {
        return error(addFileHelper.getHttpErrorCode(), addFileHelper.getErrorMessagesAsString("\n"));
    } else {
        String successMsg = ResourceBundle.getBundle("Bundle").getString("file.addreplace.success.add");
        try {
            // msgt("as String: " + addFileHelper.getSuccessResult());
            /**
             * @todo We need a consistent, sane way to communicate a human
             * readable message to an API client suitable for human
             * consumption. Imagine if the UI were built in Angular or React
             * and we want to return a message from the API as-is to the
             * user. Human readable.
             */
            logger.fine("successMsg: " + successMsg);
            return ok(addFileHelper.getSuccessResultAsJsonObjectBuilder());
        // "Look at that!  You added a file! (hey hey, it may have worked)");
        } catch (NoFilesException ex) {
            Logger.getLogger(Files.class.getName()).log(Level.SEVERE, null, ex);
            return error(Response.Status.BAD_REQUEST, "NoFileException!  Serious Error! See administrator!");
        }
    }
}
Also used : DataverseRequest(edu.harvard.iq.dataverse.engine.command.DataverseRequest) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) User(edu.harvard.iq.dataverse.authorization.users.User) Dataset(edu.harvard.iq.dataverse.Dataset) NoFilesException(edu.harvard.iq.dataverse.datasetutility.NoFilesException) OptionalFileParams(edu.harvard.iq.dataverse.datasetutility.OptionalFileParams) DataFileTagException(edu.harvard.iq.dataverse.datasetutility.DataFileTagException) AddReplaceFileHelper(edu.harvard.iq.dataverse.datasetutility.AddReplaceFileHelper) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 2 with AddReplaceFileHelper

use of edu.harvard.iq.dataverse.datasetutility.AddReplaceFileHelper in project dataverse by IQSS.

the class Files method replaceFileInDataset.

/**
 * Replace an Existing File
 *
 * @param datasetId
 * @param testFileInputStream
 * @param contentDispositionHeader
 * @param formDataBodyPart
 * @return
 */
@POST
@Path("{id}/replace")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response replaceFileInDataset(@PathParam("id") Long fileToReplaceId, @FormDataParam("jsonData") String jsonData, @FormDataParam("file") InputStream testFileInputStream, @FormDataParam("file") FormDataContentDisposition contentDispositionHeader, @FormDataParam("file") final FormDataBodyPart formDataBodyPart) {
    // -------------------------------------
    // (1) Get the user from the API key
    // -------------------------------------
    User authUser;
    try {
        authUser = this.findUserOrDie();
    } catch (AbstractApiBean.WrappedResponse ex) {
        return error(Response.Status.FORBIDDEN, ResourceBundle.getBundle("Bundle").getString("file.addreplace.error.auth"));
    }
    // -------------------------------------
    // (2) Check/Parse the JSON (if uploaded)
    // -------------------------------------
    Boolean forceReplace = false;
    OptionalFileParams optionalFileParams = null;
    if (jsonData != null) {
        JsonObject jsonObj = null;
        try {
            jsonObj = new Gson().fromJson(jsonData, JsonObject.class);
            // -------------------------------------
            if ((jsonObj.has("forceReplace")) && (!jsonObj.get("forceReplace").isJsonNull())) {
                forceReplace = jsonObj.get("forceReplace").getAsBoolean();
                if (forceReplace == null) {
                    forceReplace = false;
                }
            }
            try {
                // (2b) Load up optional params via JSON
                // - Will skip extra attributes which includes fileToReplaceId and forceReplace
                // ---------------------------------------
                optionalFileParams = new OptionalFileParams(jsonData);
            } catch (DataFileTagException ex) {
                return error(Response.Status.BAD_REQUEST, ex.getMessage());
            }
        } catch (ClassCastException ex) {
            logger.info("Exception parsing string '" + jsonData + "': " + ex);
        }
    }
    // -------------------------------------
    // (3) Get the file name and content type
    // -------------------------------------
    String newFilename = contentDispositionHeader.getFileName();
    String newFileContentType = formDataBodyPart.getMediaType().toString();
    // -------------------
    // (4) Create the AddReplaceFileHelper object
    // -------------------
    msg("REPLACE!");
    DataverseRequest dvRequest2 = createDataverseRequest(authUser);
    AddReplaceFileHelper addFileHelper = new AddReplaceFileHelper(dvRequest2, this.ingestService, this.datasetService, this.fileService, this.permissionSvc, this.commandEngine, this.systemConfig);
    if (forceReplace) {
        addFileHelper.runForceReplaceFile(fileToReplaceId, newFilename, newFileContentType, testFileInputStream, optionalFileParams);
    } else {
        addFileHelper.runReplaceFile(fileToReplaceId, newFilename, newFileContentType, testFileInputStream, optionalFileParams);
    }
    msg("we're back.....");
    if (addFileHelper.hasError()) {
        msg("yes, has error");
        return error(addFileHelper.getHttpErrorCode(), addFileHelper.getErrorMessagesAsString("\n"));
    } else {
        msg("no error");
        String successMsg = ResourceBundle.getBundle("Bundle").getString("file.addreplace.success.replace");
        try {
            msgt("as String: " + addFileHelper.getSuccessResult());
            /**
             * @todo We need a consistent, sane way to communicate a human
             * readable message to an API client suitable for human
             * consumption. Imagine if the UI were built in Angular or React
             * and we want to return a message from the API as-is to the
             * user. Human readable.
             */
            logger.fine("successMsg: " + successMsg);
            return ok(addFileHelper.getSuccessResultAsJsonObjectBuilder());
        // return okResponseGsonObject(successMsg,
        // addFileHelper.getSuccessResultAsGsonObject());
        // "Look at that!  You added a file! (hey hey, it may have worked)");
        } catch (NoFilesException ex) {
            Logger.getLogger(Files.class.getName()).log(Level.SEVERE, null, ex);
            return error(Response.Status.BAD_REQUEST, "NoFileException!  Serious Error! See administrator!");
        }
    }
}
Also used : User(edu.harvard.iq.dataverse.authorization.users.User) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) AddReplaceFileHelper(edu.harvard.iq.dataverse.datasetutility.AddReplaceFileHelper) DataverseRequest(edu.harvard.iq.dataverse.engine.command.DataverseRequest) NoFilesException(edu.harvard.iq.dataverse.datasetutility.NoFilesException) OptionalFileParams(edu.harvard.iq.dataverse.datasetutility.OptionalFileParams) DataFileTagException(edu.harvard.iq.dataverse.datasetutility.DataFileTagException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 3 with AddReplaceFileHelper

use of edu.harvard.iq.dataverse.datasetutility.AddReplaceFileHelper in project dataverse by IQSS.

the class EditDatafilesPage method init.

public String init() {
    fileMetadatas = new ArrayList<>();
    newFiles = new ArrayList<>();
    uploadedFiles = new ArrayList<>();
    this.maxFileUploadSizeInBytes = systemConfig.getMaxFileUploadSize();
    this.multipleUploadFilesLimit = systemConfig.getMultipleUploadFilesLimit();
    if (dataset.getId() != null) {
        // Set Working Version and Dataset by Datasaet Id and Version
        // retrieveDatasetVersionResponse = datasetVersionService.retrieveDatasetVersionById(dataset.getId(), null);
        dataset = datasetService.find(dataset.getId());
        // files!)
        if (dataset == null || dataset.isHarvested()) {
            return permissionsWrapper.notFound();
        }
    } else {
        // that the dataset id is mandatory... But 404 will do for now.
        return permissionsWrapper.notFound();
    }
    workingVersion = dataset.getEditVersion();
    if (workingVersion == null || !workingVersion.isDraft()) {
        // Sorry, we couldn't find/obtain a draft version for this dataset!
        return permissionsWrapper.notFound();
    }
    if (!permissionService.on(dataset).has(Permission.EditDataset)) {
        return permissionsWrapper.notAuthorized();
    }
    // -------------------------------------------
    if (mode == FileEditMode.SINGLE_REPLACE) {
        /*
            http://localhost:8080/editdatafiles.xhtml?mode=SINGLE_REPLACE&datasetId=26&fid=726
            */
        DataFile fileToReplace = loadFileToReplace();
        if (fileToReplace == null) {
            return permissionsWrapper.notFound();
        }
        // DataverseRequest dvRequest2 = createDataverseRequest(authUser);
        AddReplaceFileHelper addReplaceFileHelper = new AddReplaceFileHelper(dvRequestService.getDataverseRequest(), ingestService, datasetService, datafileService, permissionService, commandEngine, systemConfig);
        fileReplacePageHelper = new FileReplacePageHelper(addReplaceFileHelper, dataset, fileToReplace);
        populateFileMetadatas();
        singleFile = getFileToReplace();
    } else if (mode == FileEditMode.EDIT || mode == FileEditMode.SINGLE) {
        if (selectedFileIdsString != null) {
            String[] ids = selectedFileIdsString.split(",");
            for (String id : ids) {
                Long test = null;
                try {
                    test = new Long(id);
                } catch (NumberFormatException nfe) {
                    // do nothing...
                    test = null;
                }
                if (test != null) {
                    if (mode == FileEditMode.SINGLE) {
                        singleFile = datafileService.find(test);
                    }
                    selectedFileIdsList.add(test);
                }
            }
        }
        if (selectedFileIdsList.size() < 1) {
            logger.fine("No numeric file ids supplied to the page, in the edit mode. Redirecting to the 404 page.");
            // If no valid file IDs specified, send them to the 404 page...
            return permissionsWrapper.notFound();
        }
        logger.fine("The page is called with " + selectedFileIdsList.size() + " file ids.");
        populateFileMetadatas();
        // datafiles are not present in the version specified, etc.
        if (fileMetadatas.size() < 1) {
            return permissionsWrapper.notFound();
        }
        if (FileEditMode.SINGLE == mode) {
            if (fileMetadatas.get(0).getDatasetVersion().getId() != null) {
                versionString = "DRAFT";
            }
        }
    }
    saveEnabled = true;
    if (mode == FileEditMode.UPLOAD) {
        JH.addMessage(FacesMessage.SEVERITY_INFO, getBundleString("dataset.message.uploadFiles"));
    }
    if (settingsService.isTrueForKey(SettingsServiceBean.Key.PublicInstall, false)) {
        JH.addMessage(FacesMessage.SEVERITY_WARN, getBundleString("dataset.message.publicInstall"));
    }
    return null;
}
Also used : AddReplaceFileHelper(edu.harvard.iq.dataverse.datasetutility.AddReplaceFileHelper) FileReplacePageHelper(edu.harvard.iq.dataverse.datasetutility.FileReplacePageHelper)

Aggregations

AddReplaceFileHelper (edu.harvard.iq.dataverse.datasetutility.AddReplaceFileHelper)3 User (edu.harvard.iq.dataverse.authorization.users.User)2 DataFileTagException (edu.harvard.iq.dataverse.datasetutility.DataFileTagException)2 NoFilesException (edu.harvard.iq.dataverse.datasetutility.NoFilesException)2 OptionalFileParams (edu.harvard.iq.dataverse.datasetutility.OptionalFileParams)2 DataverseRequest (edu.harvard.iq.dataverse.engine.command.DataverseRequest)2 Consumes (javax.ws.rs.Consumes)2 POST (javax.ws.rs.POST)2 Path (javax.ws.rs.Path)2 Gson (com.google.gson.Gson)1 JsonObject (com.google.gson.JsonObject)1 Dataset (edu.harvard.iq.dataverse.Dataset)1 AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)1 FileReplacePageHelper (edu.harvard.iq.dataverse.datasetutility.FileReplacePageHelper)1