Example usage for javax.servlet.http HttpServletRequest getUserPrincipal

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

Introduction

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

Prototype

public java.security.Principal getUserPrincipal();

Source Link

Document

Returns a java.security.Principal object containing the name of the current authenticated user.

Usage

From source file:org.opendaylight.controller.web.DaylightWeb.java

@RequestMapping(value = "")
public String index(Model model, HttpServletRequest request) {
    IUserManager userManager = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this);
    if (userManager == null) {
        return "User Manager is not available";
    }/*from  w  w  w .ja v a  2 s.  co m*/

    String username = request.getUserPrincipal().getName();

    model.addAttribute("username", username);
    model.addAttribute("role", userManager.getUserLevel(username).toNumber());

    return "main";
}

From source file:org.jboss.bpm.console.server.FormProcessingFacade.java

@POST
@Path("task/{id}/complete")
@Produces("text/html")
@Consumes("multipart/form-data")
public Response closeTaskWithUI(@Context HttpServletRequest request, @PathParam("id") String taskId,
        MultipartFormDataInput payload) {
    FieldMapping mapping = createFieldMapping(payload);

    // complete task
    String username = request.getUserPrincipal() != null ? request.getUserPrincipal().getName() : null;

    String outcomeDirective = mapping.directives.get("outcome");

    if (outcomeDirective != null) {
        getTaskManagement().completeTask(Long.valueOf(taskId), // TODO: change to string id's
                outcomeDirective, // actually a plugin implementation detail
                mapping.processVars, username);
    } else {/*w w  w  . j ava 2  s . com*/
        getTaskManagement().completeTask(Long.valueOf(taskId), mapping.processVars, username);
    }

    return Response.ok(SUCCESSFULLY_PROCESSED_INPUT).build();
}

From source file:org.rti.zcore.dar.struts.action.ExportStockUpdate.java

protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    HttpSession session = request.getSession();
    Principal userPrincipal = request.getUserPrincipal();
    String username = userPrincipal.getName();

    String message = "";
    Connection conn = null;/* ww  w.  j  a v  a  2  s.  c  o m*/
    conn = DatabaseUtils.getAdminConnection();
    String backupDirectory = Constants.BACKUP_DIR;
    String tempBackupDirectory = Constants.BACKUP_TEMP_DIR;
    File tempDir = new File(tempBackupDirectory);
    if (!tempDir.exists()) {
        tempDir.mkdir();
    }
    String timestamp = DateUtils.getNowFileFormat();

    String updateBackupDirectory = tempBackupDirectory + "update_" + timestamp + File.separator;
    File updateDir = new File(updateBackupDirectory);
    if (!updateDir.exists()) {
        updateDir.mkdir();
    }
    PreparedStatement ps = null;

    String columnDelimiter = null;
    String characterdelimiter = null;
    String schemaName = "APP";

    String additionalAppTables = null;
    try {
        additionalAppTables = Constants.BACKUP_ADDITIONAL_APP_TABLES;
    } catch (NoSuchFieldError e) {
        // don't have it yet...
    }

    if (additionalAppTables != null) {
        for (StringTokenizer stringTokenizer = new StringTokenizer(additionalAppTables, ","); stringTokenizer
                .hasMoreTokens();) {
            String value = stringTokenizer.nextToken();
            value.trim();
            ps = conn.prepareStatement("CALL SYSCS_UTIL.SYSCS_EXPORT_TABLE (?,?,?,?,?,?)");
            ps.setString(1, schemaName);
            ps.setString(2, value);
            ps.setString(3, updateBackupDirectory + value + ".csv");
            ps.setString(4, columnDelimiter);
            ps.setString(5, characterdelimiter);
            ps.setString(6, null);
            ps.execute();
            ps.close();
        }
    }
    conn.close();

    int i = 0;
    // now zip up the files in the temp dir
    if (additionalAppTables != null) {
        for (StringTokenizer stringTokenizer = new StringTokenizer(additionalAppTables, ","); stringTokenizer
                .hasMoreTokens();) {
            i++;
            String tableName = stringTokenizer.nextToken();
            tableName.trim();
            String fileName = tableName + ".csv";
            String target = updateBackupDirectory + tableName + "_" + timestamp + ".zip";
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(target));
            Zip.addFile(updateBackupDirectory, fileName, zos);
            zos.close();
        }
    }

    // Create a manifest
    StringBuffer sb = new StringBuffer();
    int numTasks = 4 + i;
    String introText = "shutdownNetworkServer:Upgrade 1 of " + numTasks + " - Shut down the network server.:\n"
            + "startNetworkServerInsecureMode:Upgrade 2 of " + numTasks
            + " - Re-starts the DAR database in non-secure mode for upgrade.:\n"
            + "backupCurrentDatabase :Upgrade 3 of " + numTasks
            + " - Backs up the database. Please be patient; this will take a minute or two.:\n";
    int numIntroTasks = 3;
    sb.append(introText);
    //"importCsvData :Upgrade 4 of 5 - Updates the ITEM table in app schema.:ITEM_02082012_110400.zip,APP,ITEM,0,\n" + 
    int j = numIntroTasks;
    if (additionalAppTables != null) {
        for (StringTokenizer stringTokenizer = new StringTokenizer(additionalAppTables, ","); stringTokenizer
                .hasMoreTokens();) {
            j++;
            String tableName = stringTokenizer.nextToken();
            tableName.trim();
            String fileName = tableName + "_" + timestamp + ".zip";
            String output = "importCsvData :Upgrade " + j + " of " + numTasks + " - Updates the " + tableName
                    + " table in app schema.:" + fileName + ",APP," + tableName + ",0,\n";
            sb.append(output);
        }
    }
    String endText = "startNetworkServer:Upgrade " + (j + 1) + " of " + numTasks
            + " - Re-starts the DAR database.:\n" + "end:Upgrade complete. Close and re-open the DAR.:\n";
    sb.append(endText);
    String manifestPathname = updateBackupDirectory + "manifest.txt";
    try {
        BufferedWriter out = new BufferedWriter(new FileWriter(manifestPathname));
        String outText = sb.toString();
        out.write(outText);
        out.close();
    } catch (IOException e) {
        log.debug(e);
    }

    // now bundle them all up.

    String source = tempBackupDirectory;
    String includes = "update_" + timestamp + File.separator + ",update_" + timestamp + File.separator
            + "*.zip," + "update_" + timestamp + File.separator + "manifest.txt";
    String target = backupDirectory + "update_" + timestamp + ".zip";
    //Zip.zip(source, target, includes);
    org.apache.tools.ant.taskdefs.Zip zip = new org.apache.tools.ant.taskdefs.Zip();
    zip.setDestFile(new File(target));
    zip.setBasedir(new File(source));
    zip.setIncludes(includes);
    zip.setExcludes("update_" + timestamp + File.separator + "*.csv");
    zip.setProject(new Project());
    zip.execute();

    // delete the files in the temp dir
    FileUtils.cleanDir(updateBackupDirectory, false);
    FileUtils.cleanDir(tempBackupDirectory, false);

    request.setAttribute("message", "Update files exported to " + target);
    return mapping.findForward(SUCCESS_FORWARD);
}

