use of org.mycore.access.MCRAccessException in project mycore by MyCoRe-Org.
the class MCRMetadataManager method delete.
/**
* Deletes MCRDerivate.
*
* @param mcrDerivate
* to be deleted
* @throws MCRPersistenceException
* if persistence problem occurs
* @throws MCRAccessException
* if delete permission is missing
*/
public static void delete(final MCRDerivate mcrDerivate) throws MCRPersistenceException, MCRAccessException {
MCRObjectID id = mcrDerivate.getId();
if (!MCRAccessManager.checkPermission(id, PERMISSION_DELETE)) {
throw MCRAccessException.missingPermission("Delete derivate", id.toString(), PERMISSION_DELETE);
}
// mark for deletion
MCRMarkManager.instance().mark(id, Operation.DELETE);
// remove link
MCRObjectID metaId = null;
try {
metaId = mcrDerivate.getDerivate().getMetaLink().getXLinkHrefID();
if (MCRMetadataManager.removeDerivateFromObject(metaId, id)) {
LOGGER.info(MessageFormat.format("Link in MCRObject {0} to MCRDerivate {1} is deleted.", metaId, id));
} else {
LOGGER.warn(MessageFormat.format("Link in MCRObject {0} to MCRDerivate {1} could not be deleted.", metaId, id));
}
} catch (final Exception e) {
LOGGER.warn("Can't delete link for MCRDerivate {} from MCRObject {}. Error ignored.", id, metaId);
}
// delete data from IFS
if (mcrDerivate.getDerivate().getInternals() != null) {
try {
deleteDerivate(id.toString());
LOGGER.info("IFS entries for MCRDerivate {} are deleted.", id);
} catch (final Exception e) {
throw new MCRPersistenceException("Error while delete MCRDerivate " + id + " in IFS", e);
}
}
// handle events
fireEvent(mcrDerivate, null, MCREvent.DELETE_EVENT);
// remove mark
MCRMarkManager.instance().remove(id);
}
use of org.mycore.access.MCRAccessException in project mycore by MyCoRe-Org.
the class MCRMetadataManager method create.
/**
* Stores the derivate.
*
* @param mcrDerivate
* derivate instance to store
* @throws MCRPersistenceException
* if a persistence problem is occurred
* @throws MCRAccessException
* if write permission to object is missing
*/
public static void create(final MCRDerivate mcrDerivate) throws MCRPersistenceException, MCRAccessException {
if (exists(mcrDerivate.getId())) {
throw new MCRPersistenceException("The derivate " + mcrDerivate.getId() + " already exists, nothing done.");
}
try {
mcrDerivate.validate();
} catch (MCRException exc) {
throw new MCRPersistenceException("The derivate " + mcrDerivate.getId() + " is not valid.", exc);
}
final MCRObjectID objid = mcrDerivate.getDerivate().getMetaLink().getXLinkHrefID();
if (!MCRAccessManager.checkPermission(objid, PERMISSION_WRITE)) {
throw MCRAccessException.missingPermission("Add derivate " + mcrDerivate.getId() + " to object.", objid.toString(), PERMISSION_WRITE);
}
byte[] objectBackup;
try {
objectBackup = MCRXMLMetadataManager.instance().retrieveBLOB(objid);
} catch (IOException ioExc) {
throw new MCRPersistenceException("Unable to retrieve xml blob of " + objid);
}
if (objectBackup == null) {
throw new MCRPersistenceException("Cannot find " + objid + " to attach derivate " + mcrDerivate.getId() + " to it.");
}
// prepare the derivate metadata and store under the XML table
if (mcrDerivate.getService().getDate("createdate") == null || !mcrDerivate.isImportMode()) {
mcrDerivate.getService().setDate("createdate");
}
if (mcrDerivate.getService().getDate("modifydate") == null || !mcrDerivate.isImportMode()) {
mcrDerivate.getService().setDate("modifydate");
}
// handle events
fireEvent(mcrDerivate, null, MCREvent.CREATE_EVENT);
// add the link to metadata
final MCRMetaLinkID der = new MCRMetaLinkID();
der.setReference(mcrDerivate.getId().toString(), null, mcrDerivate.getLabel());
der.setSubTag("derobject");
try {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("adding Derivate in data store");
}
MCRMetadataManager.addOrUpdateDerivateToObject(objid, der);
} catch (final Exception e) {
MCRMetadataManager.restore(mcrDerivate, objid, objectBackup);
// throw final exception
throw new MCRPersistenceException("Error while creatlink to MCRObject " + objid + ".", e);
}
// create data in IFS
if (mcrDerivate.getDerivate().getInternals() != null) {
MCRObjectID derId = mcrDerivate.getId();
MCRPath rootPath = MCRPath.getPath(derId.toString(), "/");
if (mcrDerivate.getDerivate().getInternals().getSourcePath() == null) {
try {
rootPath.getFileSystem().createRoot(rootPath.getOwner());
BasicFileAttributes attrs = Files.readAttributes(rootPath, BasicFileAttributes.class);
if (!(attrs.fileKey() instanceof String)) {
throw new MCRPersistenceException("Cannot get ID from newely created directory, as it is not a String." + rootPath);
}
mcrDerivate.getDerivate().getInternals().setIFSID(attrs.fileKey().toString());
} catch (IOException ioExc) {
throw new MCRPersistenceException("Cannot create root of '" + rootPath.getOwner() + "' or read the file attributes.", ioExc);
}
} else {
final String sourcepath = mcrDerivate.getDerivate().getInternals().getSourcePath();
final File f = new File(sourcepath);
if (f.exists()) {
try {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Starting File-Import");
}
importDerivate(derId.toString(), f.toPath());
BasicFileAttributes attrs = Files.readAttributes(rootPath, BasicFileAttributes.class);
if (!(attrs.fileKey() instanceof String)) {
throw new MCRPersistenceException("Cannot get ID from newely created directory, as it is not a String." + rootPath);
}
mcrDerivate.getDerivate().getInternals().setIFSID(attrs.fileKey().toString());
} catch (final Exception e) {
if (Files.exists(rootPath)) {
deleteDerivate(derId.toString());
}
MCRMetadataManager.restore(mcrDerivate, objid, objectBackup);
throw new MCRPersistenceException("Can't add derivate to the IFS", e);
}
} else {
LOGGER.warn("Empty derivate, the File or Directory -->{}<-- was not found.", sourcepath);
}
}
}
}
use of org.mycore.access.MCRAccessException in project mycore by MyCoRe-Org.
the class MCRFileMetaEventHandler method handlePathDeleted.
@Override
protected void handlePathDeleted(MCREvent evt, Path path, BasicFileAttributes attrs) {
if (attrs.isDirectory()) {
return;
}
MCRPath mcrPath = MCRPath.toMCRPath(path);
MCRObjectID derivateID = MCRObjectID.getInstance(mcrPath.getOwner());
if (!MCRMetadataManager.exists(derivateID)) {
LOGGER.warn("Derivate {} from file '{}' does not exist.", derivateID, path);
return;
}
MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(derivateID);
MCRObjectDerivate objectDerivate = derivate.getDerivate();
if (objectDerivate.deleteFileMetaData('/' + path.subpath(0, path.getNameCount()).toString())) {
try {
MCRMetadataManager.update(derivate);
} catch (MCRPersistenceException | MCRAccessException e) {
throw new MCRPersistenceException("Could not update derivate: " + derivateID, e);
}
}
}
use of org.mycore.access.MCRAccessException in project mycore by MyCoRe-Org.
the class MCRExtractRelatedItemsEventHandler method extractRelatedItems.
private void extractRelatedItems(final MCREvent evt, final MCRObject object) {
if (!MCRMODSWrapper.isSupported(object)) {
return;
}
Element mods = new MCRMODSWrapper(object).getMODS();
MCRObjectID oid = object.getId();
for (Element relatedItem : mods.getChildren("relatedItem", MCRConstants.MODS_NAMESPACE)) {
String href = relatedItem.getAttributeValue("href", MCRConstants.XLINK_NAMESPACE);
LOGGER.info("Found related item in {}, href={}", object.getId(), href);
// MCR-957: only create releated object if mycoreId
MCRObjectID mcrIdCheck;
try {
mcrIdCheck = MCRObjectID.getInstance(href);
} catch (Exception e) {
// not a valid MCRObjectID -> don't create anyway
continue;
}
// create if integer value == 0
if (mcrIdCheck.getNumberAsInteger() == 0) {
// MCR-931: check for type='host' and present parent document
if (!isHost(relatedItem) || object.getStructure().getParentID() == null) {
MCRObjectID relatedID;
try {
relatedID = createRelatedObject(relatedItem, oid);
} catch (MCRAccessException e) {
throw new MCRException(e);
}
href = relatedID.toString();
LOGGER.info("Setting href of related item to {}", href);
relatedItem.setAttribute("href", href, MCRConstants.XLINK_NAMESPACE);
if (isHost(relatedItem)) {
LOGGER.info("Setting {} as parent of {}", href, oid);
object.getStructure().setParent(relatedID);
}
}
} else if (isParentExists(relatedItem)) {
MCRObjectID relatedID = MCRObjectID.getInstance(href);
if (object.getStructure().getParentID() == null) {
LOGGER.info("Setting {} as parent of {}", href, oid);
object.getStructure().setParent(relatedID);
} else if (!object.getStructure().getParentID().equals(relatedID)) {
LOGGER.info("Setting {} as parent of {}", href, oid);
object.getStructure().setParent(relatedID);
}
}
}
}
use of org.mycore.access.MCRAccessException in project mycore by MyCoRe-Org.
the class MCRRestAPIUploadHelper method uploadFile.
/**
* uploads a file into a given derivate
* @param info - the Jersey UriInfo object
* @param request - the HTTPServletRequest object
* @param pathParamMcrObjID - a MyCoRe Object ID
* @param pathParamMcrDerID - a MyCoRe Derivate ID
* @param uploadedInputStream - the inputstream from HTTP Post request
* @param fileDetails - the file information from HTTP Post request
* @param formParamPath - the path of the file inside the derivate
* @param formParamMaindoc - true, if this file should be marked as maindoc
* @param formParamUnzip - true, if the upload is zip file that should be unzipped inside the derivate
* @param formParamMD5 - the MD5 sum of the uploaded file
* @param formParamSize - the size of the uploaded file
* @return a Jersey Response object
* @throws MCRRestAPIException
*/
public static Response uploadFile(UriInfo info, HttpServletRequest request, String pathParamMcrObjID, String pathParamMcrDerID, InputStream uploadedInputStream, FormDataContentDisposition fileDetails, String formParamPath, boolean formParamMaindoc, boolean formParamUnzip, String formParamMD5, Long formParamSize) throws MCRRestAPIException {
SignedJWT signedJWT = MCRJSONWebTokenUtil.retrieveAuthenticationToken(request);
SortedMap<String, String> parameter = new TreeMap<>();
parameter.put("mcrObjectID", pathParamMcrObjID);
parameter.put("mcrDerivateID", pathParamMcrDerID);
parameter.put("path", formParamPath);
parameter.put("maindoc", Boolean.toString(formParamMaindoc));
parameter.put("unzip", Boolean.toString(formParamUnzip));
parameter.put("md5", formParamMD5);
parameter.put("size", Long.toString(formParamSize));
String base64Signature = request.getHeader("X-MyCoRe-RestAPI-Signature");
if (base64Signature == null) {
throw new MCRRestAPIException(Status.UNAUTHORIZED, new MCRRestAPIError(MCRRestAPIError.CODE_INVALID_AUTHENCATION, "The submitted data could not be validated.", "Please provide a signature as HTTP header 'X-MyCoRe-RestAPI-Signature'."));
}
if (verifyPropertiesWithSignature(parameter, base64Signature, MCRJSONWebTokenUtil.retrievePublicKeyFromAuthenticationToken(signedJWT))) {
try (MCRJPATransactionWrapper mtw = new MCRJPATransactionWrapper()) {
// MCRSession session = MCRServlet.getSession(request);
MCRSession session = MCRSessionMgr.getCurrentSession();
MCRUserInformation currentUser = session.getUserInformation();
MCRUserInformation apiUser = MCRUserManager.getUser(MCRJSONWebTokenUtil.retrieveUsernameFromAuthenticationToken(signedJWT));
session.setUserInformation(apiUser);
MCRObjectID objID = MCRObjectID.getInstance(pathParamMcrObjID);
MCRObjectID derID = MCRObjectID.getInstance(pathParamMcrDerID);
MCRAccessManager.invalidPermissionCache(derID.toString(), PERMISSION_WRITE);
if (MCRAccessManager.checkPermission(derID.toString(), PERMISSION_WRITE)) {
MCRDerivate der = MCRMetadataManager.retrieveMCRDerivate(derID);
java.nio.file.Path derDir = null;
String path = null;
if (der.getOwnerID().equals(objID)) {
try {
derDir = UPLOAD_DIR.resolve(derID.toString());
if (Files.exists(derDir)) {
Files.walkFileTree(derDir, MCRRecursiveDeleter.instance());
}
path = formParamPath.replace("\\", "/").replace("../", "");
while (path.startsWith("/")) {
path = path.substring(1);
}
MCRDirectory difs = MCRDirectory.getRootDirectory(derID.toString());
if (difs == null) {
difs = new MCRDirectory(derID.toString());
}
der.getDerivate().getInternals().setIFSID(difs.getID());
der.getDerivate().getInternals().setSourcePath(derDir.toString());
if (formParamUnzip) {
String maindoc = null;
try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(uploadedInputStream))) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
LOGGER.debug("Unzipping: {}", entry.getName());
java.nio.file.Path target = derDir.resolve(entry.getName());
Files.createDirectories(target.getParent());
Files.copy(zis, target, StandardCopyOption.REPLACE_EXISTING);
if (maindoc == null && !entry.isDirectory()) {
maindoc = entry.getName();
}
}
} catch (IOException e) {
LOGGER.error(e);
}
MCRFileImportExport.importFiles(derDir.toFile(), difs);
if (formParamMaindoc) {
der.getDerivate().getInternals().setMainDoc(maindoc);
}
} else {
java.nio.file.Path saveFile = derDir.resolve(path);
Files.createDirectories(saveFile.getParent());
Files.copy(uploadedInputStream, saveFile, StandardCopyOption.REPLACE_EXISTING);
// delete old file
MCRFileImportExport.importFiles(derDir.toFile(), difs);
if (formParamMaindoc) {
der.getDerivate().getInternals().setMainDoc(path);
}
}
MCRMetadataManager.update(der);
Files.walkFileTree(derDir, MCRRecursiveDeleter.instance());
} catch (IOException | MCRPersistenceException | MCRAccessException e) {
LOGGER.error(e);
throw new MCRRestAPIException(Status.INTERNAL_SERVER_ERROR, new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, "Internal error", e.getMessage()));
}
}
session.setUserInformation(currentUser);
return Response.created(info.getBaseUriBuilder().path("v1/objects/" + objID + "/derivates/" + derID + "/contents").build()).type("application/xml; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, MCRJSONWebTokenUtil.createJWTAuthorizationHeader(signedJWT)).build();
}
}
}
throw new MCRRestAPIException(Status.FORBIDDEN, new MCRRestAPIError(MCRRestAPIError.CODE_INVALID_DATA, "File upload failed.", "The submitted data could not be validated."));
}
Aggregations