Search in sources :

Example 56 with MCRSession

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

the class MCRSwordUtil method extractZipToPath.

public static void extractZipToPath(Path zipFilePath, MCRPath target) throws SwordError, IOException, NoSuchAlgorithmException, URISyntaxException {
    LOGGER.info("Extracting zip: {}", zipFilePath);
    try (FileSystem zipfs = FileSystems.newFileSystem(new URI("jar:" + zipFilePath.toUri()), new HashMap<>())) {
        final Path sourcePath = zipfs.getPath("/");
        Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                final Path relativeSP = sourcePath.relativize(dir);
                // WORKAROUND for bug
                Path targetdir = relativeSP.getNameCount() == 0 ? target : target.resolve(relativeSP);
                try {
                    Files.copy(dir, targetdir);
                } catch (FileAlreadyExistsException e) {
                    if (!Files.isDirectory(targetdir))
                        throw e;
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                MCRSession currentSession = MCRSessionMgr.getCurrentSession();
                LOGGER.info("Extracting: {}", file);
                Path targetFilePath = target.resolve(sourcePath.relativize(file));
                // and before completion we start the transaction to let niofs write the md5 to the table
                try (SeekableByteChannel destinationChannel = Files.newByteChannel(targetFilePath, StandardOpenOption.WRITE, StandardOpenOption.SYNC, StandardOpenOption.CREATE);
                    SeekableByteChannel sourceChannel = Files.newByteChannel(file, StandardOpenOption.READ)) {
                    if (currentSession.isTransactionActive()) {
                        currentSession.commitTransaction();
                    }
                    ByteBuffer buffer = ByteBuffer.allocateDirect(COPY_BUFFER_SIZE);
                    while (sourceChannel.read(buffer) != -1 || buffer.position() > 0) {
                        buffer.flip();
                        destinationChannel.write(buffer);
                        buffer.compact();
                    }
                } finally {
                    if (!currentSession.isTransactionActive()) {
                        currentSession.beginTransaction();
                    }
                }
                return FileVisitResult.CONTINUE;
            }
        });
    }
}
Also used : Path(java.nio.file.Path) MCRPath(org.mycore.datamodel.niofs.MCRPath) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) URI(java.net.URI) ByteBuffer(java.nio.ByteBuffer) SeekableByteChannel(java.nio.channels.SeekableByteChannel) MCRSession(org.mycore.common.MCRSession) FileSystem(java.nio.file.FileSystem) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 57 with MCRSession

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

the class MCRSwordServlet method prepareRequest.

protected void prepareRequest(HttpServletRequest req, HttpServletResponse resp) {
    if (req.getAttribute(MCRFrontendUtil.BASE_URL_ATTRIBUTE) == null) {
        String webappBase = MCRFrontendUtil.getBaseURL(req);
        req.setAttribute(MCRFrontendUtil.BASE_URL_ATTRIBUTE, webappBase);
    }
    MCRSession session = MCRServlet.getSession(req);
    MCRSessionMgr.setCurrentSession(session);
    LOGGER.info(MessageFormat.format("{0} ip={1} mcr={2} user={3}", req.getPathInfo(), MCRFrontendUtil.getRemoteAddr(req), session.getID(), session.getUserInformation().getUserID()));
    MCRFrontendUtil.configureSession(session, req, resp);
    MCRSessionMgr.getCurrentSession().beginTransaction();
}
Also used : MCRSession(org.mycore.common.MCRSession)

Example 58 with MCRSession

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

the class MCRPIJobRegistrationService method runAsJobUser.

public void runAsJobUser(PIRunnable task) throws MCRPersistentIdentifierException {
    final boolean jobUserPresent = isJobUserPresent();
    final String jobUser = getJobUser();
    MCRSession session = null;
    MCRUserInformation savedUserInformation = null;
    session = MCRSessionMgr.getCurrentSession();
    if (jobUserPresent) {
        savedUserInformation = session.getUserInformation();
        MCRUser user = MCRUserManager.getUser(jobUser);
        /* workaround https://mycore.atlassian.net/browse/MCR-1400*/
        session.setUserInformation(MCRSystemUserInformation.getGuestInstance());
        session.setUserInformation(user);
        LOGGER.info("Continue as User {}", jobUser);
    }
    boolean transactionActive = !session.isTransactionActive();
    try {
        if (transactionActive) {
            session.beginTransaction();
        }
        task.run();
    } finally {
        if (transactionActive && session.isTransactionActive()) {
            session.commitTransaction();
        }
        if (jobUserPresent) {
            LOGGER.info("Continue as previous User {}", savedUserInformation.getUserID());
            /* workaround https://mycore.atlassian.net/browse/MCR-1400*/
            session.setUserInformation(MCRSystemUserInformation.getGuestInstance());
            session.setUserInformation(savedUserInformation);
        }
    }
}
Also used : MCRSession(org.mycore.common.MCRSession) MCRUser(org.mycore.user2.MCRUser) MCRUserInformation(org.mycore.common.MCRUserInformation)

Example 59 with MCRSession

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

the class MCROAISearchManager method getRecordListParallel.

private OAIDataList<Record> getRecordListParallel(MCROAISearcher searcher, MCROAIResult result) {
    List<Header> headerList = result.list();
    int listSize = headerList.size();
    Record[] records = new Record[listSize];
    @SuppressWarnings("rawtypes") CompletableFuture[] futures = new CompletableFuture[listSize];
    MetadataFormat metadataFormat = searcher.getMetadataFormat();
    MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
    for (int i = 0; i < listSize; i++) {
        Header header = headerList.get(i);
        int resultIndex = i;
        MCRTransactionableRunnable r = new MCRTransactionableRunnable(() -> records[resultIndex] = this.objManager.getRecord(header, metadataFormat), mcrSession);
        CompletableFuture<Void> future = CompletableFuture.runAsync(r, executorService);
        futures[i] = future;
    }
    CompletableFuture.allOf(futures).join();
    OAIDataList<Record> recordList = new OAIDataList<>();
    recordList.addAll(Arrays.asList(records));
    return recordList;
}
Also used : OAIDataList(org.mycore.oai.pmh.OAIDataList) CompletableFuture(java.util.concurrent.CompletableFuture) MetadataFormat(org.mycore.oai.pmh.MetadataFormat) MCRSession(org.mycore.common.MCRSession) Header(org.mycore.oai.pmh.Header) Record(org.mycore.oai.pmh.Record) MCRTransactionableRunnable(org.mycore.util.concurrent.MCRTransactionableRunnable)

Example 60 with MCRSession

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

the class MCRHttpSessionListener method valueUnbound.

public void valueUnbound(HttpSessionBindingEvent hsbe) {
    LOGGER.debug("Attribute {} is beeing unbound from session", hsbe.getName());
    Object obj = hsbe.getValue();
    if (obj instanceof MCRSession) {
        MCRSession mcrSession = (MCRSession) obj;
        mcrSession.close();
    }
    LOGGER.debug("Attribute {} is unbounded from session", hsbe.getName());
}
Also used : MCRSession(org.mycore.common.MCRSession)

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