Search in sources :

Example 1 with MCRSession

use of org.mycore.common.MCRSession in project mycore by MyCoRe-Org.

the class MCRSessionContext method sessionEvent.

public void sessionEvent(MCRSessionEvent event) {
    MCRSession mcrSession = event.getSession();
    EntityManager currentEntityManager;
    switch(event.getType()) {
        case activated:
            if (event.getConcurrentAccessors() <= 1) {
                LOGGER.debug(() -> "First Thread to access " + mcrSession);
            }
            break;
        case passivated:
            currentEntityManager = unbind();
            autoCloseSession(currentEntityManager);
            break;
        case destroyed:
            currentEntityManager = unbind();
            autoCloseSession(currentEntityManager);
            break;
        case created:
            break;
        default:
            break;
    }
}
Also used : EntityManager(javax.persistence.EntityManager) MCRSession(org.mycore.common.MCRSession)

Example 2 with MCRSession

use of org.mycore.common.MCRSession in project mycore by MyCoRe-Org.

the class MCRAbstractCategoryImplTest method getCurrentLabel.

@Test
public void getCurrentLabel() {
    MCRCategory cat = new MCRSimpleAbstractCategoryImpl();
    MCRLabel label1 = new MCRLabel("de", "german", null);
    MCRLabel label2 = new MCRLabel("fr", "french", null);
    MCRLabel label3 = new MCRLabel("at", "austrian", null);
    cat.getLabels().add(label1);
    cat.getLabels().add(label2);
    cat.getLabels().add(label3);
    MCRSession session = MCRSessionMgr.getCurrentSession();
    session.setCurrentLanguage("en");
    assertEquals("German label expected", label3, cat.getCurrentLabel().get());
    cat.getLabels().clear();
    cat.getLabels().add(label2);
    cat.getLabels().add(label3);
    cat.getLabels().add(label1);
    assertEquals("German label expected", label3, cat.getCurrentLabel().get());
}
Also used : MCRCategory(org.mycore.datamodel.classifications2.MCRCategory) MCRSession(org.mycore.common.MCRSession) MCRLabel(org.mycore.datamodel.classifications2.MCRLabel) Test(org.junit.Test)

Example 3 with MCRSession

use of org.mycore.common.MCRSession in project mycore by MyCoRe-Org.

the class MCRUserInformationLookupTest method testLookupString.

@Test
public final void testLookupString() {
    MCRUserInformationLookup lookup = new MCRUserInformationLookup();
    assertNull("User information should not be available", lookup.lookup("id"));
    MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
    assertEquals(MCRSystemUserInformation.getGuestInstance().getUserID(), lookup.lookup("id"));
    assertNull("Guest user should have no role", lookup.lookup("role:admin:editor:submitter"));
    mcrSession.setUserInformation(new MCRUserInformation() {

        @Override
        public boolean isUserInRole(String role) {
            return !role.startsWith("a");
        }

        @Override
        public String getUserID() {
            return "junit";
        }

        @Override
        public String getUserAttribute(String attribute) {
            return null;
        }
    });
    String[] testRoles = { "admin", "editor", "submitter" };
    String expRole = testRoles[1];
    assertTrue("Current user should be in role " + expRole, mcrSession.getUserInformation().isUserInRole(expRole));
    assertEquals(expRole, lookup.lookup("role:" + Arrays.asList(testRoles).stream().collect(Collectors.joining(","))));
}
Also used : MCRSession(org.mycore.common.MCRSession) MCRUserInformation(org.mycore.common.MCRUserInformation) Test(org.junit.Test)

Example 4 with MCRSession

use of org.mycore.common.MCRSession in project mycore by MyCoRe-Org.

the class MCRRestAPIUploadHelper method uploadObject.

/**
 * uploads a MyCoRe Object
 * based upon:
 * http://puspendu.wordpress.com/2012/08/23/restful-webservice-file-upload-with-jersey/
 *
 * @param info - the Jersey UriInfo object
 * @param request - the HTTPServletRequest object
 * @param uploadedInputStream - the inputstream from HTTP Post request
 * @param fileDetails - the file information from HTTP Post request
 * @return a Jersey Response object
 * @throws MCRRestAPIException
 */
