Example usage for javax.servlet.http HttpServletRequest getRemoteUser

List of usage examples for javax.servlet.http HttpServletRequest getRemoteUser

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getRemoteUser.

Prototype

public String getRemoteUser();

Source Link

Document

Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated.

Usage

From source file:nl.fontys.fhict.jea.gwt.jee7.server.bus.FileUploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    System.out.println("working?");
    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {

        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        try {/*from   www  .  java  2s.c  om*/
            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                // process only file upload - discard other form item types
                if (item.isFormField()) {
                    continue;
                }

                String fileName = item.getName();
                // get only the file name not whole path
                if (fileName != null) {
                    fileName = FilenameUtils.getName(fileName);
                }

                File uploadedFile = new File(UPLOAD_DIRECTORY, fileName);
                uploadedFile.delete();
                if (uploadedFile.createNewFile()) {
                    item.write(uploadedFile);
                } else {
                    throw new IOException("The file already exists in repository.");
                }

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                BufferedImage in = ImageIO.read(uploadedFile);
                try {
                    ImageIO.write(in, "png", baos);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String imageString = "data:image/png;base64,"
                        + DatatypeConverter.printBase64Binary(baos.toByteArray());
                serviceBean.setPicture(req.getRemoteUser(), imageString);

                resp.setStatus(HttpServletResponse.SC_CREATED);
                resp.setContentType("image/png");
                resp.getWriter().print(imageString);
                resp.flushBuffer();

            }
        } catch (Exception e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while creating the file : " + e.getMessage());
        }

    } else {
        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:io.apiman.manager.ui.server.servlets.ConfigurationServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *///from   w w w  .  j  av a  2  s  . c o m
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        Class.forName("io.apiman.manager.ui.server.UIConfig"); //$NON-NLS-1$
    } catch (Throwable t) {
        t.printStackTrace();
    }

    JsonGenerator g = null;
    try {
        response.getOutputStream().write("window.APIMAN_CONFIG_DATA = ".getBytes("UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$
        JsonFactory f = new JsonFactory();
        g = f.createGenerator(response.getOutputStream(), JsonEncoding.UTF8);
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL);
        g.setCodec(mapper);
        g.useDefaultPrettyPrinter();

        // Get data from various sources.
        String endpoint = getConfig().getManagementApiEndpoint();
        if (endpoint == null) {
            endpoint = getDefaultEndpoint(request);
        }
        UIVersion version = UIVersion.get();
        ApiAuthType authType = getConfig().getManagementApiAuthType();

        ConfigurationBean configBean = new ConfigurationBean();
        configBean.setApiman(new AppConfigurationBean());
        configBean.setUser(new UserConfigurationBean());
        configBean.setUi(new UiConfigurationBean());
        configBean.setApi(new ApiConfigurationBean());
        configBean.getUi().setHeader("community"); //$NON-NLS-1$
        configBean.getUi().setMetrics(getConfig().isMetricsEnabled());
        configBean.getUi().setPlatform(getConfig().getPlatform());
        configBean.getApiman().setVersion(version.getVersionString());
        configBean.getApiman().setBuiltOn(version.getVersionDate());
        configBean.getApiman().setLogoutUrl(getConfig().getLogoutUrl());
        configBean.getUser().setUsername(request.getRemoteUser());
        configBean.getApi().setEndpoint(endpoint);
        configBean.getApi().setAuth(new ApiAuthConfigurationBean());
        switch (authType) {
        case authToken: {
            configBean.getApi().getAuth().setType(ApiAuthType.authToken);
            String tokenGeneratorClassName = getConfig().getManagementApiAuthTokenGenerator();
            if (tokenGeneratorClassName == null) {
                throw new ServletException("No token generator class specified."); //$NON-NLS-1$
            }
            Class<?> c = Class.forName(tokenGeneratorClassName);
            ITokenGenerator tokenGenerator = (ITokenGenerator) c.newInstance();
            configBean.getApi().getAuth().setBearerToken(tokenGenerator.generateToken(request));
            break;
        }
        case basic: {
            configBean.getApi().getAuth().setType(ApiAuthType.basic);
            configBean.getApi().getAuth().setBasic(new BasicAuthCredentialsBean());
            String username = getConfig().getManagementApiAuthUsername();
            String password = getConfig().getManagementApiAuthPassword();
            configBean.getApi().getAuth().getBasic().setUsername(username);
            configBean.getApi().getAuth().getBasic().setPassword(password);
            break;
        }
        case bearerToken: {
            configBean.getApi().getAuth().setType(ApiAuthType.bearerToken);
            String tokenGeneratorClassName = getConfig().getManagementApiAuthTokenGenerator();
            if (tokenGeneratorClassName == null)
                throw new ServletException("No token generator class specified."); //$NON-NLS-1$
            Class<?> c = Class.forName(tokenGeneratorClassName);
            ITokenGenerator tokenGenerator = (ITokenGenerator) c.newInstance();
            configBean.getApi().getAuth().setBearerToken(tokenGenerator.generateToken(request));
            break;
        }
        case samlBearerToken: {
            configBean.getApi().getAuth().setType(ApiAuthType.samlBearerToken);
            String tokenGeneratorClassName = getConfig().getManagementApiAuthTokenGenerator();
            if (tokenGeneratorClassName == null)
                throw new ServletException("No token generator class specified."); //$NON-NLS-1$
            Class<?> c = Class.forName(tokenGeneratorClassName);
            ITokenGenerator tokenGenerator = (ITokenGenerator) c.newInstance();
            configBean.getApi().getAuth().setBearerToken(tokenGenerator.generateToken(request));
            break;
        }
        }
        g.writeObject(configBean);

        g.flush();
        response.getOutputStream().write(";".getBytes("UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$
    } catch (Exception e) {
        throw new ServletException(e);
    } finally {
        IOUtils.closeQuietly(g);
    }
}

From source file:org.gbif.portal.web.controller.registration.RegistrationController.java

/**
 * Retrieve the provider for this request from UDDI. Returns null in case of bad key.
 * //from  ww  w.j  a v a 2s.c  o  m
 * @param request
 * @return
 * @throws NamingException
 * @throws UDDIException
 * @throws TransportException
 */
private ProviderDetail retrieveProviderFromUDDI(HttpServletRequest request) {
    ProviderDetail provider = null;
    String key = request.getParameter(REQUEST_BUSINESS_UDDI_KEY);
    // get the authenticated user from LDAP
    try {
        // need to cache these LDAP details for speed
        UserLogin userLogin = ldapUtils.getUserLogin(request.getRemoteUser());
        if (StringUtils.isNotEmpty(key)) {
            provider = uddiUtils.createProviderFromUDDI(key, userLogin.getUsername());
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return provider;
}

From source file:org.nema.medical.mint.server.controller.JobsController.java

@RequestMapping(method = RequestMethod.POST, value = "/jobs/createstudy")
public void createStudy(HttpServletRequest req, HttpServletResponse res) throws IOException {

    String studyUUID = UUID.randomUUID().toString();
    String jobID = UUID.randomUUID().toString();

    File jobFolder = new File(jobTemp, jobID);
    jobFolder.mkdirs();//w  w w.  j av a 2s .co m

    // the list of files uploaded
    List<File> files = new ArrayList<File>();

    // the set of form parameters
    Map<String, String> params = new HashMap<String, String>();

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    if (!isMultipart) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "expected multipart form data");
        return;
    }

    try {
        handleUpload(req, jobFolder, files, params);
    } catch (FileUploadException e) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "unable to parse multipart form data");
        return;
    }

    Iterator<File> iterator = files.iterator();
    if (!iterator.hasNext()) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "at least one file (containing metadata) is required.");
        return;
    }

    JobInfo jobInfo = new JobInfo();
    jobInfo.setId(jobID);
    jobInfo.setStudyID(studyUUID);
    jobInfo.setStatus(JobStatus.IN_PROGRESS);
    jobInfo.setStatusDescription("0% complete");
    String jobURI = req.getContextPath() + "/jobs/status/" + jobInfo.getId();
    jobInfoDAO.saveOrUpdateJobInfo(jobInfo);

    final MetadataType dataDictionary = availableTypes.get("DICOM");

    StudyCreateProcessor processor = new StudyCreateProcessor(jobFolder, new File(studiesRoot, studyUUID),
            dataDictionary, req.getRemoteUser(), req.getRemoteHost(), jobInfoDAO, studyDAO, updateDAO);
    executor.execute(processor); // process immediately in the background

    res.setStatus(HttpServletResponse.SC_SEE_OTHER);
    res.setHeader("Location", jobURI);
}

