Search in sources :

Example 6 with JsonParser

use of edu.harvard.iq.dataverse.util.json.JsonParser in project dataverse by IQSS.

the class Groups method postIpGroup.

/**
 * Creates a new {@link IpGroup}. The name of the group is based on the
 * {@code alias:} field, but might be changed to ensure uniqueness.
 * @param dto
 * @return Response describing the created group or the error that prevented
 *         that group from being created.
 */
@POST
@Path("ip")
public Response postIpGroup(JsonObject dto) {
    try {
        IpGroup grp = new JsonParser().parseIpGroup(dto);
        grp.setGroupProvider(ipGroupPrv);
        grp.setPersistedGroupAlias(ipGroupPrv.findAvailableName(grp.getPersistedGroupAlias() == null ? "ipGroup" : grp.getPersistedGroupAlias()));
        grp = ipGroupPrv.store(grp);
        return created("/groups/ip/" + grp.getPersistedGroupAlias(), json(grp));
    } catch (Exception e) {
        logger.log(Level.WARNING, "Error while storing a new IP group: " + e.getMessage(), e);
        return error(Response.Status.INTERNAL_SERVER_ERROR, "Error: " + e.getMessage());
    }
}
Also used : IpGroup(edu.harvard.iq.dataverse.authorization.groups.impl.ipaddress.IpGroup) JsonParser(edu.harvard.iq.dataverse.util.json.JsonParser) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 7 with JsonParser

use of edu.harvard.iq.dataverse.util.json.JsonParser in project dataverse by IQSS.

