use of org.mycore.common.MCRException in project mycore by MyCoRe-Org.
the class MCRBasketServlet method doGetPost.
public void doGetPost(MCRServletJob job) throws Exception {
HttpServletRequest req = job.getRequest();
HttpServletResponse res = job.getResponse();
String type = req.getParameter("type");
String action = req.getParameter("action");
String[] uris = req.getParameterValues("uri");
String[] ids = req.getParameterValues("id");
String redirect = getProperty(req, "redirect");
URL referer = getReferer(req);
boolean resolveContent = "true".equals(req.getParameter("resolve"));
LOGGER.info("{} {} {}", action, type, ids == null ? "" : ids);
MCRBasket basket = MCRBasketManager.getOrCreateBasketInSession(type);
if ("add".equals(action)) {
if (uris.length != ids.length) {
throw new MCRException("Amount of URIs must match amount of IDs");
}
for (int i = 0; i < uris.length; i++) {
MCRBasketEntry entry = new MCRBasketEntry(ids[i], uris[i]);
basket.add(entry);
if (resolveContent) {
entry.resolveContent();
}
}
} else if ("remove".equals(action)) {
for (String id : ids) {
basket.removeEntry(id);
}
} else if ("up".equals(action)) {
for (String id : ids) {
basket.up(basket.get(id));
}
} else if ("down".equals(action)) {
for (String id : ids) {
basket.down(basket.get(id));
}
} else if ("clear".equals(action)) {
basket.clear();
} else if ("create".equals(action)) {
String ownerID = req.getParameter("ownerID");
MCRObjectID ownerOID = MCRObjectID.getInstance(ownerID);
MCRBasketPersistence.createDerivateWithBasket(basket, ownerOID);
} else if ("update".equals(action)) {
MCRBasketPersistence.updateBasket(basket);
} else if ("retrieve".equals(action)) {
String derivateID = req.getParameter("derivateID");
basket = MCRBasketPersistence.retrieveBasket(derivateID);
type = basket.getType();
MCRBasketManager.setBasketInSession(basket);
} else if ("comment".equals(action)) {
Document sub = (Document) (job.getRequest().getAttribute("MCRXEditorSubmission"));
String comment = sub.getRootElement().getChildTextTrim("comment");
for (String id : ids) {
basket.get(id).setComment(comment);
}
} else if ("show".equals(action)) {
req.setAttribute("XSL.Style", type);
Document xml = new MCRBasketXMLBuilder(true).buildXML(basket);
getLayoutService().doLayout(req, res, new MCRJDOMContent(xml));
return;
}
if (referer != null && "referer".equals(redirect)) {
res.sendRedirect(res.encodeRedirectURL(referer.toExternalForm()));
} else if (redirect != null) {
res.sendRedirect(res.encodeRedirectURL(redirect));
} else {
res.sendRedirect(res.encodeRedirectURL(getServletBaseURL() + "MCRBasketServlet?action=show&type=" + type));
}
}
use of org.mycore.common.MCRException in project mycore by MyCoRe-Org.
the class MCRAccessCommands method createPermissionsFromFile.
/**
* This method sets the new permissions given in a certain file
*
* @param filename
* the filename of the file that contains the mcrpermissions
*/
public static void createPermissionsFromFile(String filename) throws Exception {
MCRAccessInterface AI = MCRAccessManager.getAccessImpl();
if (!checkFilename(filename)) {
return;
}
LOGGER.info("Reading file {} ...", filename);
org.jdom2.Document doc = MCRXMLParserFactory.getValidatingParser().parseXML(new MCRFileContent(filename));
org.jdom2.Element rootelm = doc.getRootElement();
if (!rootelm.getName().equals("mcrpermissions")) {
throw new MCRException("The data are not for mcrpermissions.");
}
List<Element> listelm = rootelm.getChildren("mcrpermission");
for (Element mcrpermission : listelm) {
String permissionName = mcrpermission.getAttributeValue("name").trim();
String ruleDescription = mcrpermission.getAttributeValue("ruledescription");
if (ruleDescription == null) {
ruleDescription = "";
}
Element rule = mcrpermission.getChild("condition").clone();
String objectid = mcrpermission.getAttributeValue("objectid");
if (objectid == null) {
AI.addRule(permissionName, rule, ruleDescription);
} else {
AI.addRule(objectid, permissionName, rule, ruleDescription);
}
}
}
use of org.mycore.common.MCRException in project mycore by MyCoRe-Org.
the class MCRIFS2Commands method repairUnicodeInContentStores.
@MCRCommand(syntax = "repair unicode in content stores {0}", help = "this fixes consequences of MCR-1423 in content" + " stores . If {0} is false then nothing will be done (dry run).")
public static void repairUnicodeInContentStores(String execute) {
boolean dry = execute.toLowerCase(Locale.ROOT).equals(Boolean.FALSE.toString().toLowerCase(Locale.ROOT));
MCRContentStoreFactory.getAvailableStores().forEach((name, cs) -> {
LOGGER.info("{} store: {} ", dry ? "would fix" : "fixing", name);
try {
Path path = cs.getBaseDir().toPath();
LOGGER.info("Starting with path : {}", path);
java.nio.file.Files.walkFileTree(path, new MCRUnicodeFilenameNormalizer(dry));
} catch (IOException e) {
throw new MCRException("Error while get basedir of content store " + name, e);
}
});
}
use of org.mycore.common.MCRException in project mycore by MyCoRe-Org.
the class MCRIFS2Commands method fixFileEntry.
private static void fixFileEntry(File node, String content_store, String derivate_id, String storage_base, boolean check_only) {
LOGGER.debug("fixFileEntry : name = {}", node.getName());
String storageid = node.getAbsolutePath().substring(storage_base.length()).replace("\\", "/");
LOGGER.debug("fixFileEntry : storageid = {}", storageid);
String id = "";
String md5_old = "";
long size_old = 0;
boolean foundEntry = false;
MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
boolean transactionActive = mcrSession.isTransactionActive();
if (!transactionActive) {
mcrSession.beginTransaction();
}
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
try {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<MCRFSNODES> query = cb.createQuery(MCRFSNODES.class);
Root<MCRFSNODES> nodes = query.from(MCRFSNODES.class);
try {
MCRFSNODES fsNode = em.createQuery(query.where(cb.equal(nodes.get(MCRFSNODES_.owner), derivate_id), cb.equal(nodes.get(MCRFSNODES_.storeid), content_store), cb.equal(nodes.get(MCRFSNODES_.storageid), storageid), cb.equal(nodes.get(MCRFSNODES_.type), "F"))).getSingleResult();
LOGGER.debug("Found file entry for {}", storageid);
foundEntry = true;
id = fsNode.getId();
md5_old = fsNode.getMd5();
size_old = fsNode.getSize();
em.detach(fsNode);
} catch (NoResultException e) {
LOGGER.error("Can't find file entry for {}", storageid);
if (check_only)
return;
} catch (NonUniqueResultException e) {
LOGGER.error("Non unique file entry for {}", storageid);
return;
}
} catch (Exception e) {
e.printStackTrace();
}
// check fctid, size and MD5 of the file
String fctid = "";
String md5 = "";
try (MCRContentInputStream cis = new MCRContentInputStream(new FileInputStream(node))) {
byte[] header = cis.getHeader();
fctid = MCRFileContentTypeFactory.detectType(node.getName(), header).getID();
ByteStreams.copy(cis, ByteStreams.nullOutputStream());
md5 = cis.getMD5String();
} catch (MCRException | IOException e1) {
e1.printStackTrace();
return;
}
long size = node.length();
LOGGER.debug("size old : {} <--> size : {}", Long.toString(size_old), Long.toString(size));
LOGGER.debug("MD5 old : {} <--> MD5 : {}", md5_old, md5);
if (size_old == size && md5_old.equals(md5)) {
return;
}
if (foundEntry && size_old != size) {
LOGGER.warn("Wrong file size for {} : {} <-> {}", storageid, size_old, size);
}
if (foundEntry && !md5.equals(md5_old)) {
LOGGER.warn("Wrong file md5 for {} : {} <-> {}", storageid, md5_old, md5);
}
if (check_only)
return;
// fix entry
LOGGER.info("Fix entry for file {}", storageid);
if (!foundEntry) {
MCRFileMetadataManager fmmgr = MCRFileMetadataManager.instance();
id = fmmgr.createNodeID();
}
String pid = null;
try {
pid = getParentID(node, derivate_id);
} catch (NoResultException e1) {
LOGGER.error("Can't find parent id of directory for file {}", storageid);
} catch (NonUniqueResultException e1) {
LOGGER.error("The directory entry for {} and {} is not unique!", derivate_id, node.getParentFile().getName());
return;
}
try {
MCRFSNODES mcrfsnodes = new MCRFSNODES();
mcrfsnodes.setId(id);
mcrfsnodes.setPid(pid);
mcrfsnodes.setType("F");
mcrfsnodes.setOwner(derivate_id);
mcrfsnodes.setName(node.getName());
mcrfsnodes.setSize(size);
mcrfsnodes.setDate(new Date(node.lastModified()));
mcrfsnodes.setStoreid(content_store);
mcrfsnodes.setStorageid(storageid);
mcrfsnodes.setFctid(fctid);
mcrfsnodes.setMd5(md5);
em.merge(mcrfsnodes);
mcrSession.commitTransaction();
LOGGER.debug("Entry {} fixed.", node.getName());
} catch (PersistenceException pe) {
mcrSession.rollbackTransaction();
pe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
use of org.mycore.common.MCRException in project mycore by MyCoRe-Org.
the class MCRIFSCommands method fixDirectorySize.
private static long fixDirectorySize(MCRDirectory directory) {
long directorySize = 0;
for (MCRFilesystemNode child : directory.getChildren()) {
if (child instanceof MCRDirectory) {
directorySize += fixDirectorySize((MCRDirectory) child);
} else if (child instanceof MCRFile) {
MCRFile file = (MCRFile) child;
directorySize += file.getSize();
}
}
/*
There is no setSize method on MCRFileSystemNode and there should not be one.
But in this repair command we need to set the size, so we use reflection.
*/
try {
Field privateLongField = MCRFilesystemNode.class.getDeclaredField(MCRFILESYSTEMNODE_SIZE_FIELD_NAME);
privateLongField.setAccessible(true);
privateLongField.set(directory, directorySize);
} catch (NoSuchFieldException e) {
String message = MessageFormat.format("There is no field named {0} in MCRFileSystemNode!", MCRFILESYSTEMNODE_SIZE_FIELD_NAME);
throw new MCRException(message, e);
} catch (IllegalAccessException e) {
String message = MessageFormat.format("Could not acces filed {0} in {1}!", MCRFILESYSTEMNODE_SIZE_FIELD_NAME, directory.toString());
throw new MCRException(message, e);
}
// now call touch with the old date of MCRFSN to apply the changes to the DB
GregorianCalendar lastModified = directory.getLastModified();
FileTime LastModifiedFileTime = FileTime.fromMillis(lastModified.getTimeInMillis());
try {
Method touchMethod = MCRFilesystemNode.class.getDeclaredMethod(MCRFILESYSTEMNODE_TOUCH_METHOD_NAME, FileTime.class, boolean.class);
touchMethod.setAccessible(true);
touchMethod.invoke(directory, LastModifiedFileTime, false);
} catch (NoSuchMethodException e) {
throw new MCRException(MessageFormat.format("There is no {0}-method..", MCRFILESYSTEMNODE_TOUCH_METHOD_NAME));
} catch (InvocationTargetException | IllegalAccessException e) {
throw new MCRException(MessageFormat.format("Error while calling {0}-method..", MCRFILESYSTEMNODE_TOUCH_METHOD_NAME));
}
LOGGER.info(MessageFormat.format("Changed size of directory {0} to {1} Bytes", directory.getName(), directorySize));
return directorySize;
}
Aggregations