From source file:org.auscope.portal.server.web.controllers.GridSubmitController.java

/**
 * Creates a new Job object with predefined values for some fields.
 *
 * @param request The servlet request containing a session object
 *
 * @return The new job object./* w ww .j a va  2s  . c  o m*/
 */
private GeodesyJob prepareModel(HttpServletRequest request) {
    final String user = request.getRemoteUser();
    final String maxWallTime = "60"; // in minutes
    final String maxMemory = "2048"; // in MB
    final String stdInput = "";
    final String stdOutput = "stdOutput.txt";
    final String stdError = "stdError.txt";
    final String[] arguments = new String[0];
    final String[] inTransfers = new String[0];
    final String[] outTransfers = new String[0];
    String name = "GeodesyJob";
    String site = "iVEC";
    Integer cpuCount = 1;
    String version = "";
    String queue = "";
    String description = "";
    String scriptFile = "";

    // Set a default version and queue
    String[] allVersions = gridAccess.retrieveCodeVersionsAtSite(site, GeodesyJob.CODE_NAME);
    if (allVersions.length > 0)
        version = allVersions[0];

    String[] allQueues = gridAccess.retrieveQueueNamesAtSite(site);
    if (allQueues.length > 0)
        queue = allQueues[0];

    // Create a new directory to put all files for this job into.
    // This directory will always be the first stageIn directive.
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
    String dateFmt = sdf.format(new Date());
    String jobID = user + "-" + dateFmt + File.separator;
    String jobInputDir = gridAccess.getGridFtpStageInDir() + jobID;

    boolean success = createGridDir(request, jobInputDir);
    if (!success) {
        logger.error("Setting up Grid StageIn directory failed.");
        return null;
    }

    success = createGridDir(request, jobInputDir + GridSubmitController.RINEX_DIR + File.separator);
    if (!success) {
        logger.error("Setting up Grid Rinex StageIn directory failed.");
        return null;
    }

    //Create local stageIn directory.
    success = createLocalDir(request);
    if (!success) {
        logger.error("Setting up local StageIn directory failed.");
        return null;
    }

    // Save in session to use it when submitting job
    request.getSession().setAttribute("jobInputDir", jobInputDir);

    // Check if the user requested to re-submit a previous job.
    String jobIdStr = (String) request.getSession().getAttribute("resubmitJob");
    GeodesyJob existingJob = null;
    if (jobIdStr != null) {
        request.getSession().removeAttribute("resubmitJob");
        logger.debug("Request to re-submit a job.");
        try {
            int jobId = Integer.parseInt(jobIdStr);
            existingJob = jobManager.getJobById(jobId);
        } catch (NumberFormatException e) {
            logger.error("Error parsing job ID!");
        }
    }

    if (existingJob != null) {
        logger.debug("Using attributes of " + existingJob.getName());
        site = existingJob.getSite();
        version = existingJob.getVersion();
        name = existingJob.getName() + "_resubmit";
        scriptFile = existingJob.getScriptFile();
        description = existingJob.getDescription();

        allQueues = gridAccess.retrieveQueueNamesAtSite(site);
        if (allQueues.length > 0)
            queue = allQueues[0];

        logger.debug("Copying files from old job to stage-in directory");
        File srcDir = new File(existingJob.getOutputDir());
        File destDir = new File(jobInputDir);
        success = Util.copyFilesRecursive(srcDir, destDir);
        if (!success) {
            logger.error("Could not copy all files!");
            // TODO: Let user know this didn't work
        }
    }

    // Check if the ScriptBuilder was used. If so, there is a file in the
    // system temp directory which needs to be staged in.
    String newScript = (String) request.getSession().getAttribute("scriptFile");
    if (newScript != null) {
        request.getSession().removeAttribute("scriptFile");
        logger.debug("Adding " + newScript + " to stage-in directory");
        File tmpScriptFile = new File(
                System.getProperty("java.io.tmpdir") + File.separator + newScript + ".py");
        File newScriptFile = new File(jobInputDir, tmpScriptFile.getName());
        success = Util.moveFile(tmpScriptFile, newScriptFile);
        if (success) {
            logger.info("Moved " + newScript + " to stageIn directory");
            scriptFile = newScript + ".py";

            // Extract information from script file
            ScriptParser parser = new ScriptParser();
            try {
                parser.parse(newScriptFile);
                cpuCount = parser.getNumWorkerProcesses() + 1;
            } catch (IOException e) {
                logger.warn("Error parsing file: " + e.getMessage());
            }
        } else {
            logger.warn("Could not move " + newScript + " to stage-in!");
        }
    }

    logger.debug("Creating new GeodesyJob instance");
    GeodesyJob job = new GeodesyJob(site, name, version, arguments, queue, maxWallTime, maxMemory, cpuCount,
            inTransfers, outTransfers, user, stdInput, stdOutput, stdError);

    job.setScriptFile(scriptFile);
    job.setDescription(description);

    return job;
}

