Search in sources :

Example 16 with DataFile

use of edu.harvard.iq.dataverse.DataFile in project dataverse by IQSS.

the class WorldMapRelatedData method deleteWorldMapLayerData.

// end updateWorldMapLayerData
/*
        For WorldMap/GeoConnect Usage
        Delete MayLayerMetadata object for a given Datafile

        POST params
        {
           "GEOCONNECT_TOKEN": "-- some 64 char token which contains a link to the DataFile --"
        }
    */
@POST
@Path(DELETE_MAP_LAYER_DATA_API_PATH_FRAGMENT)
public Response deleteWorldMapLayerData(String jsonData) {
    /*----------------------------------
            Parse the json message.
            - Auth check: GEOCONNECT_TOKEN
        //----------------------------------*/
    if (jsonData == null) {
        logger.log(Level.SEVERE, "jsonData is null");
        return error(Response.Status.BAD_REQUEST, "No JSON data");
    }
    // (1) Parse JSON
    // 
    JsonObject jsonInfo;
    try (StringReader rdr = new StringReader(jsonData)) {
        jsonInfo = Json.createReader(rdr).readObject();
    } catch (JsonParsingException jpe) {
        logger.log(Level.SEVERE, "Json: " + jsonData);
        return error(Response.Status.BAD_REQUEST, "Error parsing Json: " + jpe.getMessage());
    }
    // (2) Retrieve token string
    String worldmapTokenParam = this.retrieveTokenValueFromJson(jsonInfo);
    if (worldmapTokenParam == null) {
        return error(Response.Status.BAD_REQUEST, "Token not found in JSON request.");
    }
    // (3) Retrieve WorldMapToken and make sure it is valid
    // 
    WorldMapToken wmToken = this.tokenServiceBean.retrieveAndRefreshValidToken(worldmapTokenParam);
    if (wmToken == null) {
        return error(Response.Status.UNAUTHORIZED, "No access. Invalid token.");
    }
    // 
    if (!(tokenServiceBean.canTokenUserEditFile(wmToken))) {
        tokenServiceBean.expireToken(wmToken);
        return error(Response.Status.UNAUTHORIZED, "No access. Invalid token.");
    }
    // (5) Attempt to retrieve DataFile and mapLayerMetadata
    DataFile dfile = wmToken.getDatafile();
    MapLayerMetadata mapLayerMetadata = this.mapLayerMetadataService.findMetadataByDatafile(dfile);
    if (mapLayerMetadata == null) {
        return error(Response.Status.EXPECTATION_FAILED, "No map layer metadata found.");
    }
    // 
    if (!(this.mapLayerMetadataService.deleteMapLayerMetadataObject(mapLayerMetadata, wmToken.getDataverseUser()))) {
        return error(Response.Status.PRECONDITION_FAILED, "Failed to delete layer");
    }
    ;
    return ok("Map layer metadata deleted.");
}
Also used : DataFile(edu.harvard.iq.dataverse.DataFile) MapLayerMetadata(edu.harvard.iq.dataverse.MapLayerMetadata) StringReader(java.io.StringReader) JsonObject(javax.json.JsonObject) WorldMapToken(edu.harvard.iq.dataverse.worldmapauth.WorldMapToken) JsonParsingException(javax.json.stream.JsonParsingException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 17 with DataFile

use of edu.harvard.iq.dataverse.DataFile in project dataverse by IQSS.

the class WorldMapRelatedData method updateWorldMapLayerData.

/*
        For WorldMap/GeoConnect Usage
        Create/Updated a MapLayerMetadata object for a given Datafile id
        
        Example of jsonLayerData String:
        {
             "layerName": "geonode:boston_census_blocks_zip_cr9"
            , "layerLink": "http://localhost:8000/data/geonode:boston_census_blocks_zip_cr9"
            , "embedMapLink": "http://localhost:8000/maps/embed/?layer=geonode:boston_census_blocks_zip_cr9"
            , "worldmapUsername": "dv_pete"
        }
    */
@POST
@Path(UPDATE_MAP_LAYER_DATA_API_PATH_FRAGMENT)
public Response updateWorldMapLayerData(String jsonLayerData) {
    // ----------------------------------
    if (jsonLayerData == null) {
        logger.log(Level.SEVERE, "jsonLayerData is null");
        return error(Response.Status.BAD_REQUEST, "No JSON data");
    }
    // (1) Parse JSON
    // 
    JsonObject jsonInfo;
    try (StringReader rdr = new StringReader(jsonLayerData)) {
        jsonInfo = Json.createReader(rdr).readObject();
    } catch (JsonParsingException jpe) {
        logger.log(Level.SEVERE, "Json: " + jsonLayerData);
        return error(Response.Status.BAD_REQUEST, "Error parsing Json: " + jpe.getMessage());
    }
    // Retrieve token string
    String worldmapTokenParam = this.retrieveTokenValueFromJson(jsonInfo);
    if (worldmapTokenParam == null) {
        return error(Response.Status.BAD_REQUEST, "Token not found in JSON request.");
    }
    // Retrieve WorldMapToken and make sure it is valid
    // 
    WorldMapToken wmToken = this.tokenServiceBean.retrieveAndRefreshValidToken(worldmapTokenParam);
    if (wmToken == null) {
        return error(Response.Status.UNAUTHORIZED, "No access. Invalid token.");
    }
    // 
    if (!(tokenServiceBean.canTokenUserEditFile(wmToken))) {
        tokenServiceBean.expireToken(wmToken);
        return error(Response.Status.UNAUTHORIZED, "No access. Invalid token.");
    }
    // 
    for (String attr : MapLayerMetadata.MANDATORY_JSON_FIELDS) {
        if (!jsonInfo.containsKey(attr)) {
            return error(Response.Status.BAD_REQUEST, "Error parsing Json.  Key not found [" + attr + "]\nRequired keys are: " + MapLayerMetadata.MANDATORY_JSON_FIELDS);
        }
    }
    // (3) Attempt to retrieve DataverseUser
    AuthenticatedUser dvUser = wmToken.getDataverseUser();
    if (dvUser == null) {
        return error(Response.Status.NOT_FOUND, "DataverseUser not found for token");
    }
    // (4) Attempt to retrieve DataFile
    DataFile dfile = wmToken.getDatafile();
    if (dfile == null) {
        return error(Response.Status.NOT_FOUND, "DataFile not found for token");
    }
    // check permissions!
    if (!permissionService.request(createDataverseRequest(dvUser)).on(dfile.getOwner()).has(Permission.EditDataset)) {
        String errMsg = "The user does not have permission to edit metadata for this file. (MapLayerMetadata)";
        return error(Response.Status.FORBIDDEN, errMsg);
    }
    // (5) See if a MapLayerMetadata already exists
    // 
    MapLayerMetadata mapLayerMetadata = this.mapLayerMetadataService.findMetadataByDatafile(dfile);
    if (mapLayerMetadata == null) {
        // Create a new mapLayerMetadata object
        mapLayerMetadata = new MapLayerMetadata();
    }
    // Create/Update new MapLayerMetadata object and save it
    mapLayerMetadata.setDataFile(dfile);
    mapLayerMetadata.setDataset(dfile.getOwner());
    mapLayerMetadata.setLayerName(jsonInfo.getString("layerName"));
    mapLayerMetadata.setLayerLink(jsonInfo.getString("layerLink"));
    mapLayerMetadata.setEmbedMapLink(jsonInfo.getString("embedMapLink"));
    mapLayerMetadata.setWorldmapUsername(jsonInfo.getString("worldmapUsername"));
    if (jsonInfo.containsKey("mapImageLink")) {
        mapLayerMetadata.setMapImageLink(jsonInfo.getString("mapImageLink"));
    }
    // If this was a tabular join set the attributes:
    // - isJoinLayer
    // - joinDescription
    // 
    String joinDescription = jsonInfo.getString("joinDescription", null);
    if ((joinDescription == null) || (joinDescription.equals(""))) {
        mapLayerMetadata.setIsJoinLayer(true);
        mapLayerMetadata.setJoinDescription(joinDescription);
    } else {
        mapLayerMetadata.setIsJoinLayer(false);
        mapLayerMetadata.setJoinDescription(null);
    }
    // Set the mapLayerLinks
    // 
    String mapLayerLinks = jsonInfo.getString("mapLayerLinks", null);
    if ((mapLayerLinks == null) || (mapLayerLinks.equals(""))) {
        mapLayerMetadata.setMapLayerLinks(null);
    } else {
        mapLayerMetadata.setMapLayerLinks(mapLayerLinks);
    }
    // mapLayer.save();
    MapLayerMetadata savedMapLayerMetadata = mapLayerMetadataService.save(mapLayerMetadata);
    if (savedMapLayerMetadata == null) {
        logger.log(Level.SEVERE, "Json: " + jsonLayerData);
        return error(Response.Status.BAD_REQUEST, "Failed to save map layer!  Original JSON: ");
    }
    // notify user
    userNotificationService.sendNotification(dvUser, wmToken.getCurrentTimestamp(), UserNotification.Type.MAPLAYERUPDATED, dfile.getOwner().getLatestVersion().getId());
    // ------------------------------------------
    try {
        logger.info("retrieveMapImageForIcon");
        this.mapLayerMetadataService.retrieveMapImageForIcon(savedMapLayerMetadata);
    } catch (IOException ex) {
        logger.severe("Failed to retrieve image from WorldMap server");
        Logger.getLogger(WorldMapRelatedData.class.getName()).log(Level.SEVERE, null, ex);
    }
    return ok("map layer object saved!");
}
Also used : DataFile(edu.harvard.iq.dataverse.DataFile) MapLayerMetadata(edu.harvard.iq.dataverse.MapLayerMetadata) StringReader(java.io.StringReader) JsonObject(javax.json.JsonObject) WorldMapToken(edu.harvard.iq.dataverse.worldmapauth.WorldMapToken) IOException(java.io.IOException) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) JsonParsingException(javax.json.stream.JsonParsingException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 18 with DataFile

use of edu.harvard.iq.dataverse.DataFile in project dataverse by IQSS.

the class WorldMapRelatedData method mapDataFileTokenOnlyOption.

/*
        Link used within Dataverse for MapIt button
        Sends file link to GeoConnect using a Redirect
    
    */
// @GET
// @Path( MAP_IT_API_PATH_FRAGMENT + "token-option/{datafile_id}/{dvuser_id}/{token_only}")
private Response mapDataFileTokenOnlyOption(@Context HttpServletRequest request, Long datafile_id, Long dvuser_id, boolean tokenOnly) {
    logger.log(Level.INFO, "mapDataFile datafile_id: {0}", datafile_id);
    logger.log(Level.INFO, "mapDataFile dvuser_id: {0}", dvuser_id);
    AuthenticatedUser user = null;
    if (session != null) {
        if (session.getUser() != null) {
            if (session.getUser().isAuthenticated()) {
                user = (AuthenticatedUser) session.getUser();
            }
        }
    }
    if (user == null) {
        return error(Response.Status.FORBIDDEN, "Not logged in");
    }
    if (true) {
    // return okResponse( "Looks good " + datafile_id);
    // tokenAppServiceBean.getGeoConnectApplication();
    // return okResponse("Currently deactivated (mapDataFile)");
    }
    // Check if the user exists
    AuthenticatedUser dvUser = dataverseUserService.findByID(dvuser_id);
    if (dvUser == null) {
        return error(Response.Status.FORBIDDEN, "Invalid user");
    }
    // Check if this file exists
    DataFile dfile = dataFileService.find(datafile_id);
    if (dfile == null) {
        return error(Response.Status.NOT_FOUND, "DataFile not found for id: " + datafile_id);
    }
    /*
            Is the dataset public?
        */
    if (!dfile.getOwner().isReleased()) {
        return error(Response.Status.FORBIDDEN, "Mapping is only permitted for public datasets/files");
    }
    // Does this user have permission to edit metadata for this file?
    if (!permissionService.request(createDataverseRequest(dvUser)).on(dfile.getOwner()).has(Permission.EditDataset)) {
        String errMsg = "The user does not have permission to edit metadata for this file.";
        return error(Response.Status.FORBIDDEN, errMsg);
    }
    WorldMapToken token = tokenServiceBean.getNewToken(dfile, dvUser);
    if (tokenOnly) {
        // Return only the token in a JSON object
        final JsonObjectBuilder jsonInfo = Json.createObjectBuilder();
        jsonInfo.add(WorldMapToken.GEOCONNECT_TOKEN_KEY, token.getToken());
        return ok(jsonInfo);
    }
    // Redirect to geoconnect url
    String callback_url = systemConfig.getDataverseSiteUrl() + GET_WORLDMAP_DATAFILE_API_PATH;
    String redirect_url_str = token.getApplication().getMapitLink() + "/" + token.getToken() + "/?cb=" + URLEncoder.encode(callback_url);
    URI redirect_uri;
    try {
        redirect_uri = new URI(redirect_url_str);
    } catch (URISyntaxException ex) {
        return error(Response.Status.NOT_FOUND, "Faile to create URI from: " + redirect_url_str);
    }
    // Response.
    return Response.seeOther(redirect_uri).build();
}
Also used : DataFile(edu.harvard.iq.dataverse.DataFile) WorldMapToken(edu.harvard.iq.dataverse.worldmapauth.WorldMapToken) URISyntaxException(java.net.URISyntaxException) JsonObjectBuilder(javax.json.JsonObjectBuilder) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) URI(java.net.URI)