From source file:com.tasktop.c2c.server.webdav.server.SpringAwareWebdavServlet.java

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

    ITransaction transaction = null;/*www . j a v a2  s. co  m*/
    boolean needRollback = false;

    try {
        Principal userPrincipal = req.getUserPrincipal();
        transaction = webdavStore.begin(userPrincipal);
        needRollback = true;
        webdavStore.checkAuthentication(transaction);

        IMethodExecutor methodExecutor = methodMap.get(req.getMethod());
        if (methodExecutor == null) {
            methodExecutor = methodMap.get("*NO*IMPL*");
        }

        methodExecutor.execute(transaction, req, resp);

        webdavStore.commit(transaction);
        needRollback = false;

    } catch (UnauthenticatedException e) {
        resp.sendError(WebdavStatus.SC_UNAUTHORIZED);
    } catch (AccessDeniedException ade) {

        // If we got a security exception, determine the correct type of error code to return.
        AuthenticationToken token = AuthenticationServiceUser.getCurrent().getToken();
        List<String> roles = token.getAuthorities();

        // Our request was rejected - time to send back an appropriate error.
        if (roles.contains(Role.Anonymous)) {
            // This was an anonymous request, so prompt the user for credentials - perhaps they can still do this.
            resp.addHeader("WWW-Authenticate",
                    String.format("Basic realm=\"%s\"", TenancyUtil.getCurrentTenantProjectIdentifer()));
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Please login to continue");
        } else {
            // This user was authenticated, but this request is not allowed for permissions reasons - reject it.
            resp.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "Insufficient permissions to perform this WebDav request");
        }
    } catch (Exception e) {
        LOG.error(e);
        resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
        throw new ServletException(e);
    } finally {
        if (needRollback) {
            webdavStore.rollback(transaction);
        }
    }
}

From source file:org.opendaylight.controller.web.DaylightWeb.java

@RequestMapping(value = "logout")
public String logout(Map<String, Object> model, final HttpServletRequest request) {

    IUserManager userManager = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this);
    if (userManager == null) {
        return "User Manager is not available";
    }//w  ww.  j ava  2 s  . co m
    String username = request.getUserPrincipal().getName();
    HttpSession session = request.getSession(false);
    if (session != null) {
        if (username != null) {
            userManager.userLogout(username);
        }
        session.invalidate();

    }
    return "redirect:" + "/";
}

From source file:org.tolven.restful.UserFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    HttpSession session = request.getSession();
    //      LoginContext loginContext = (LoginContext) session.getAttribute("loginContext");
    Principal principal = request.getUserPrincipal();
    // If we have a principal, then we can proceed
    if (principal != null) {
        chain.doFilter(servletRequest, servletResponse);
        return;//w  w w . j  a v a 2  s . c  o m
    }
    // before we accept a password, must ensure that this is a secure session
    if (!request.isSecure()) {
        response.setStatus(403);
        return;
    }
    String authorizationHeader = request.getHeader("Authorization");
    // See if we have the username/password
    if (authorizationHeader != null && authorizationHeader.startsWith("Basic ")) {
        Base64 decoder = new Base64();
        byte[] decoded = decoder.decode(authorizationHeader.substring(6).getBytes());
        String[] usernamePassword = new String(decoded).split(":");
        //WebAuthentication webA = new WebAuthentication();
        //boolean loginStatus = webA.login(usernamePassword[0], usernamePassword[1]);
        //if (!loginStatus) {
        //   response.setStatus(403);
        //   System.out.println( "Login for " + usernamePassword[0] + " - failed");
        //   return;
        //}
        System.out.println("Login for " + usernamePassword[0] + " - succeeded");
        //principal = new TolvenPrincipal(usernamePassword[0]);
        Subject subject = new Subject();
        subject.getPrincipals().add(principal);
        //            loginContext = new LoginContext("tolvenLDAP", subject, new CB(usernamePassword[0], usernamePassword[1].toCharArray()));
        //            loginContext.login();
        // Success
        //         session.setAttribute("loginContext", loginContext);
        chain.doFilter(servletRequest, servletResponse);
    } else {
        // Ask for password now
        response.setStatus(401);
        response.setHeader("WWW-Authenticate", "Basic realm=\"tolvenLDAP\"");
    }
}

From source file:org.nuxeo.ecm.platform.web.common.session.NuxeoHttpSessionMonitor.java

public SessionInfo associatedUser(HttpServletRequest request) {
    HttpSession session = request.getSession(false);
    if (session != null && session.getId() != null) {
        SessionInfo si = sessionTracker.get(session.getId());
        if (si == null) {
            si = addEntry(session);/*w  w  w .ja  v a 2s.  co m*/
        }
        if (request.getUserPrincipal() != null && si.getLoginName() == null) {
            si.setLoginName(request.getUserPrincipal().getName());
            CounterHelper.increaseCounter(SESSION_COUNTER);
        }
        si.setLastAccessUrl(request.getRequestURI());
        increaseRequestCounter();
        return si;
    }
    return null;
}