the class ImportServiceBean method doImportHarvestedDataset.

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public Dataset doImportHarvestedDataset(DataverseRequest dataverseRequest, HarvestingClient harvestingClient, String harvestIdentifier, String metadataFormat, File metadataFile, PrintWriter cleanupLog) throws ImportException, IOException {
    if (harvestingClient == null || harvestingClient.getDataverse() == null) {
        throw new ImportException("importHarvestedDataset called wiht a null harvestingClient, or an invalid harvestingClient.");
    }
    Dataverse owner = harvestingClient.getDataverse();
    Dataset importedDataset = null;
    DatasetDTO dsDTO = null;
    String json = null;
    if ("ddi".equalsIgnoreCase(metadataFormat) || "oai_ddi".equals(metadataFormat) || metadataFormat.toLowerCase().matches("^oai_ddi.*")) {
        try {
            String xmlToParse = new String(Files.readAllBytes(metadataFile.toPath()));
            // TODO:
            // import type should be configurable - it should be possible to
            // select whether you want to harvest with or without files,
            // ImportType.HARVEST vs. ImportType.HARVEST_WITH_FILES
            logger.fine("importing DDI " + metadataFile.getAbsolutePath());
            dsDTO = importDDIService.doImport(ImportType.HARVEST_WITH_FILES, xmlToParse);
        } catch (IOException | XMLStreamException | ImportException e) {
            throw new ImportException("Failed to process DDI XML record: " + e.getClass() + " (" + e.getMessage() + ")");
        }
    } else if ("dc".equalsIgnoreCase(metadataFormat) || "oai_dc".equals(metadataFormat)) {
        logger.fine("importing DC " + metadataFile.getAbsolutePath());
        try {
            String xmlToParse = new String(Files.readAllBytes(metadataFile.toPath()));
            dsDTO = importGenericService.processOAIDCxml(xmlToParse);
        } catch (IOException | XMLStreamException e) {
            throw new ImportException("Failed to process Dublin Core XML record: " + e.getClass() + " (" + e.getMessage() + ")");
        }
    } else if ("dataverse_json".equals(metadataFormat)) {
        // This is Dataverse metadata already formatted in JSON.
        // Simply read it into a string, and pass to the final import further down:
        logger.fine("Attempting to import custom dataverse metadata from file " + metadataFile.getAbsolutePath());
        json = new String(Files.readAllBytes(metadataFile.toPath()));
    } else {
        throw new ImportException("Unsupported import metadata format: " + metadataFormat);
    }
    if (json == null) {
        if (dsDTO != null) {
            // convert DTO to Json,
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            json = gson.toJson(dsDTO);
            logger.fine("JSON produced for the metadata harvested: " + json);
        } else {
            throw new ImportException("Failed to transform XML metadata format " + metadataFormat + " into a DatasetDTO");
        }
    }
    JsonReader jsonReader = Json.createReader(new StringReader(json));
    JsonObject obj = jsonReader.readObject();
    // and call parse Json to read it into a dataset
    try {
        JsonParser parser = new JsonParser(datasetfieldService, metadataBlockService, settingsService);
        parser.setLenient(true);
        Dataset ds = parser.parseDataset(obj);
        // For ImportType.NEW, if the metadata contains a global identifier, and it's not a protocol
        // we support, it should be rejected.
        // (TODO: ! - add some way of keeping track of supported protocols!)
        // if (ds.getGlobalId() != null && !ds.getProtocol().equals(settingsService.getValueForKey(SettingsServiceBean.Key.Protocol, ""))) {
        // throw new ImportException("Could not register id " + ds.getGlobalId() + ", protocol not supported");
        // }
        ds.setOwner(owner);
        ds.getLatestVersion().setDatasetFields(ds.getLatestVersion().initDatasetFields());
        // Check data against required contraints
        List<ConstraintViolation<DatasetField>> violations = ds.getVersions().get(0).validateRequired();
        if (!violations.isEmpty()) {
            // For migration and harvest, add NA for missing required values
            for (ConstraintViolation<DatasetField> v : violations) {
                DatasetField f = v.getRootBean();
                f.setSingleValue(DatasetField.NA_VALUE);
            }
        }
        // Check data against validation constraints
        // If we are migrating and "scrub migration data" is true we attempt to fix invalid data
        // if the fix fails stop processing of this file by throwing exception
        Set<ConstraintViolation> invalidViolations = ds.getVersions().get(0).validate();
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        if (!invalidViolations.isEmpty()) {
            for (ConstraintViolation<DatasetFieldValue> v : invalidViolations) {
                DatasetFieldValue f = v.getRootBean();
                boolean fixed = false;
                boolean converted = false;
                // TODO: Is this scrubbing something we want to continue doing?
                if (settingsService.isTrueForKey(SettingsServiceBean.Key.ScrubMigrationData, false)) {
                    fixed = processMigrationValidationError(f, cleanupLog, metadataFile.getName());
                    converted = true;
                    if (fixed) {
                        Set<ConstraintViolation<DatasetFieldValue>> scrubbedViolations = validator.validate(f);
                        if (!scrubbedViolations.isEmpty()) {
                            fixed = false;
                        }
                    }
                }
                if (!fixed) {
                    String msg = "Data modified - File: " + metadataFile.getName() + "; Field: " + f.getDatasetField().getDatasetFieldType().getDisplayName() + "; " + "Invalid value:  '" + f.getValue() + "'" + " Converted Value:'" + DatasetField.NA_VALUE + "'";
                    cleanupLog.println(msg);
                    f.setValue(DatasetField.NA_VALUE);
                }
            }
        }
        // this dataset:
        if (StringUtils.isEmpty(ds.getGlobalId())) {
            throw new ImportException("The harvested metadata record with the OAI server identifier " + harvestIdentifier + " does not contain a global unique identifier that we could recognize, skipping.");
        }
        ds.setHarvestedFrom(harvestingClient);
        ds.setHarvestIdentifier(harvestIdentifier);
        Dataset existingDs = datasetService.findByGlobalId(ds.getGlobalId());
        if (existingDs != null) {
            // we are just going to skip it!
            if (existingDs.getOwner() != null && !owner.getId().equals(existingDs.getOwner().getId())) {
                throw new ImportException("The dataset with the global id " + ds.getGlobalId() + " already exists, in the dataverse " + existingDs.getOwner().getAlias() + ", skipping.");
            }
            // skip it also:
            if (!existingDs.isHarvested()) {
                throw new ImportException("A LOCAL dataset with the global id " + ds.getGlobalId() + " already exists in this dataverse; skipping.");
            }
            // We will replace the current version with the imported version.
            if (existingDs.getVersions().size() != 1) {
                throw new ImportException("Error importing Harvested Dataset, existing dataset has " + existingDs.getVersions().size() + " versions");
            }
            // Purge all the SOLR documents associated with this client from the
            // index server:
            indexService.deleteHarvestedDocuments(existingDs);
            // DeleteFileCommand on them.
            for (DataFile harvestedFile : existingDs.getFiles()) {
                DataFile merged = em.merge(harvestedFile);
                em.remove(merged);
                harvestedFile = null;
            }
            // TODO:
            // Verify what happens with the indexed files in SOLR?
            // are they going to be overwritten by the reindexing of the dataset?
            existingDs.setFiles(null);
            Dataset merged = em.merge(existingDs);
            engineSvc.submit(new DestroyDatasetCommand(merged, dataverseRequest));
            importedDataset = engineSvc.submit(new CreateDatasetCommand(ds, dataverseRequest, false, ImportType.HARVEST));
        } else {
            importedDataset = engineSvc.submit(new CreateDatasetCommand(ds, dataverseRequest, false, ImportType.HARVEST));
        }
    } catch (JsonParseException | ImportException | CommandException ex) {
        logger.fine("Failed to import harvested dataset: " + ex.getClass() + ": " + ex.getMessage());
        FileOutputStream savedJsonFileStream = new FileOutputStream(new File(metadataFile.getAbsolutePath() + ".json"));
        byte[] jsonBytes = json.getBytes();
        int i = 0;
        while (i < jsonBytes.length) {
            int chunkSize = i + 8192 <= jsonBytes.length ? 8192 : jsonBytes.length - i;
            savedJsonFileStream.write(jsonBytes, i, chunkSize);
            i += chunkSize;
            savedJsonFileStream.flush();
        }
        savedJsonFileStream.close();
        logger.info("JSON produced saved in " + metadataFile.getAbsolutePath() + ".json");
        throw new ImportException("Failed to import harvested dataset: " + ex.getClass() + " (" + ex.getMessage() + ")", ex);
    }
    return importedDataset;
}
Also used : DatasetField(edu.harvard.iq.dataverse.DatasetField) CreateDatasetCommand(edu.harvard.iq.dataverse.engine.command.impl.CreateDatasetCommand) Gson(com.google.gson.Gson) JsonObject(javax.json.JsonObject) JsonParseException(edu.harvard.iq.dataverse.util.json.JsonParseException) DatasetDTO(edu.harvard.iq.dataverse.api.dto.DatasetDTO) DataFile(edu.harvard.iq.dataverse.DataFile) DatasetFieldValue(edu.harvard.iq.dataverse.DatasetFieldValue) StringReader(java.io.StringReader) JsonReader(javax.json.JsonReader) JsonParser(edu.harvard.iq.dataverse.util.json.JsonParser) ValidatorFactory(javax.validation.ValidatorFactory) GsonBuilder(com.google.gson.GsonBuilder) Dataset(edu.harvard.iq.dataverse.Dataset) IOException(java.io.IOException) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException) Dataverse(edu.harvard.iq.dataverse.Dataverse) XMLStreamException(javax.xml.stream.XMLStreamException) ConstraintViolation(javax.validation.ConstraintViolation) FileOutputStream(java.io.FileOutputStream) DataFile(edu.harvard.iq.dataverse.DataFile) File(java.io.File) Validator(javax.validation.Validator) DestroyDatasetCommand(edu.harvard.iq.dataverse.engine.command.impl.DestroyDatasetCommand) TransactionAttribute(javax.ejb.TransactionAttribute)