From source file:com.aurel.track.prop.LoginBL.java

/**
 * This method controls entire login procedure.
 *
 * @param isInTestMode// w  ww .  ja  v a 2  s.c  o  m
 * @param isMobileApplication
 * @param username
 * @param usingContainerBasedAuthentication
 * @param password
 * @param forwardUrl
 * @param springAuthenticated
 * @param mobileApplicationVersionNo
 * @param locale
 * @return
 */
public static String login(String isInTestMode, boolean isMobileApplication, String username,
        boolean usingContainerBasedAuthentication, String password, String forwardUrl,
        boolean springAuthenticated, Integer mobileApplicationVersionNo, Locale _locale) {
    Boolean ready = (Boolean) ServletActionContext.getServletContext().getAttribute(ApplicationStarter.READY);
    if (ready == null || !ready.booleanValue()) {
        return "loading";
    }
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpSession httpSession = request.getSession();
    String nonce = (String) httpSession.getAttribute("NONCE");

    if ("true".equals(isInTestMode)) {
        nonce = null; // accept clear text passwords
    }

    httpSession.setAttribute(ISMOBILEAPP, isMobileApplication);

    Locale locale = _locale;
    if (locale == null) {
        locale = Locale.getDefault();
        LOGGER.debug("Requested locale is null. Using default:" + locale.getDisplayName());
    } else {
        LOGGER.debug("Requested locale " + locale.getDisplayName());
    }
    httpSession.setAttribute("localizationJSON", LocalizeJSON.encodeLocalization(locale));
    TMotdBean motd = MotdBL.loadMotd(locale.getLanguage());

    if (motd == null) {
        motd = MotdBL.loadMotd("en");
    }
    // if already logged in forward to home page
    if (SessionUtils.getCurrentUser(httpSession) != null) {

        String redirectMapEntry = "itemNavigator";
        TPersonBean personBean = (TPersonBean) httpSession.getAttribute(Constants.USER_KEY);
        if (personBean != null && personBean.getHomePage() != null
                && personBean.getHomePage().trim().length() > 0) {
            redirectMapEntry = personBean.getHomePage();
        }
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        JSONUtility.appendBooleanValue(sb, JSONUtility.JSON_FIELDS.SUCCESS, true);
        sb.append(DATABRACE);
        JSONUtility.appendStringValue(sb, "jsonURL", redirectMapEntry + DOTACTION, true);
        sb.append("}");
        sb.append("}");
        return LoginBL.writeJSONResponse(sb); // The redirect is done by the
        // client JavaScript
    }
    // if Container Based Authentication is enabled and we can get a remote
    // user we use that one, no more questions asked. However, a local login
    // always overrules.

    if ((username == null || "".equals(username) || password == null || "".equals(password))
            && (request.getRemoteUser() != null
                    && ApplicationBean.getInstance().getSiteBean().getIsCbaAllowed())) {
        username = request.getRemoteUser();
        usingContainerBasedAuthentication = true;
    }

    List<LabelValueBean> errors = new ArrayList<LabelValueBean>();
    StringBuilder sb = new StringBuilder();
    String redirectMapEntry = "";
    sb = LoginBL.createLoginResponseJSON(username, password, nonce, usingContainerBasedAuthentication,
            springAuthenticated, request, errors, httpSession, forwardUrl, motd, isMobileApplication, locale,
            mobileApplicationVersionNo, redirectMapEntry);

    if (errors != null && errors.size() > 0 && usingContainerBasedAuthentication) {
        return "forwardToLogin"; // could not verify container registered
        // user with Genji
    }

    if (usingContainerBasedAuthentication && !isMobileApplication) {
        ACCESSLOGGER.info("User was authenticated via container.");
        if (redirectMapEntry.isEmpty())
            return SUCCESS;
        return redirectMapEntry;
    }
    return writeJSONResponse(sb); // The redirect is done by the client
    // JavaScript
}

