Search in sources :

Example 56 with AuthenticatedUser

use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.

the class DataversePage method saveSavedSearch.

public String saveSavedSearch() {
    if (linkingDataverseId == null) {
        JsfHelper.addErrorMessage("You must select a linking dataverse.");
        return "";
    }
    linkingDataverse = dataverseService.find(linkingDataverseId);
    AuthenticatedUser savedSearchCreator = getAuthenticatedUser();
    if (savedSearchCreator == null) {
        String msg = "Only authenticated users can save a search.";
        logger.severe(msg);
        JsfHelper.addErrorMessage(msg);
        return returnRedirect();
    }
    SavedSearch savedSearch = new SavedSearch(searchIncludeFragment.getQuery(), linkingDataverse, savedSearchCreator);
    savedSearch.setSavedSearchFilterQueries(new ArrayList<>());
    for (String filterQuery : searchIncludeFragment.getFilterQueriesDebug()) {
        /**
         * @todo Why are there null's here anyway? Turn on debug and figure
         * this out.
         */
        if (filterQuery != null && !filterQuery.isEmpty()) {
            SavedSearchFilterQuery ssfq = new SavedSearchFilterQuery(filterQuery, savedSearch);
            savedSearch.getSavedSearchFilterQueries().add(ssfq);
        }
    }
    CreateSavedSearchCommand cmd = new CreateSavedSearchCommand(dvRequestService.getDataverseRequest(), linkingDataverse, savedSearch);
    try {
        commandEngine.submit(cmd);
        List<String> arguments = new ArrayList<>();
        String linkString = "<a href=\"/dataverse/" + linkingDataverse.getAlias() + "\">" + StringEscapeUtils.escapeHtml(linkingDataverse.getDisplayName()) + "</a>";
        arguments.add(linkString);
        String successMessageString = BundleUtil.getStringFromBundle("dataverse.saved.search.success", arguments);
        JsfHelper.addSuccessMessage(successMessageString);
        return returnRedirect();
    } catch (CommandException ex) {
        String msg = "There was a problem linking this search to yours: " + ex;
        logger.severe(msg);
        JsfHelper.addErrorMessage(BundleUtil.getStringFromBundle("dataverse.saved.search.failure") + " " + ex);
        return returnRedirect();
    }
}
Also used : CreateSavedSearchCommand(edu.harvard.iq.dataverse.engine.command.impl.CreateSavedSearchCommand) SavedSearch(edu.harvard.iq.dataverse.search.savedsearch.SavedSearch) SavedSearchFilterQuery(edu.harvard.iq.dataverse.search.savedsearch.SavedSearchFilterQuery) ArrayList(java.util.ArrayList) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)

Example 57 with AuthenticatedUser

use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.

the class DataversePage method saveLinkedDataverse.

public String saveLinkedDataverse() {
    if (linkingDataverseId == null) {
        JsfHelper.addSuccessMessage("You must select a linking dataverse.");
        return "";
    }
    AuthenticatedUser savedSearchCreator = getAuthenticatedUser();
    if (savedSearchCreator == null) {
        String msg = "Only authenticated users can link a dataverse.";
        logger.severe(msg);
        JsfHelper.addErrorMessage(msg);
        return returnRedirect();
    }
    linkingDataverse = dataverseService.find(linkingDataverseId);
    LinkDataverseCommand cmd = new LinkDataverseCommand(dvRequestService.getDataverseRequest(), linkingDataverse, dataverse);
    // LinkDvObjectCommand cmd = new LinkDvObjectCommand (session.getUser(), linkingDataverse, dataverse);
    try {
        commandEngine.submit(cmd);
    } catch (CommandException ex) {
        String msg = "Unable to link " + dataverse.getDisplayName() + " to " + linkingDataverse.getDisplayName() + ". An internal error occurred.";
        logger.log(Level.SEVERE, "{0} {1}", new Object[] { msg, ex });
        JsfHelper.addErrorMessage(msg);
        return returnRedirect();
    }
    SavedSearch savedSearchOfChildren = createSavedSearchForChildren(savedSearchCreator);
    boolean createLinksAndIndexRightNow = false;
    if (createLinksAndIndexRightNow) {
        try {
            // create links (does indexing) right now (might be expensive)
            boolean debug = false;
            DataverseRequest dataverseRequest = new DataverseRequest(savedSearchCreator, SavedSearchServiceBean.getHttpServletRequest());
            savedSearchService.makeLinksForSingleSavedSearch(dataverseRequest, savedSearchOfChildren, debug);
            JsfHelper.addSuccessMessage(BundleUtil.getStringFromBundle("dataverse.linked.success", getSuccessMessageArguments()));
            return returnRedirect();
        } catch (SearchException | CommandException ex) {
            // error: solr is down, etc. can't link children right now
            JsfHelper.addErrorMessage(BundleUtil.getStringFromBundle("dataverse.linked.internalerror", getSuccessMessageArguments()));
            String msg = dataverse.getDisplayName() + " has been successfully linked to " + linkingDataverse.getDisplayName() + " but contents will not appear until an internal error has been fixed.";
            logger.log(Level.SEVERE, "{0} {1}", new Object[] { msg, ex });
            // JsfHelper.addErrorMessage(msg);
            return returnRedirect();
        }
    } else {
        // defer: please wait for the next timer/cron job
        // JsfHelper.addSuccessMessage(dataverse.getDisplayName() + " has been successfully linked to " + linkingDataverse.getDisplayName() + ". Please wait for its contents to appear.");
        JsfHelper.addSuccessMessage(BundleUtil.getStringFromBundle("dataverse.linked.success.wait", getSuccessMessageArguments()));
        return returnRedirect();
    }
}
Also used : DataverseRequest(edu.harvard.iq.dataverse.engine.command.DataverseRequest) SavedSearch(edu.harvard.iq.dataverse.search.savedsearch.SavedSearch) SearchException(edu.harvard.iq.dataverse.search.SearchException) CommandException(edu.harvard.iq.dataverse.engine.command.exception.CommandException) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) LinkDataverseCommand(edu.harvard.iq.dataverse.engine.command.impl.LinkDataverseCommand)