Example 8 with JsonParser

use of edu.harvard.iq.dataverse.util.json.JsonParser in project dataverse by IQSS.

the class ImportGenericServiceBean method importDCTerms.

public void importDCTerms(String xmlToParse, DatasetVersion datasetVersion, DatasetFieldServiceBean datasetFieldSvc, MetadataBlockServiceBean blockService, SettingsServiceBean settingsService) {
    DatasetDTO datasetDTO = this.initializeDataset();
    try {
        // Read docDescr and studyDesc into DTO objects.
        Map<String, String> fileMap = mapDCTerms(xmlToParse, datasetDTO);
        // 
        // convert DTO to Json,
        Gson gson = new Gson();
        String json = gson.toJson(datasetDTO.getDatasetVersion());
        JsonReader jsonReader = Json.createReader(new StringReader(json));
        JsonObject obj = jsonReader.readObject();
        // and call parse Json to read it into a datasetVersion
        DatasetVersion dv = new JsonParser(datasetFieldSvc, blockService, settingsService).parseDatasetVersion(obj, datasetVersion);
    } catch (XMLStreamException | JsonParseException e) {
        // EMK TODO: exception handling
        e.printStackTrace();
    }
// EMK TODO:  Call methods for reading FileMetadata and related objects from xml, return list of FileMetadata objects.
/*try {
            
         Map<String, DataTable> dataTableMap = new DataTableImportDDI().processDataDscr(xmlr);
         } catch(Exception e) {
            
         }*/
// Save Dataset and DatasetVersion in database
}
Also used : XMLStreamException(javax.xml.stream.XMLStreamException) StringReader(java.io.StringReader) Gson(com.google.gson.Gson) JsonReader(javax.json.JsonReader) JsonObject(javax.json.JsonObject) DatasetVersion(edu.harvard.iq.dataverse.DatasetVersion) JsonParseException(edu.harvard.iq.dataverse.util.json.JsonParseException) JsonParser(edu.harvard.iq.dataverse.util.json.JsonParser)

