Search in sources :

Example 31 with XPathExpression

use of org.jdom2.xpath.XPathExpression in project mycore by MyCoRe-Org.

the class MCRUserServlet method saveUser.

/**
 * Handles MCRUserServlet?action=save&id={userID}.
 * This is called by user-editor.xml editor form to save the
 * changed user data from editor submission. Redirects to
 * show user data afterwards.
 */
private void saveUser(HttpServletRequest req, HttpServletResponse res) throws Exception {
    MCRUser currentUser = MCRUserManager.getCurrentUser();
    if (!checkUserIsNotNull(res, currentUser, null)) {
        return;
    }
    boolean hasAdminPermission = MCRAccessManager.checkPermission(MCRUser2Constants.USER_ADMIN_PERMISSION);
    boolean allowed = hasAdminPermission || MCRAccessManager.checkPermission(MCRUser2Constants.USER_CREATE_PERMISSION);
    if (!allowed) {
        String msg = MCRTranslation.translate("component.user2.UserServlet.noCreatePermission");
        res.sendError(HttpServletResponse.SC_FORBIDDEN, msg);
        return;
    }
    Document doc = (Document) (req.getAttribute("MCRXEditorSubmission"));
    Element u = doc.getRootElement();
    String userName = u.getAttributeValue("name");
    String realmID = MCRRealmFactory.getLocalRealm().getID();
    if (hasAdminPermission) {
        realmID = u.getAttributeValue("realm");
    }
    MCRUser user;
    boolean userExists = MCRUserManager.exists(userName, realmID);
    if (!userExists) {
        user = new MCRUser(userName, realmID);
        LOGGER.info("create new user {} {}", userName, realmID);
        // For new local users, set password
        String pwd = u.getChildText("password");
        if ((pwd != null) && (pwd.trim().length() > 0) && user.getRealm().equals(MCRRealmFactory.getLocalRealm())) {
            MCRUserManager.updatePasswordHashToSHA256(user, pwd);
        }
    } else {
        user = MCRUserManager.getUser(userName, realmID);
        if (!(hasAdminPermission || currentUser.equals(user) || currentUser.equals(user.getOwner()))) {
            res.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
    }
    XPathExpression<Attribute> hintPath = XPathFactory.instance().compile("password/@hint", Filters.attribute());
    Attribute hintAttr = hintPath.evaluateFirst(u);
    String hint = hintAttr == null ? null : hintAttr.getValue();
    if ((hint != null) && (hint.trim().length() == 0)) {
        hint = null;
    }
    user.setHint(hint);
    updateBasicUserInfo(u, user);
    if (hasAdminPermission) {
        boolean locked = "true".equals(u.getAttributeValue("locked"));
        user.setLocked(locked);
        boolean disabled = "true".equals(u.getAttributeValue("disabled"));
        user.setDisabled(disabled);
        Element o = u.getChild("owner");
        if (o != null && !o.getAttributes().isEmpty()) {
            String ownerName = o.getAttributeValue("name");
            String ownerRealm = o.getAttributeValue("realm");
            MCRUser owner = MCRUserManager.getUser(ownerName, ownerRealm);
            if (!checkUserIsNotNull(res, owner, ownerName + "@" + ownerRealm)) {
                return;
            }
            user.setOwner(owner);
        } else {
            user.setOwner(null);
        }
        String validUntilText = u.getChildTextTrim("validUntil");
        if (validUntilText == null || validUntilText.length() == 0) {
            user.setValidUntil(null);
        } else {
            String dateInUTC = validUntilText;
            if (validUntilText.length() == 10) {
                dateInUTC = convertToUTC(validUntilText, "yyyy-MM-dd");
            }
            MCRISO8601Date date = new MCRISO8601Date(dateInUTC);
            user.setValidUntil(date.getDate());
        }
    } else {
        // save read user of creator
        user.setRealm(MCRRealmFactory.getLocalRealm());
        user.setOwner(currentUser);
    }
    Element gs = u.getChild("roles");
    if (gs != null) {
        user.getSystemRoleIDs().clear();
        user.getExternalRoleIDs().clear();
        List<Element> groupList = gs.getChildren("role");
        for (Element group : groupList) {
            String groupName = group.getAttributeValue("name");
            if (hasAdminPermission || currentUser.isUserInRole(groupName)) {
                user.assignRole(groupName);
            } else {
                LOGGER.warn("Current user {} has not the permission to add user to group {}", currentUser.getUserID(), groupName);
            }
        }
    }
    if (userExists) {
        MCRUserManager.updateUser(user);
    } else {
        MCRUserManager.createUser(user);
    }
    res.sendRedirect(res.encodeRedirectURL("MCRUserServlet?action=show&id=" + URLEncoder.encode(user.getUserID(), "UTF-8")));
}
Also used : Attribute(org.jdom2.Attribute) Element(org.jdom2.Element) Document(org.jdom2.Document) MCRISO8601Date(org.mycore.datamodel.common.MCRISO8601Date)

Example 32 with XPathExpression

use of org.jdom2.xpath.XPathExpression in project mycore by MyCoRe-Org.

the class MCRDataciteClient method changeToTestDOI.

private void changeToTestDOI(Document metadata) {
    XPathExpression<Element> compile = XPathFactory.instance().compile("//datacite:identifier[@identifierType='DOI']", Filters.element(), null, Namespace.getNamespace("datacite", "http://datacite.org/schema/kernel-3"));
    Element element = compile.evaluateFirst(metadata);
    MCRDigitalObjectIdentifier doi = new MCRDOIParser().parse(element.getText()).orElseThrow(() -> new MCRException("Datacite Document contains invalid DOI!"));
    String testDOI = doi.toTestPrefix().asString();
    element.setText(testDOI);
}
Also used : MCRException(org.mycore.common.MCRException) Element(org.jdom2.Element)

Example 33 with XPathExpression

use of org.jdom2.xpath.XPathExpression in project mycore by MyCoRe-Org.

the class MCRDOIRegistrationService method insertDOI.

private void insertDOI(Document datacite, MCRDigitalObjectIdentifier doi) throws MCRPersistentIdentifierException {
    XPathExpression<Element> compile = XPathFactory.instance().compile("//datacite:identifier[@identifierType='DOI']", Filters.element(), null, nameSpace);
    List<Element> doiList = compile.evaluate(datacite);
    if (doiList.size() > 1) {
        throw new MCRPersistentIdentifierException("There is more then one identifier with type DOI!");
    } else if (doiList.size() == 1) {
        Element doiElement = doiList.stream().findAny().get();
        LOGGER.warn("Found existing DOI({}) in Document will be replaced with {}", doiElement.getTextTrim(), doi.asString());
        doiElement.setText(doi.asString());
    } else {
        // must be 0
        Element doiElement = new Element("identifier", nameSpace);
        datacite.getRootElement().addContent(doiElement);
        doiElement.setAttribute("identifierType", "DOI");
        doiElement.setText(doi.asString());
    }
}
Also used : Element(org.jdom2.Element) MCRPersistentIdentifierException(org.mycore.pi.exceptions.MCRPersistentIdentifierException)

Example 34 with XPathExpression

use of org.jdom2.xpath.XPathExpression in project mycore by MyCoRe-Org.

the class MCRMODSWrapperTest method testSetMODS.

@Test
public void testSetMODS() throws SAXParseException, IOException, JDOMException {
    Element mods = loadMODSDocument().detachRootElement();
    MCRMODSWrapper wrapper = new MCRMODSWrapper();
    wrapper.setID("JUnit", 4711);
    wrapper.setMODS(mods);
    Document mcrObjXml = wrapper.getMCRObject().createXML();
    XPathExpression<Element> xpathCheck = XPathFactory.instance().compile("//mods:mods", Filters.element(), null, MCRConstants.MODS_NAMESPACE);
    assertEquals("Did not find mods data", 1, xpathCheck.evaluate(mcrObjXml).size());
}
Also used : Element(org.jdom2.Element) Document(org.jdom2.Document) Test(org.junit.Test)

Example 35 with XPathExpression

use of org.jdom2.xpath.XPathExpression in project mycore by MyCoRe-Org.

the class MCRClassificationMappingEventHandlerTest method testMapping.

@Test
public void testMapping() throws SAXParseException, IOException, JDOMException, URISyntaxException {
    MCRSessionMgr.getCurrentSession().isTransactionActive();
    ClassLoader classLoader = getClass().getClassLoader();
    SAXBuilder saxBuilder = new SAXBuilder();
    loadCategory("diniPublType.xml");
    loadCategory("genre.xml");
    Document document = saxBuilder.build(classLoader.getResourceAsStream(TEST_DIRECTORY + "testMods.xml"));
    MCRObject mcro = new MCRObject();
    MCRMODSWrapper mw = new MCRMODSWrapper(mcro);
    mw.setMODS(document.getRootElement().detach());
    mw.setID("junit", 1);
    MCRClassificationMappingEventHandler mapper = new MCRClassificationMappingEventHandler();
    mapper.handleObjectUpdated(null, mcro);
    String expression = "//mods:classification[contains(@generator,'-mycore') and contains(@valueURI, 'StudyThesis')]";
    XPathExpression<Element> expressionObject = XPathFactory.instance().compile(expression, Filters.element(), null, MCRConstants.MODS_NAMESPACE, MCRConstants.XLINK_NAMESPACE);
    Document xml = mcro.createXML();
    Assert.assertNotNull("The mapped classification should be in the MyCoReObject now!", expressionObject.evaluateFirst(xml));
    expression = "//mods:classification[contains(@generator,'-mycore') and contains(@valueURI, 'masterThesis')]";
    expressionObject = XPathFactory.instance().compile(expression, Filters.element(), null, MCRConstants.MODS_NAMESPACE, MCRConstants.XLINK_NAMESPACE);
    Assert.assertNull("The mapped classification of the child should not be contained in the MyCoReObject now!", expressionObject.evaluateFirst(xml));
    LOGGER.info(new XMLOutputter(Format.getPrettyFormat()).outputString(xml));
}
Also used : XMLOutputter(org.jdom2.output.XMLOutputter) SAXBuilder(org.jdom2.input.SAXBuilder) MCRObject(org.mycore.datamodel.metadata.MCRObject) Element(org.jdom2.Element) MCRMODSWrapper(org.mycore.mods.MCRMODSWrapper) Document(org.jdom2.Document) Test(org.junit.Test)

Aggregations

Element (org.jdom2.Element)43 Document (org.jdom2.Document)23 XPathExpression (org.jdom2.xpath.XPathExpression)13 IOException (java.io.IOException)9 XPathFactory (org.jdom2.xpath.XPathFactory)9 SAXBuilder (org.jdom2.input.SAXBuilder)7 Attribute (org.jdom2.Attribute)6 JDOMException (org.jdom2.JDOMException)5 Test (org.junit.Test)5 Text (org.jdom2.Text)4 XMLOutputter (org.jdom2.output.XMLOutputter)4 MCRObject (org.mycore.datamodel.metadata.MCRObject)4 MCRPath (org.mycore.datamodel.niofs.MCRPath)4 URISyntaxException (java.net.URISyntaxException)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 SimpleDateFormat (java.text.SimpleDateFormat)2 HashMap (java.util.HashMap)2 MCRPersistenceException (org.mycore.common.MCRPersistenceException)2 MCRNodeBuilder (org.mycore.common.xml.MCRNodeBuilder)2 MCRCategory (org.mycore.datamodel.classifications2.MCRCategory)2