From source file:org.gbif.portal.web.controller.registration.RegistrationController.java

/**
 * Synchronises the provider with the LDAP help entry for it if it exists (UUID being set)
 * or creates a new one if it does not exist.
 * /*from   w  w w  .  j  ava 2 s .c  o  m*/
 * @param request For any extra parameters
 * @param provider To synchronise
 * @param errors To add to when the uddi cannot be sync'ed with
 */
@SuppressWarnings("unchecked")
protected boolean synchroniseProvider(HttpServletRequest request, ProviderDetail provider, Errors errors) {
    try {
        logger.debug("Synchronizing provider");
        boolean creatingNewProvider = StringUtils.isEmpty(provider.getBusinessKey());
        uddiUtils.synchroniseProvider(provider);
        if (creatingNewProvider) {
            uddiUtils.createRegistrationLogin(request.getRemoteUser(), provider.getBusinessKey());
        }
        return true;
    } catch (Exception e) {
        logger.error("Unexpected error communicating with UDDI: " + e.getMessage(), e);
        errors.reject(ErrorMessageKeys.UDDI_COMMUNICATION_ERROR);
    }
    return false;
}

From source file:alpha.portal.webapp.controller.CardAssignFormController.java

/**
 * Adds the selected user to the case's participants and sets him as
 * Contributor for the card. Also returns to caseform on cancel.
 * /*from   ww w . j a  v a  2 s . c  om*/
 * @param request
 *            the request
 * @param response
 *            the response
 * @throws Exception
 *             the exception
 */