Example 9 with JsonParser

use of edu.harvard.iq.dataverse.util.json.JsonParser in project dataverse by IQSS.

the class ImportGenericServiceBean method importXML.

public void importXML(File xmlFile, String foreignFormat, DatasetVersion datasetVersion) {
    FileInputStream in = null;
    XMLStreamReader xmlr = null;
    // look up the foreign metadata mapping for this format:
    ForeignMetadataFormatMapping mappingSupported = findFormatMappingByName(foreignFormat);
    if (mappingSupported == null) {
        throw new EJBException("Unknown/unsupported foreign metadata format " + foreignFormat);
    }
    try {
        in = new FileInputStream(xmlFile);
        XMLInputFactory xmlFactory = javax.xml.stream.XMLInputFactory.newInstance();
        xmlr = xmlFactory.createXMLStreamReader(in);
        DatasetDTO datasetDTO = processXML(xmlr, mappingSupported);
        Gson gson = new Gson();
        String json = gson.toJson(datasetDTO.getDatasetVersion());
        logger.info("Json:\n" + json);
        JsonReader jsonReader = Json.createReader(new StringReader(json));
        JsonObject obj = jsonReader.readObject();
        DatasetVersion dv = new JsonParser(datasetFieldSvc, blockService, settingsService).parseDatasetVersion(obj, datasetVersion);
    } catch (FileNotFoundException ex) {
        // Logger.getLogger("global").log(Level.SEVERE, null, ex);
        throw new EJBException("ERROR occurred in mapDDI: File Not Found!");
    } catch (XMLStreamException ex) {
        // Logger.getLogger("global").log(Level.SEVERE, null, ex);
        throw new EJBException("ERROR occurred while parsing XML (file " + xmlFile.getAbsolutePath() + "); ", ex);
    } catch (JsonParseException ex) {
        Logger.getLogger(ImportGenericServiceBean.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (xmlr != null) {
                xmlr.close();
            }
        } catch (XMLStreamException ex) {
        }
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
        }
    }
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) ForeignMetadataFormatMapping(edu.harvard.iq.dataverse.ForeignMetadataFormatMapping) FileNotFoundException(java.io.FileNotFoundException) Gson(com.google.gson.Gson) JsonObject(javax.json.JsonObject) DatasetVersion(edu.harvard.iq.dataverse.DatasetVersion) IOException(java.io.IOException) JsonParseException(edu.harvard.iq.dataverse.util.json.JsonParseException) FileInputStream(java.io.FileInputStream) XMLStreamException(javax.xml.stream.XMLStreamException) StringReader(java.io.StringReader) JsonReader(javax.json.JsonReader) EJBException(javax.ejb.EJBException) XMLInputFactory(javax.xml.stream.XMLInputFactory) JsonParser(edu.harvard.iq.dataverse.util.json.JsonParser)