Example 58 with AuthenticatedUser

use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.

the class UserServiceBean method createAuthenticatedUserForView.

private AuthenticatedUser createAuthenticatedUserForView(Object[] dbRowValues, String roles, int rowNum) {
    AuthenticatedUser user = new AuthenticatedUser();
    user.setId(new Long((int) dbRowValues[0]));
    user.setUserIdentifier((String) dbRowValues[1]);
    user.setLastName(UserUtil.getStringOrNull(dbRowValues[2]));
    user.setFirstName(UserUtil.getStringOrNull(dbRowValues[3]));
    user.setEmail(UserUtil.getStringOrNull(dbRowValues[4]));
    user.setAffiliation(UserUtil.getStringOrNull(dbRowValues[5]));
    user.setSuperuser((Boolean) (dbRowValues[6]));
    user.setPosition(UserUtil.getStringOrNull(dbRowValues[7]));
    user.setCreatedTime(UserUtil.getTimestampOrNull(dbRowValues[8]));
    user.setLastLoginTime(UserUtil.getTimestampOrNull(dbRowValues[9]));
    user.setLastApiUseTime(UserUtil.getTimestampOrNull(dbRowValues[10]));
    user.setAuthProviderId(UserUtil.getStringOrNull(dbRowValues[11]));
    user.setAuthProviderFactoryAlias(UserUtil.getStringOrNull(dbRowValues[12]));
    user.setRoles(roles);
    return user;
}
Also used : AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)

Example 59 with AuthenticatedUser

use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.

the class UserServiceBean method getAuthenticatedUserList.

/**
 * Return the user information as a List of AuthenticatedUser objects -- easier to work with in the UI
 * - With Role added as a transient field
 * @param searchTerm
 * @param sortKey
 * @param resultLimit
 * @param offset
 * @return
 */
public List<AuthenticatedUser> getAuthenticatedUserList(String searchTerm, String sortKey, Integer resultLimit, Integer offset) {
    if ((offset == null) || (offset < 0)) {
        offset = 0;
    }
    List<Object[]> userResults = getUserListCore(searchTerm, sortKey, resultLimit, offset);
    // Initialize empty list for AuthenticatedUser objects
    // 
    List<AuthenticatedUser> viewObjects = new ArrayList<>();
    if (userResults == null) {
        return viewObjects;
    }
    // -------------------------------------------------
    // GATHER GIANT HASHMAP OF ALL { user identifier : [role, role, role] }
    // -------------------------------------------------
    HashMap<String, List<String>> roleLookup = retrieveRolesForUsers(userResults);
    if (roleLookup == null) {
        roleLookup = new HashMap<>();
    }
    // 1st Loop :
    // gather  [ @user, .....]
    // get the hashmap
    // -------------------------------------------------
    // We have results, format them into AuthenticatedUser objects
    // -------------------------------------------------
    // used for the rowNumber
    int rowNum = offset++;
    String roleString;
    for (Object[] userInfo : userResults) {
        // GET ROLES FOR THIS USER FROM GIANT HASHMAP
        rowNum++;
        // String roles = getUserRolesAsString((Integer) dbResultRow[0]);
        roleString = "";
        List<String> roleList = roleLookup.get("@" + (String) userInfo[1]);
        if ((roleList != null) && (!roleList.isEmpty())) {
            roleString = roleList.stream().collect(Collectors.joining(", "));
        }
        AuthenticatedUser singleUser = createAuthenticatedUserForView(userInfo, roleString, rowNum);
        viewObjects.add(singleUser);
    }
    return viewObjects;
}
Also used : ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)

Example 60 with AuthenticatedUser

use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.

the class DataverseTimerServiceBean method handleTimeout.

/**
 * This method is called whenever an EJB Timer goes off.
 * Check to see if this is a Harvest Timer, and if it is
 * Run the harvest for the given (scheduled) dataverse
 * @param timer
 */