@RequestMapping(method = RequestMethod.POST)
public void onSubmit(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final String caseId = request.getParameter("case");
    final String cardId = request.getParameter("card");
    final String userId = request.getParameter("user");

    if (request.getParameter("cancel") != null) {
        this.returnToCase(response, caseId, cardId);
        return;
    }

    if (StringUtils.isBlank(userId)) {
        this.saveError(request, this.getText("cardassign.noUser", request.getLocale()));
        this.returnToCase(response, caseId, cardId);
        return;
    }

    Long userIdLong = null;
    try {
        userIdLong = Long.parseLong(userId);
    } catch (final NumberFormatException e) {
        this.saveError(request, "cardassign.invalidUser");
        this.returnToCase(response, caseId, cardId);
        return;
    }

    if (userIdLong == null) {
        this.saveMessage(request, this.getText("cardassign.invalidUser", request.getLocale()));
        this.returnToCase(response, caseId, cardId);
        return;
    }

    final AlphaCard card = this.cardManager.get(new AlphaCardIdentifier(caseId, cardId));

    UserExtension ue = null;
    try {
        ue = this.userExtensionManager.get(userIdLong);
    } catch (final DataAccessException e) {
    }
    if (ue == null) {
        try {
            final User u = this.getUserManager().get(userIdLong);
            ue = new UserExtension(u);
            ue = this.userExtensionManager.save(ue);
        } catch (final DataAccessException e) {
            this.saveError(request, "cardassign.invalidUser");
            this.returnToCase(response, caseId, cardId);
            return;
        }
    }

    ContributorRequest contrRequest = new ContributorRequest(
            this.getUserManager().getUserByUsername(request.getRemoteUser()),
            this.getUserManager().get(userIdLong), card);
    contrRequest = this.contrReqManager.save(contrRequest);

    response.sendRedirect("caseform?caseId=" + caseId + "&activeCardId=" + cardId);
}

From source file:org.auscope.portal.server.web.controllers.JobListController.java

/**
 * Returns a JSON object containing an array of jobs for the given series.
 *
 * @param request The servlet request including a seriesId parameter
 * @param response The servlet response/*  w  w  w. j  a va 2s.  co m*/
 *
 * @return A JSON object with a jobs attribute which is an array of
 *         <code>GeodesyJob</code> objects.
 */