public static Response uploadObject(UriInfo info, HttpServletRequest request, InputStream uploadedInputStream, FormDataContentDisposition fileDetails) throws MCRRestAPIException {
    SignedJWT signedJWT = MCRJSONWebTokenUtil.retrieveAuthenticationToken(request);
    java.nio.file.Path fXML = null;
    try (MCRJPATransactionWrapper mtw = new MCRJPATransactionWrapper()) {
        SAXBuilder sb = new SAXBuilder();
        Document docOut = sb.build(uploadedInputStream);
        MCRObjectID mcrID = MCRObjectID.getInstance(docOut.getRootElement().getAttributeValue("ID"));
        if (mcrID.getNumberAsInteger() == 0) {
            mcrID = MCRObjectID.getNextFreeId(mcrID.getBase());
        }
        fXML = UPLOAD_DIR.resolve(mcrID + ".xml");
        docOut.getRootElement().setAttribute("ID", mcrID.toString());
        docOut.getRootElement().setAttribute("label", mcrID.toString());
        XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat());
        try (BufferedWriter bw = Files.newBufferedWriter(fXML, StandardCharsets.UTF_8)) {
            xmlOut.output(docOut, bw);
        }
        MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
        MCRUserInformation currentUser = mcrSession.getUserInformation();
        MCRUserInformation apiUser = MCRUserManager.getUser(MCRJSONWebTokenUtil.retrieveUsernameFromAuthenticationToken(signedJWT));
        mcrSession.setUserInformation(apiUser);
        // handles "create" as well
        MCRObjectCommands.updateFromFile(fXML.toString(), false);
        mcrSession.setUserInformation(currentUser);
        return Response.created(info.getBaseUriBuilder().path("v1/objects/" + mcrID).build()).type("application/xml; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, MCRJSONWebTokenUtil.createJWTAuthorizationHeader(signedJWT)).build();
    } catch (Exception e) {
        LOGGER.error("Unable to Upload file: {}", String.valueOf(fXML), e);
        throw new MCRRestAPIException(Status.BAD_REQUEST, new MCRRestAPIError(MCRRestAPIError.CODE_WRONG_PARAMETER, "Unable to Upload file: " + String.valueOf(fXML), e.getMessage()));
    } finally {
        if (fXML != null) {
            try {
                Files.delete(fXML);
            } catch (IOException e) {
                LOGGER.error("Unable to delete temporary workflow file: {}", String.valueOf(fXML), e);
            }
        }
    }
}
Also used : XMLOutputter(org.jdom2.output.XMLOutputter) SAXBuilder(org.jdom2.input.SAXBuilder) MCRRestAPIException(org.mycore.restapi.v1.errors.MCRRestAPIException) MCRRestAPIError(org.mycore.restapi.v1.errors.MCRRestAPIError) SignedJWT(com.nimbusds.jwt.SignedJWT) IOException(java.io.IOException) Document(org.jdom2.Document) MCRPersistenceException(org.mycore.common.MCRPersistenceException) MCRRestAPIException(org.mycore.restapi.v1.errors.MCRRestAPIException) MCRAccessException(org.mycore.access.MCRAccessException) IOException(java.io.IOException) BufferedWriter(java.io.BufferedWriter) MCRSession(org.mycore.common.MCRSession) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRUserInformation(org.mycore.common.MCRUserInformation)

Example 5 with MCRSession

use of org.mycore.common.MCRSession in project mycore by MyCoRe-Org.

the class MCRRestAPIUploadHelper method uploadDerivate.

/**
 * creates or updates a MyCoRe derivate
 * @param info - the Jersey UriInfo object
 * @param request - the HTTPServletRequest object
 * @param mcrObjID - the MyCoRe Object ID
 * @param label - the label of the new derivate
 * @param overwriteOnExistingLabel, if true an existing MyCoRe derivate with the given label will be returned
 * @return a Jersey Response object
 * @throws MCRRestAPIException
 */