Example 19 with DataFile

use of edu.harvard.iq.dataverse.DataFile in project dataverse by IQSS.

the class WorldMapRelatedData method getWorldMapDatafileInfo.

/**
 * Retrieve FileMetadata for Use by WorldMap.
 *  This includes information about the DataFile, Dataset, DatasetVersion, and Dataverse
 *
 * @param jsonTokenData
 * @param request
 * @return
 */
@POST
// + "{worldmap_token}")
@Path(GET_WORLDMAP_DATAFILE_API_PATH_FRAGMENT)
public Response getWorldMapDatafileInfo(String jsonTokenData, @Context HttpServletRequest request) {
    // , @PathParam("worldmap_token") String worldmapTokenParam) {
    if (true) {
    // return okResponse("Currently deactivated");
    // return okResponse("remote server: " + request.getRemoteAddr());
    }
    logger.info("API call: getWorldMapDatafileInfo");
    // ----------------------------------
    // Auth check: Parse the json message and check for a valid GEOCONNECT_TOKEN_KEY and GEOCONNECT_TOKEN_VALUE
    // -- For testing, the GEOCONNECT_TOKEN_VALUE will be dynamic, found in the db
    // ----------------------------------
    logger.info("(1) jsonTokenData: " + jsonTokenData);
    // Parse JSON
    JsonObject jsonTokenInfo;
    try (StringReader rdr = new StringReader(jsonTokenData)) {
        jsonTokenInfo = Json.createReader(rdr).readObject();
    } catch (JsonParsingException jpe) {
        logger.log(Level.SEVERE, "Json: " + jsonTokenData);
        return error(Response.Status.BAD_REQUEST, "Error parsing Json: " + jpe.getMessage());
    }
    logger.info("(1a) jsonTokenInfo: " + jsonTokenInfo);
    // Retrieve token string
    String worldmapTokenParam = this.retrieveTokenValueFromJson(jsonTokenInfo);
    logger.info("(1b) token from JSON: " + worldmapTokenParam);
    if (worldmapTokenParam == null) {
        return error(Response.Status.BAD_REQUEST, "Token not found in JSON request.");
    }
    // Retrieve WorldMapToken and make sure it is valid
    // 
    WorldMapToken wmToken = tokenServiceBean.retrieveAndRefreshValidToken(worldmapTokenParam);
    logger.info("(2) token retrieved from db: " + wmToken);
    if (wmToken == null) {
        return error(Response.Status.UNAUTHORIZED, "No access. Invalid token.");
    }
    // Make sure the token's User still has permissions to access the file
    // 
    logger.info("(3) check permissions");
    if (!(tokenServiceBean.canTokenUserEditFile(wmToken))) {
        tokenServiceBean.expireToken(wmToken);
        return error(Response.Status.UNAUTHORIZED, "No access. Invalid token.");
    }
    // (1) Retrieve token connected data: DataverseUser, DataFile
    // 
    // Make sure token user and file are still available
    // 
    AuthenticatedUser dvUser = wmToken.getDataverseUser();
    if (dvUser == null) {
        return error(Response.Status.NOT_FOUND, "DataverseUser not found for token");
    }
    DataFile dfile = wmToken.getDatafile();
    if (dfile == null) {
        return error(Response.Status.NOT_FOUND, "DataFile not found for token");
    }
    // (1a) Retrieve FileMetadata
    FileMetadata dfile_meta = dfile.getFileMetadata();
    if (dfile_meta == null) {
        return error(Response.Status.NOT_FOUND, "FileMetadata not found");
    }
    // (2) Now get the dataset and the latest DatasetVersion
    Dataset dset = dfile.getOwner();
    if (dset == null) {
        return error(Response.Status.NOT_FOUND, "Owning Dataset for this DataFile not found");
    }
    // (2a) latest DatasetVersion
    // !! How do you check if the lastest version has this specific file?
    // 
    DatasetVersion dset_version = dset.getLatestVersion();
    if (dset_version == null) {
        return error(Response.Status.NOT_FOUND, "Latest DatasetVersion for this DataFile not found");
    }
    // (3) get Dataverse
    Dataverse dverse = dset.getOwner();
    if (dverse == null) {
        return error(Response.Status.NOT_FOUND, "Dataverse for this DataFile's Dataset not found");
    }
    // (4) Roll it all up in a JSON response
    final JsonObjectBuilder jsonData = Json.createObjectBuilder();
    // ------------------------------------
    if (dfile.isShapefileType()) {
        jsonData.add("mapping_type", "shapefile");
    } else if (dfile.isTabularData()) {
        jsonData.add("mapping_type", "tabular");
    } else {
        logger.log(Level.SEVERE, "This was neither a Shapefile nor a Tabular data file.  DataFile id: " + dfile.getId());
        return error(Response.Status.BAD_REQUEST, "Sorry! This file does not have mapping data. Please contact the Dataverse administrator. DataFile id: " + dfile.getId());
    }
    // ------------------------------------
    // DataverseUser Info
    // ------------------------------------
    jsonData.add("dv_user_id", dvUser.getId());
    jsonData.add("dv_username", dvUser.getUserIdentifier());
    jsonData.add("dv_user_email", dvUser.getEmail());
    // ------------------------------------
    // Dataverse URLs to this server
    // ------------------------------------
    String serverName = systemConfig.getDataverseSiteUrl();
    jsonData.add("return_to_dataverse_url", dset_version.getReturnToFilePageURL(serverName, dset, dfile));
    jsonData.add("datafile_download_url", dfile.getMapItFileDownloadURL(serverName));
    // ------------------------------------
    // Dataverse
    // ------------------------------------
    // jsonData.add("dataverse_installation_name", "Harvard Dataverse"); // todo / fix
    // is this enough to distinguish a dataverse installation?
    jsonData.add("dataverse_installation_name", systemConfig.getDataverseSiteUrl());
    jsonData.add("dataverse_id", dverse.getId());
    jsonData.add("dataverse_name", dverse.getName());
    String dataverseDesc = dverse.getDescription();
    if (dataverseDesc == null || dataverseDesc.equalsIgnoreCase("")) {
        dataverseDesc = "";
    }
    jsonData.add("dataverse_description", dataverseDesc);
    // ------------------------------------
    // Dataset Info
    // ------------------------------------
    jsonData.add("dataset_id", dset.getId());
    // ------------------------------------
    // DatasetVersion Info
    // ------------------------------------
    // database id
    jsonData.add("dataset_version_id", dset_version.getId());
    // major/minor version number, e.g. 3.1
    jsonData.add("dataset_semantic_version", dset_version.getSemanticVersion());
    jsonData.add("dataset_name", dset_version.getTitle());
    jsonData.add("dataset_citation", dset_version.getCitation(true));
    // Need to fix to/do
    jsonData.add("dataset_description", "");
    jsonData.add("dataset_is_public", dset_version.isReleased());
    // ------------------------------------
    // DataFile/FileMetaData Info
    // ------------------------------------
    jsonData.add("datafile_id", dfile.getId());
    jsonData.add("datafile_label", dfile_meta.getLabel());
    // jsonData.add("filename", dfile_meta.getLabel());
    jsonData.add("datafile_expected_md5_checksum", dfile.getChecksumValue());
    Long fsize = dfile.getFilesize();
    if (fsize == null) {
        fsize = new Long(-1);
    }
    jsonData.add("datafile_filesize", fsize);
    jsonData.add("datafile_content_type", dfile.getContentType());
    jsonData.add("datafile_create_datetime", dfile.getCreateDate().toString());
    // restriction status of the DataFile
    jsonData.add("datafile_is_restricted", dfile.isRestricted());
    return ok(jsonData);
}
Also used : Dataset(edu.harvard.iq.dataverse.Dataset) FileMetadata(edu.harvard.iq.dataverse.FileMetadata) JsonObject(javax.json.JsonObject) WorldMapToken(edu.harvard.iq.dataverse.worldmapauth.WorldMapToken) DatasetVersion(edu.harvard.iq.dataverse.DatasetVersion) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Dataverse(edu.harvard.iq.dataverse.Dataverse) DataFile(edu.harvard.iq.dataverse.DataFile) StringReader(java.io.StringReader) JsonObjectBuilder(javax.json.JsonObjectBuilder) JsonParsingException(javax.json.stream.JsonParsingException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 20 with DataFile

use of edu.harvard.iq.dataverse.DataFile in project dataverse by IQSS.

the class MediaResourceManagerImpl method replaceOrAddFiles.

DepositReceipt replaceOrAddFiles(String uri, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration swordConfiguration, boolean shouldReplace) throws SwordError, SwordAuthException, SwordServerException {
    AuthenticatedUser user = swordAuth.auth(authCredentials);
    DataverseRequest dvReq = new DataverseRequest(user, httpRequest);
    urlManager.processUrl(uri);
    String globalId = urlManager.getTargetIdentifier();
    if (urlManager.getTargetType().equals("study") && globalId != null) {
        logger.fine("looking up dataset with globalId " + globalId);
        Dataset dataset = datasetService.findByGlobalId(globalId);
        if (dataset == null) {
            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not find dataset with global ID of " + globalId);
        }
        UpdateDatasetCommand updateDatasetCommand = new UpdateDatasetCommand(dataset, dvReq);
        if (!permissionService.isUserAllowedOn(user, updateDatasetCommand, dataset)) {
            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "user " + user.getDisplayInfo().getTitle() + " is not authorized to modify dataset with global ID " + dataset.getGlobalId());
        }
        // -------------------------------------
        if (DataCaptureModuleUtil.rsyncSupportEnabled(settingsSvc.getValueForKey(SettingsServiceBean.Key.UploadMethods))) {
            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, SettingsServiceBean.Key.UploadMethods + " contains " + SystemConfig.FileUploadMethods.RSYNC + ". Please use rsync file upload.");
        }
        /**
         * @todo decide if we want non zip files to work. Technically, now
         * that we're letting ingestService.createDataFiles unpack the zip
         * for us, the following *does* work:
         *
         * curl--data-binary @path/to/trees.png -H "Content-Disposition:
         * filename=trees.png" -H "Content-Type: image/png" -H "Packaging:
         * http://purl.org/net/sword/package/SimpleZip"
         *
         * We *might* want to continue to force API users to only upload zip
         * files so that some day we can support a including a file or files
         * that contain the metadata (i.e. description) for each file in the
         * zip: https://github.com/IQSS/dataverse/issues/723
         */
        if (!deposit.getPackaging().equals(UriRegistry.PACKAGE_SIMPLE_ZIP)) {
            throw new SwordError(UriRegistry.ERROR_CONTENT, 415, "Package format " + UriRegistry.PACKAGE_SIMPLE_ZIP + " is required but format specified in 'Packaging' HTTP header was " + deposit.getPackaging());
        }
        String uploadedZipFilename = deposit.getFilename();
        DatasetVersion editVersion = dataset.getEditVersion();
        if (deposit.getInputStream() == null) {
            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Deposit input stream was null.");
        }
        int bytesAvailableInInputStream = 0;
        try {
            bytesAvailableInInputStream = deposit.getInputStream().available();
        } catch (IOException ex) {
            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not determine number of bytes available in input stream: " + ex);
        }
        if (bytesAvailableInInputStream == 0) {
            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Bytes available in input stream was " + bytesAvailableInInputStream + ". Please check the file you are attempting to deposit.");
        }
        /**
         * @todo Think about if we should instead pass in "application/zip"
         * rather than letting ingestService.createDataFiles() guess the
         * contentType by passing it "null". See also the note above about
         * SimpleZip vs. other contentTypes.
         */
        String guessContentTypeForMe = null;
        List<DataFile> dataFiles = new ArrayList<>();
        try {
            try {
                dataFiles = FileUtil.createDataFiles(editVersion, deposit.getInputStream(), uploadedZipFilename, guessContentTypeForMe, systemConfig);
            } catch (EJBException ex) {
                Throwable cause = ex.getCause();
                if (cause != null) {
                    if (cause instanceof IllegalArgumentException) {
                        /**
                         * @todo should be safe to remove this catch of
                         * EJBException and IllegalArgumentException once
                         * this ticket is resolved:
                         *
                         * IllegalArgumentException: MALFORMED when
                         * uploading certain zip files
                         * https://github.com/IQSS/dataverse/issues/1021
                         */
                        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Exception caught calling ingestService.createDataFiles. Problem with zip file, perhaps: " + cause);
                    } else {
                        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Exception caught calling ingestService.createDataFiles: " + cause);
                    }
                } else {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Exception caught calling ingestService.createDataFiles. No cause: " + ex.getMessage());
                }
            }
        /*TODO: L.A. 4.6! catch (FileExceedsMaxSizeException ex) {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Exception caught calling ingestService.createDataFiles: " + ex.getMessage());
                    //Logger.getLogger(MediaResourceManagerImpl.class.getName()).log(Level.SEVERE, null, ex);
                }*/
        } catch (IOException ex) {
            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unable to add file(s) to dataset: " + ex.getMessage());
        }
        if (!dataFiles.isEmpty()) {
            Set<ConstraintViolation> constraintViolations = editVersion.validate();
            if (constraintViolations.size() > 0) {
                ConstraintViolation violation = constraintViolations.iterator().next();
                throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unable to add file(s) to dataset: " + violation.getMessage() + " The invalid value was \"" + violation.getInvalidValue() + "\".");
            } else {
                ingestService.addFiles(editVersion, dataFiles);
            }
        } else {
            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "No files to add to dataset. Perhaps the zip file was empty.");
        }
        try {
            dataset = commandEngine.submit(updateDatasetCommand);
        } catch (CommandException ex) {
            throw returnEarly("Couldn't update dataset " + ex);
        } catch (EJBException ex) {
            /**
             * @todo stop bothering to catch an EJBException once this has
             * been implemented:
             *
             * Have commands catch ConstraintViolationException and turn
             * them into something that inherits from CommandException ยท
             * https://github.com/IQSS/dataverse/issues/1009
             */
            Throwable cause = ex;
            StringBuilder sb = new StringBuilder();
            sb.append(ex.getLocalizedMessage());
            while (cause.getCause() != null) {
                cause = cause.getCause();
                sb.append(cause + " ");
                if (cause instanceof ConstraintViolationException) {
                    ConstraintViolationException constraintViolationException = (ConstraintViolationException) cause;
                    for (ConstraintViolation<?> violation : constraintViolationException.getConstraintViolations()) {
                        sb.append(" Invalid value \"").append(violation.getInvalidValue()).append("\" for ").append(violation.getPropertyPath()).append(" at ").append(violation.getLeafBean()).append(" - ").append(violation.getMessage());
                    }
                }
            }
            throw returnEarly("EJBException: " + sb.toString());
        }
        ingestService.startIngestJobs(dataset, user);
        ReceiptGenerator receiptGenerator = new ReceiptGenerator();
        String baseUrl = urlManager.getHostnamePlusBaseUrlPath(uri);
        DepositReceipt depositReceipt = receiptGenerator.createDatasetReceipt(baseUrl, dataset);
        return depositReceipt;
    } else {
        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unable to determine target type or identifier from URL: " + uri);
    }
}
Also used : SwordError(org.swordapp.server.SwordError) Dataset(edu.harvard.iq.dataverse.Dataset) ArrayList(java.util.ArrayList) DatasetVersion(edu.harvard.iq.dataverse.DatasetVersion) IOException(java.io.IOException) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) DataverseRequest(edu.harvard.iq.dataverse.engine.command.DataverseRequest) DataFile(edu.harvard.iq.dataverse.DataFile) DepositReceipt(org.swordapp.server.DepositReceipt) ConstraintViolation(javax.validation.ConstraintViolation) ConstraintViolationException(javax.validation.ConstraintViolationException) EJBException(javax.ejb.EJBException) UpdateDatasetCommand(edu.harvard.iq.dataverse.engine.command.impl.UpdateDatasetCommand)

Aggregations

DataFile (edu.harvard.iq.dataverse.DataFile)111 Dataset (edu.harvard.iq.dataverse.Dataset)39 IOException (java.io.IOException)39 FileMetadata (edu.harvard.iq.dataverse.FileMetadata)30 ArrayList (java.util.ArrayList)25 DatasetVersion (edu.harvard.iq.dataverse.DatasetVersion)20 File (java.io.File)20 FileNotFoundException (java.io.FileNotFoundException)18 Path (javax.ws.rs.Path)18 Dataverse (edu.harvard.iq.dataverse.Dataverse)17 FileInputStream (java.io.FileInputStream)16 AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)14 CommandException (edu.harvard.iq.dataverse.engine.command.exception.CommandException)13 Date (java.util.Date)13 GET (javax.ws.rs.GET)13 Test (org.junit.Test)13 Timestamp (java.sql.Timestamp)11 InputStream (java.io.InputStream)10 DataVariable (edu.harvard.iq.dataverse.datavariable.DataVariable)8 FileOutputStream (java.io.FileOutputStream)8