@RequestMapping("/listJobs.do")
public ModelAndView listJobs(HttpServletRequest request, HttpServletResponse response) {

    String seriesIdStr = request.getParameter("seriesId");
    List<GeodesyJob> seriesJobs = null;
    ModelAndView mav = new ModelAndView("jsonView");
    Object credential = request.getSession().getAttribute("userCred");
    int seriesId = -1;

    if (credential == null) {
        final String errorString = "Invalid grid credentials!";
        logger.error(errorString);
        mav.addObject("error", errorString);
        mav.addObject("success", false);
        return mav;
    }

    if (seriesIdStr != null) {
        try {
            seriesId = Integer.parseInt(seriesIdStr);
            seriesJobs = jobManager.getSeriesJobs(seriesId);
        } catch (NumberFormatException e) {
            logger.error("Error parsing series ID '" + seriesIdStr + "'");
        }
    } else {
        logger.warn("No series ID specified!");
    }

    if (seriesJobs != null) {
        // check if current user is the owner of the series and update
        // the status of the jobs if so
        GeodesySeries s = jobManager.getSeriesById(seriesId);
        if (request.getRemoteUser().equals(s.getUser())) {
            logger.debug("Updating status of jobs attached to series " + seriesIdStr + ".");
            for (GeodesyJob j : seriesJobs) {
                String state = j.getStatus();
                if (!state.equals("Done") && !state.equals("Failed") && !state.equals("Cancelled")) {
                    String newState = gridAccess.retrieveJobStatus(j.getReference(), credential);
                    if (newState != null && !state.equals(newState)) {
                        j.setStatus(newState);
                        jobManager.saveJob(j);
                    } else if (newState == null) {
                        if (directoryExist(j.getOutputDir(), credential)) {
                            // job might have finished but status cannot be
                            // retrieved anymore -> a good heuristics is to check
                            // if the job files have been staged out and assume
                            // success if that is the case.
                            j.setStatus("Done");

                            jobManager.saveJob(j);
                        } else {
                            j.setStatus("Failed");
                            jobManager.saveJob(j);
                        }
                    }
                }
                String output = j.getOutputDir().substring(j.getOutputDir().indexOf("grid-auscope"),
                        j.getOutputDir().length());
                j.setOutputLocation("http://files.ivec.org/" + output);
            }
        }
        mav.addObject("jobs", seriesJobs);
    }

    logger.debug("Returning series job list");
    return mav;
}

From source file:org.gbif.portal.web.controller.registration.RegistrationController.java

/**
 * Update registration logins, creating those for the business keys passed in the request.
 * /*from  ww  w. j ava  2  s .  c  o m*/
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ModelAndView updateRegistrationLogins(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    String user = request.getParameter("user");
    boolean sendEmail = ServletRequestUtils.getBooleanParameter(request, "sendEmail", false);

    // if user is not supplied in a parameter, update is for the current user
    if (StringUtils.isEmpty(user)) {
        user = request.getRemoteUser();
    }

    String[] businessKeys = request.getParameterValues(REQUEST_BUSINESS_UDDI_KEY);
    String[] businessKeysToRemove = request.getParameterValues("businessKeyToRemove");
    List<String> existingKeys = uddiUtils.getAssociatedBusinessKeys(user);
    List<String> createdRegistrations = new ArrayList<String>();

    // add the selected registration logins
    if (businessKeys != null) {
        for (int i = 0; i < businessKeys.length; i++) {
            if (!existingKeys.contains(businessKeys[i])) {
                uddiUtils.createRegistrationLogin(user, businessKeys[i]);
                createdRegistrations.add(businessKeys[i]);
            }
        }
    }

    // if required sent a notification email
    if (sendEmail && !createdRegistrations.isEmpty()) {
        UserLogin userLogin = ldapUtils.getUserLogin(user);
        // send verification email
        SimpleMailMessage verificationMessage = new SimpleMailMessage(userTemplateMessage);
        verificationMessage.setTo(userLogin.getEmail());
        verificationMessage.setSubject("User has been granted access to Provider Details");
        StringBuffer sb = new StringBuffer(
                "Your request to access the details of the following providers has been granted:\n\n");
        for (String createdRegistration : createdRegistrations) {
            ProviderDetail pd = uddiUtils.createProviderFromUDDI(createdRegistration, userLogin.getUsername());
            sb.append(pd.getBusinessName());
            sb.append("\n");
        }
        verificationMessage.setText(sb.toString());
        try {
            mailSender.send(verificationMessage);
        } catch (MailException e) {
            // simply log it and go on...
            logger.error("Couldn't send message", e);
        }
    }

    // remove the selected registration logins
    if (businessKeysToRemove != null) {
        for (String element : businessKeysToRemove) {
            if (existingKeys.contains(element))
                uddiUtils.deleteRegistrationLogin(user, element);
        }
    }
    return new ModelAndView(new RedirectView(request.getContextPath() + "/register/"));
}