Example 10 with JsonParser

use of edu.harvard.iq.dataverse.util.json.JsonParser in project dataverse by IQSS.

the class ImportGenericServiceBean method importXML.

public void importXML(String xmlToParse, String foreignFormat, DatasetVersion datasetVersion) {
    StringReader reader = null;
    XMLStreamReader xmlr = null;
    ForeignMetadataFormatMapping mappingSupported = findFormatMappingByName(foreignFormat);
    if (mappingSupported == null) {
        throw new EJBException("Unknown/unsupported foreign metadata format " + foreignFormat);
    }
    try {
        reader = new StringReader(xmlToParse);
        XMLInputFactory xmlFactory = javax.xml.stream.XMLInputFactory.newInstance();
        xmlr = xmlFactory.createXMLStreamReader(reader);
        DatasetDTO datasetDTO = processXML(xmlr, mappingSupported);
        Gson gson = new Gson();
        String json = gson.toJson(datasetDTO.getDatasetVersion());
        logger.fine(json);
        JsonReader jsonReader = Json.createReader(new StringReader(json));
        JsonObject obj = jsonReader.readObject();
        DatasetVersion dv = new JsonParser(datasetFieldSvc, blockService, settingsService).parseDatasetVersion(obj, datasetVersion);
    } catch (XMLStreamException ex) {
        // Logger.getLogger("global").log(Level.SEVERE, null, ex);
        throw new EJBException("ERROR occurred while parsing XML fragment  (" + xmlToParse.substring(0, 64) + "...); ", ex);
    } catch (JsonParseException ex) {
        Logger.getLogger(ImportGenericServiceBean.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (xmlr != null) {
                xmlr.close();
            }
        } catch (XMLStreamException ex) {
        }
    }
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) ForeignMetadataFormatMapping(edu.harvard.iq.dataverse.ForeignMetadataFormatMapping) Gson(com.google.gson.Gson) JsonObject(javax.json.JsonObject) DatasetVersion(edu.harvard.iq.dataverse.DatasetVersion) JsonParseException(edu.harvard.iq.dataverse.util.json.JsonParseException) XMLStreamException(javax.xml.stream.XMLStreamException) StringReader(java.io.StringReader) JsonReader(javax.json.JsonReader) EJBException(javax.ejb.EJBException) XMLInputFactory(javax.xml.stream.XMLInputFactory) JsonParser(edu.harvard.iq.dataverse.util.json.JsonParser)

Aggregations

JsonParser (edu.harvard.iq.dataverse.util.json.JsonParser)12 StringReader (java.io.StringReader)9 JsonObject (javax.json.JsonObject)9 JsonReader (javax.json.JsonReader)9 DatasetVersion (edu.harvard.iq.dataverse.DatasetVersion)8 JsonParseException (edu.harvard.iq.dataverse.util.json.JsonParseException)6 Gson (com.google.gson.Gson)5 File (java.io.File)5 XMLStreamException (javax.xml.stream.XMLStreamException)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 Test (org.junit.Test)4 Dataset (edu.harvard.iq.dataverse.Dataset)3 GsonBuilder (com.google.gson.GsonBuilder)2 DatasetField (edu.harvard.iq.dataverse.DatasetField)2 DatasetFieldValue (edu.harvard.iq.dataverse.DatasetFieldValue)2 Dataverse (edu.harvard.iq.dataverse.Dataverse)2 ForeignMetadataFormatMapping (edu.harvard.iq.dataverse.ForeignMetadataFormatMapping)2 DatasetDTO (edu.harvard.iq.dataverse.api.dto.DatasetDTO)2 IpGroup (edu.harvard.iq.dataverse.authorization.groups.impl.ipaddress.IpGroup)2 CommandException (edu.harvard.iq.dataverse.engine.command.exception.CommandException)2