@Timeout
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void handleTimeout(javax.ejb.Timer timer) {
    if (!systemConfig.isTimerServer()) {
        // logger.info("I am not the timer server! - bailing out of handleTimeout()");
        Logger.getLogger(DataverseTimerServiceBean.class.getName()).log(Level.WARNING, null, "I am not the timer server! - but handleTimeout() got called. Please investigate!");
    }
    try {
        logger.log(Level.INFO, "Handling timeout on " + InetAddress.getLocalHost().getCanonicalHostName());
    } catch (UnknownHostException ex) {
        Logger.getLogger(DataverseTimerServiceBean.class.getName()).log(Level.SEVERE, null, ex);
    }
    if (timer.getInfo() instanceof MotherTimerInfo) {
        logger.info("Behold! I am the Master Timer, king of all timers! I'm here to create all the lesser timers!");
        removeHarvestTimers();
        for (HarvestingClient client : harvestingClientService.getAllHarvestingClients()) {
            createHarvestTimer(client);
        }
    } else if (timer.getInfo() instanceof HarvestTimerInfo) {
        HarvestTimerInfo info = (HarvestTimerInfo) timer.getInfo();
        try {
            logger.log(Level.INFO, "running a harvesting client: id=" + info.getHarvestingClientId());
            // Timer batch jobs are run by the main Admin user.
            // TODO: revisit how we retrieve the superuser here.
            // Should it be configurable somewhere, which superuser
            // runs these jobs? Should there be a central mechanism for obtaining
            // the "major", builtin superuser for this Dataverse instance?
            // -- L.A. 4.5, Aug. 2016
            // getAuthenticatedUser("admin");
            AuthenticatedUser adminUser = authSvc.getAdminUser();
            if (adminUser == null) {
                logger.info("Scheduled harvest: failed to locate the admin user! Exiting.");
                throw new IOException("Scheduled harvest: failed to locate the admin user");
            }
            logger.info("found admin user " + adminUser.getName());
            DataverseRequest dataverseRequest = new DataverseRequest(adminUser, (HttpServletRequest) null);
            harvesterService.doHarvest(dataverseRequest, info.getHarvestingClientId());
        } catch (Throwable e) {
            // Harvester Service should be handling any error notifications,
            // if/when things go wrong.
            // (TODO: -- verify this logic; harvesterService may still be able
            // to throw an IOException, if it could not run the harvest at all,
            // or could not for whatever reason modify the database record...
            // in this case we should, probably, log the error and try to send
            // a mail notification. -- L.A. 4.4)
            // dataverseService.setHarvestResult(info.getHarvestingDataverseId(), harvesterService.HARVEST_RESULT_FAILED);
            // mailService.sendHarvestErrorNotification(dataverseService.find().getSystemEmail(), dataverseService.find().getName());
            logException(e, logger);
        }
    } else if (timer.getInfo() instanceof ExportTimerInfo) {
        try {
            ExportTimerInfo info = (ExportTimerInfo) timer.getInfo();
            logger.info("Timer Service: Running a scheduled export job.");
            // try to export all unexported datasets:
            datasetService.exportAll();
            // and update all oai sets:
            oaiSetService.exportAllSets();
        } catch (Throwable e) {
            logException(e, logger);
        }
    }
}
Also used : DataverseRequest(edu.harvard.iq.dataverse.engine.command.DataverseRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) UnknownHostException(java.net.UnknownHostException) IOException(java.io.IOException) HarvestingClient(edu.harvard.iq.dataverse.harvest.client.HarvestingClient) HarvestTimerInfo(edu.harvard.iq.dataverse.harvest.client.HarvestTimerInfo) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) TransactionAttribute(javax.ejb.TransactionAttribute) Timeout(javax.ejb.Timeout)

Aggregations

AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)125 Dataverse (edu.harvard.iq.dataverse.Dataverse)24 Timestamp (java.sql.Timestamp)24 Date (java.util.Date)24 CommandException (edu.harvard.iq.dataverse.engine.command.exception.CommandException)23 Dataset (edu.harvard.iq.dataverse.Dataset)22 DataverseRequest (edu.harvard.iq.dataverse.engine.command.DataverseRequest)21 Path (javax.ws.rs.Path)19 EJBException (javax.ejb.EJBException)16 ArrayList (java.util.ArrayList)14 User (edu.harvard.iq.dataverse.authorization.users.User)13 DataFile (edu.harvard.iq.dataverse.DataFile)11 IOException (java.io.IOException)11 JsonObjectBuilder (javax.json.JsonObjectBuilder)11 POST (javax.ws.rs.POST)11 Test (org.junit.Test)11 BuiltinUser (edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser)10 SwordError (org.swordapp.server.SwordError)10 DataverseRole (edu.harvard.iq.dataverse.authorization.DataverseRole)8 PermissionException (edu.harvard.iq.dataverse.engine.command.exception.PermissionException)8