use of org.mycore.restapi.v1.errors.MCRRestAPIError in project mycore by MyCoRe-Org.
the class MCRRestAPIUploadHelper method deleteAllFiles.
/**
* deletes all files inside a given derivate
* @param info - the Jersey UriInfo object
* @param request - the HTTPServletRequest object
* @param pathParamMcrObjID - the MyCoRe Object ID
* @param pathParamMcrDerID - the MyCoRe Derivate ID
* @return a Jersey Response Object
* @throws MCRRestAPIException
*/
public static Response deleteAllFiles(UriInfo info, HttpServletRequest request, String pathParamMcrObjID, String pathParamMcrDerID) throws MCRRestAPIException {
Response response = Response.status(Status.INTERNAL_SERVER_ERROR).build();
SignedJWT signedJWT = MCRJSONWebTokenUtil.retrieveAuthenticationToken(request);
SortedMap<String, String> parameter = new TreeMap<>();
parameter.put("mcrObjectID", pathParamMcrObjID);
parameter.put("mcrDerivateID", pathParamMcrDerID);
String base64Signature = request.getHeader("X-MyCoRe-RestAPI-Signature");
if (base64Signature == null) {
// ToDo error handling
}
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.checkPermission uses CACHE, which seems to be dirty from other calls
MCRAccessManager.invalidPermissionCache(derID.toString(), PERMISSION_WRITE);
if (MCRAccessManager.checkPermission(derID.toString(), PERMISSION_WRITE)) {
MCRDerivate der = MCRMetadataManager.retrieveMCRDerivate(derID);
final MCRPath rootPath = MCRPath.getPath(der.getId().toString(), "/");
try {
Files.walkFileTree(rootPath, MCRRecursiveDeleter.instance());
Files.createDirectory(rootPath);
} catch (IOException e) {
LOGGER.error(e);
}
}
session.setUserInformation(currentUser);
response = 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();
}
} else {
throw new MCRRestAPIException(Status.FORBIDDEN, new MCRRestAPIError(MCRRestAPIError.CODE_INVALID_DATA, "Delete failed.", "The submitted data could not be validated."));
}
return response;
}
use of org.mycore.restapi.v1.errors.MCRRestAPIError 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."));
}
use of org.mycore.restapi.v1.errors.MCRRestAPIError in project mycore by MyCoRe-Org.
the class MCRRestAPIUtil method checkRestAPIAccess.
/**
* checks if the given REST API operation is allowed
* @param request - the HTTP request
* @param permission "read" or "write"
* @param path - the REST API path, e.g. /v1/messages
*
* @throws MCRRestAPIException if access is restricted
*/
public static void checkRestAPIAccess(HttpServletRequest request, MCRRestAPIACLPermission permission, String path) throws MCRRestAPIException {
// save the current user and set REST API user into session,
// because ACL System can only validate the current user in session.
MCRUserInformation oldUser = MCRSessionMgr.getCurrentSession().getUserInformation();
try {
String userID = MCRJSONWebTokenUtil.retrieveUsernameFromAuthenticationToken(request);
if (userID != null) {
if (MCRSystemUserInformation.getGuestInstance().getUserID().equals(userID)) {
MCRSessionMgr.getCurrentSession().setUserInformation(MCRSystemUserInformation.getGuestInstance());
} else {
MCRSessionMgr.getCurrentSession().setUserInformation(MCRUserManager.getUser(userID));
}
}
MCRIPAddress theIP = new MCRIPAddress(MCRFrontendUtil.getRemoteAddr(request));
String thePath = path.startsWith("/") ? path : "/" + path;
boolean hasAPIAccess = ((MCRAccessControlSystem) MCRAccessControlSystem.instance()).checkAccess("restapi:/", permission.toString(), userID, theIP);
if (hasAPIAccess) {
MCRAccessRule rule = (MCRAccessRule) MCRAccessControlSystem.instance().getAccessRule("restapi:" + thePath, permission.toString());
if (rule != null) {
if (rule.checkAccess(userID, new Date(), theIP)) {
return;
}
} else {
return;
}
}
} catch (UnknownHostException e) {
// ignore
} finally {
MCRSessionMgr.getCurrentSession().setUserInformation(oldUser);
}
throw new MCRRestAPIException(Status.FORBIDDEN, new MCRRestAPIError(MCRRestAPIError.CODE_ACCESS_DENIED, "REST-API action is not allowed.", "Check access right '" + permission + "' on ACLs 'restapi:/' and 'restapi:" + path + "'!"));
}
use of org.mycore.restapi.v1.errors.MCRRestAPIError in project mycore by MyCoRe-Org.
the class MCRRestAPIClassifications method showObject.
/**
* returns a single classification object
*
* @param classID - the classfication id
* @param format
* Possible values are: json | xml (required)
* @param filter
* a ';'-separated list of ':'-separated key-value pairs, possible keys are:
* - lang - the language of the returned labels, if ommited all labels in all languages will be returned
* - root - an id for a category which will be used as root
* - nonempty - hide empty categories
* @param style
* a ';'-separated list of values, possible keys are:
* - 'checkboxtree' - create a json syntax which can be used as input for a dojo checkboxtree;
* - 'checked' - (together with 'checkboxtree') all checkboxed will be checked
* - 'jstree' - create a json syntax which can be used as input for a jsTree
* - 'opened' - (together with 'jstree') - all nodes will be opened
* - 'disabled' - (together with 'jstree') - all nodes will be disabled
* - 'selected' - (together with 'jstree') - all nodes will be selected
* @param request - the HTTPServletRequestObject
* @param callback - used in JSONP to wrap json result into a Javascript function named by callback parameter
* @return a Jersey Response object
* @throws MCRRestAPIException
*/
@GET
// @Path("/id/{value}{format:(\\.[^/]+?)?}") -> working, but returns empty string instead of default value
@Path("/{classID}")
@Produces({ MediaType.TEXT_XML + ";charset=UTF-8", MediaType.APPLICATION_JSON + ";charset=UTF-8" })
public Response showObject(@Context HttpServletRequest request, @PathParam("classID") String classID, @QueryParam("format") @DefaultValue("xml") String format, @QueryParam("filter") @DefaultValue("") String filter, @QueryParam("style") @DefaultValue("") String style, @QueryParam("callback") @DefaultValue("") String callback) throws MCRRestAPIException {
MCRRestAPIUtil.checkRestAPIAccess(request, MCRRestAPIACLPermission.READ, "/v1/classifications");
String rootCateg = null;
String lang = null;
boolean filterNonEmpty = false;
boolean filterNoChildren = false;
for (String f : filter.split(";")) {
if (f.startsWith("root:")) {
rootCateg = f.substring(5);
}
if (f.startsWith("lang:")) {
lang = f.substring(5);
}
if (f.startsWith("nonempty")) {
filterNonEmpty = true;
}
if (f.startsWith("nochildren")) {
filterNoChildren = true;
}
}
if (format == null || classID == null) {
return Response.serverError().status(Status.BAD_REQUEST).build();
// TODO response.sendError(HttpServletResponse.SC_NOT_FOUND,
// "Please specify parameters format and classid.");
}
try {
MCRCategory cl = DAO.getCategory(MCRCategoryID.rootID(classID), -1);
if (cl == null) {
throw new MCRRestAPIException(Response.Status.BAD_REQUEST, new MCRRestAPIError(MCRRestAPIError.CODE_NOT_FOUND, "Classification not found.", "There is no classification with the given ID."));
}
Document docClass = MCRCategoryTransformer.getMetaDataDocument(cl, false);
Element eRoot = docClass.getRootElement();
if (rootCateg != null) {
XPathExpression<Element> xpe = XPathFactory.instance().compile("//category[@ID='" + rootCateg + "']", Filters.element());
Element e = xpe.evaluateFirst(docClass);
if (e != null) {
eRoot = e;
} else {
throw new MCRRestAPIException(Response.Status.BAD_REQUEST, new MCRRestAPIError(MCRRestAPIError.CODE_NOT_FOUND, "Category not found.", "The classfication does not contain a category with the given ID."));
}
}
if (filterNonEmpty) {
Element eFilter = eRoot;
if (eFilter.getName().equals("mycoreclass")) {
eFilter = eFilter.getChild("categories");
}
filterNonEmpty(docClass.getRootElement().getAttributeValue("ID"), eFilter);
}
if (filterNoChildren) {
eRoot.removeChildren("category");
}
String authHeader = MCRJSONWebTokenUtil.createJWTAuthorizationHeader(MCRJSONWebTokenUtil.retrieveAuthenticationToken(request));
if (FORMAT_JSON.equals(format)) {
String json = writeJSON(eRoot, lang, style);
// eventually: allow Cross Site Requests: .header("Access-Control-Allow-Origin", "*")
if (callback.length() > 0) {
return Response.ok(callback + "(" + json + ")").type("application/javascript; charset=UTF-8").build();
} else {
return Response.ok(json).type("application/json; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, authHeader).build();
}
}
if (FORMAT_XML.equals(format)) {
String xml = writeXML(eRoot, lang);
return Response.ok(xml).type("application/xml; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, authHeader).build();
}
} catch (Exception e) {
LogManager.getLogger(this.getClass()).error("Error outputting classification", e);
// TODO response.sendError(HttpServletResponse.SC_NOT_FOUND, "Error outputting classification");
}
return null;
}
use of org.mycore.restapi.v1.errors.MCRRestAPIError in project mycore by MyCoRe-Org.
the class MCRRestAPIObjectsHelper method retrieveMCRObject.
private static MCRObject retrieveMCRObject(String idString) throws MCRRestAPIException {
// the default value for the key
String key = "mcr";
if (idString.contains(":")) {
int pos = idString.indexOf(":");
key = idString.substring(0, pos);
idString = idString.substring(pos + 1);
if (!key.equals("mcr")) {
try {
idString = URLDecoder.decode(idString, "UTF-8");
} catch (UnsupportedEncodingException e) {
// will not happen
}
// ToDo - Shall we restrict the key set with a property?
// throw new MCRRestAPIException(MCRRestAPIError.create(Response.Status.BAD_REQUEST,
// "The ID is not valid.", "The prefix is unkown. Only 'mcr' is allowed."));
}
}
if (key.equals("mcr")) {
MCRObjectID mcrID = null;
try {
mcrID = MCRObjectID.getInstance(idString);
} catch (Exception e) {
throw new MCRRestAPIException(Response.Status.BAD_REQUEST, new MCRRestAPIError(MCRRestAPIError.CODE_WRONG_ID, "The MyCoRe ID '" + idString + "' is not valid. - Did you use the proper format: '{project}_{type}_{number}'?", e.getMessage()));
}
if (!MCRMetadataManager.exists(mcrID)) {
throw new MCRRestAPIException(Response.Status.NOT_FOUND, new MCRRestAPIError(MCRRestAPIError.CODE_NOT_FOUND, "There is no object with the given MyCoRe ID '" + idString + "'.", null));
}
return MCRMetadataManager.retrieveMCRObject(mcrID);
} else {
SolrClient solrClient = MCRSolrClientFactory.getSolrClient();
SolrQuery query = new SolrQuery();
query.setQuery(key + ":" + idString);
try {
QueryResponse response = solrClient.query(query);
SolrDocumentList solrResults = response.getResults();
if (solrResults.getNumFound() == 1) {
String id = solrResults.get(0).getFieldValue("returnId").toString();
return retrieveMCRObject(id);
} else {
if (solrResults.getNumFound() == 0) {
throw new MCRRestAPIException(Response.Status.NOT_FOUND, new MCRRestAPIError(MCRRestAPIError.CODE_NOT_FOUND, "There is no object with the given ID '" + key + ":" + idString + "'.", null));
} else {
throw new MCRRestAPIException(Response.Status.NOT_FOUND, new MCRRestAPIError(MCRRestAPIError.CODE_NOT_FOUND, "The ID is not unique. There are " + solrResults.getNumFound() + " objecst fore the given ID '" + key + ":" + idString + "'.", null));
}
}
} catch (SolrServerException | IOException e) {
LOGGER.error(e);
throw new MCRRestAPIException(Response.Status.BAD_REQUEST, new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, "Internal server error.", e.getMessage()));
}
}
}
Aggregations