From source file:edu.emory.cci.aiw.cvrg.eureka.services.resource.UserResource.java

/**
 * Put an updated user to the system. Unless the user has the admin role,
 * s/he may only update their own user info.
 *
 * @param inUser Object containing all the information about the user to
 * add.//w  w w .  j a va2 s  .c o  m
 * @return A "Created" response with a link to the user page if successful.
 */
@RolesAllowed({ "researcher", "admin" })
@Path("/{id}")
@PUT
public Response putUser(@Context HttpServletRequest req, User inUser, @PathParam("id") Long inId) {
    String username = req.getUserPrincipal().getName();
    if (!req.isUserInRole("admin") && !username.equals(inUser.getUsername())) {
        throw new HttpStatusException(Response.Status.FORBIDDEN);
    }
    LOGGER.debug("Received updated user: {}", inUser);
    Response response;
    UserEntity currentUser = this.userDao.retrieve(inId);
    boolean activation = (!currentUser.isActive()) && (inUser.isActive());
    List<Role> updatedRoles = this.roleIdsToRoles(inUser.getRoles());

    currentUser.setRoles(updatedRoles);
    currentUser.setActive(inUser.isActive());
    currentUser.setLastLogin(inUser.getLastLogin());

    if (this.validateUpdatedUser(currentUser)) {
        LOGGER.debug("Saving updated user: {}", currentUser.getEmail());
        this.userDao.update(currentUser);

        if (activation) {
            try {
                this.emailSender.sendActivationMessage(currentUser);
            } catch (EmailException ee) {
                LOGGER.error(ee.getMessage(), ee);
            }
        }
        response = Response.ok().entity(currentUser).build();
    } else {
        response = Response.notModified(this.validationError).build();
    }
    return response;
}

From source file:org.opendaylight.phoenix.web.DaylightWeb.java

@RequestMapping(value = "web.json")
@ResponseBody/*from   w w  w .ja  v  a 2  s .c  o m*/
public Map<String, Map<String, Object>> bundles(HttpServletRequest request) {
    Object[] instances = ServiceHelper.getGlobalInstances(IDaylightWeb.class, this, null);
    Map<String, Map<String, Object>> bundles = new HashMap<String, Map<String, Object>>();
    if (instances == null) {
        return bundles;
    }
    Map<String, Object> entry;
    IDaylightWeb bundle;
    String username = request.getUserPrincipal().getName();
    IUserManager userManger = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this);
    for (Object instance : instances) {
        bundle = (IDaylightWeb) instance;
        if (userManger != null && bundle.isAuthorized(userManger.getUserLevel(username))) {
            entry = new HashMap<String, Object>();
            entry.put("name", bundle.getWebName());
            entry.put("order", bundle.getWebOrder());
            bundles.put(bundle.getWebId(), entry);
        }
    }
    return bundles;
}

From source file:org.eurekaclinical.user.service.resource.UserResource.java

/**
 * Get a user using the username.//from  ww  w .  j  av a2s.c o  m
 *
 * @param req The HTTP request containing the user name.
 *
 * @return The user corresponding to the given name.
 */
@RolesAllowed({ "researcher", "admin" })
@Path("/me")
@GET
public User getMe(@Context HttpServletRequest req) {

    AttributePrincipal principal = (AttributePrincipal) req.getUserPrincipal();
    String username = principal.getName();
    UserEntity userEntity = this.userDao.getByName(username);
    if (userEntity != null) {
        this.userDao.refresh(userEntity);
    } else {
        throw new HttpStatusException(Response.Status.NOT_FOUND);
    }
    LOGGER.debug("Returning user for name {}", username);
    UserEntityToUserVisitor visitor = new UserEntityToUserVisitor();
    userEntity.accept(visitor);
    return visitor.getUser();
}