public static Response uploadDerivate(UriInfo info, HttpServletRequest request, String mcrObjID, String label, boolean overwriteOnExistingLabel) throws MCRRestAPIException {
    Response response = Response.status(Status.INTERNAL_SERVER_ERROR).build();
    SignedJWT signedJWT = MCRJSONWebTokenUtil.retrieveAuthenticationToken(request);
    // File fXML = null;
    MCRObjectID mcrObjIDObj = MCRObjectID.getInstance(mcrObjID);
    try (MCRJPATransactionWrapper mtw = new MCRJPATransactionWrapper()) {
        MCRSession session = MCRServlet.getSession(request);
        MCRUserInformation currentUser = session.getUserInformation();
        MCRUserInformation apiUser = MCRUserManager.getUser(MCRJSONWebTokenUtil.retrieveUsernameFromAuthenticationToken(signedJWT));
        session.setUserInformation(apiUser);
        MCRObject mcrObj = MCRMetadataManager.retrieveMCRObject(mcrObjIDObj);
        MCRObjectID derID = null;
        if (overwriteOnExistingLabel) {
            for (MCRMetaLinkID derLink : mcrObj.getStructure().getDerivates()) {
                if (label.equals(derLink.getXLinkLabel()) || label.equals(derLink.getXLinkTitle())) {
                    derID = derLink.getXLinkHrefID();
                }
            }
        }
        if (derID == null) {
            derID = MCRObjectID.getNextFreeId(mcrObjIDObj.getProjectId() + "_derivate");
            MCRDerivate mcrDerivate = new MCRDerivate();
            mcrDerivate.setLabel(label);
            mcrDerivate.setId(derID);
            mcrDerivate.setSchema("datamodel-derivate.xsd");
            mcrDerivate.getDerivate().setLinkMeta(new MCRMetaLinkID("linkmeta", mcrObjIDObj, null, null));
            mcrDerivate.getDerivate().setInternals(new MCRMetaIFS("internal", UPLOAD_DIR.resolve(derID.toString()).toString()));
            MCRMetadataManager.create(mcrDerivate);
            MCRMetadataManager.addOrUpdateDerivateToObject(mcrObjIDObj, new MCRMetaLinkID("derobject", derID, null, label));
        }
        response = Response.created(info.getBaseUriBuilder().path("v1/objects/" + mcrObjID + "/derivates/" + derID).build()).type("application/xml; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, MCRJSONWebTokenUtil.createJWTAuthorizationHeader(signedJWT)).build();
        session.setUserInformation(currentUser);
    } catch (Exception e) {
        LOGGER.error("Exeption while uploading derivate", e);
    }
    return response;
}
Also used : Response(javax.ws.rs.core.Response) MCRSession(org.mycore.common.MCRSession) MCRObject(org.mycore.datamodel.metadata.MCRObject) MCRMetaLinkID(org.mycore.datamodel.metadata.MCRMetaLinkID) MCRDerivate(org.mycore.datamodel.metadata.MCRDerivate) SignedJWT(com.nimbusds.jwt.SignedJWT) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRMetaIFS(org.mycore.datamodel.metadata.MCRMetaIFS) MCRUserInformation(org.mycore.common.MCRUserInformation) MCRPersistenceException(org.mycore.common.MCRPersistenceException) MCRRestAPIException(org.mycore.restapi.v1.errors.MCRRestAPIException) MCRAccessException(org.mycore.access.MCRAccessException) IOException(java.io.IOException)

Aggregations

MCRSession (org.mycore.common.MCRSession)63 IOException (java.io.IOException)15 MCRUserInformation (org.mycore.common.MCRUserInformation)10 MCRObjectID (org.mycore.datamodel.metadata.MCRObjectID)10 MCRPath (org.mycore.datamodel.niofs.MCRPath)6 SignedJWT (com.nimbusds.jwt.SignedJWT)5 Date (java.util.Date)5 EntityManager (javax.persistence.EntityManager)5 Path (java.nio.file.Path)4 Response (javax.ws.rs.core.Response)4 Test (org.junit.Test)4 MCRRestAPIException (org.mycore.restapi.v1.errors.MCRRestAPIException)4 SAXException (org.xml.sax.SAXException)4 UnknownHostException (java.net.UnknownHostException)3 Document (org.jdom2.Document)3 MCRAccessException (org.mycore.access.MCRAccessException)3 MCRException (org.mycore.common.MCRException)3 MCRPersistenceException (org.mycore.common.MCRPersistenceException)3 MCRDerivate (org.mycore.datamodel.metadata.MCRDerivate)3 MCRRestAPIError (org.mycore.restapi.v1.errors.MCRRestAPIError)3