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.fosstrak.epcis.repository.capture.CaptureOperationsServlet.java

/**
 * Implements the EPCIS capture operation. Takes HTTP POST request, extracts
 * the payload into an XML document, validates the document against the
 * EPCIS schema, and captures the EPCIS events given in the document. Errors
 * are caught and returned as simple plaintext messages via HTTP.
 * /*from  w  ww  . j  a va  2s  . c  o  m*/
 * @param req
 *            The HttpServletRequest.
 * @param rsp
 *            The HttpServletResponse.
 * @throws IOException
 *             If an error occurred while validating the request or writing
 *             the response.
 */
public void doPost(final HttpServletRequest req, final HttpServletResponse rsp)
        throws ServletException, IOException {
    LOG.info("EPCIS Capture Interface invoked.");
    InputStream is = null;

    // check if we have a POST request with form parameters
    if ("application/x-www-form-urlencoded".equalsIgnoreCase(req.getContentType())) {
        rsp.setContentType("text/plain");
        PrintWriter out = rsp.getWriter();
        // check if the 'event' or 'dbReset' form parameter are given
        String event = req.getParameter("event");
        String dbReset = req.getParameter("dbReset");
        if (event != null) {
            LOG.info("Found deprecated 'event=' parameter. Refusing to process request.");
            String msg = "Starting from version 0.2.2, the EPCIS repository does not accept the EPCISDocument in the HTTP POST form parameter 'event' anymore. Please provide the EPCISDocument as HTTP POST payload instead.";
            rsp.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
            out.println(msg);
        } else if (dbReset != null && dbReset.equalsIgnoreCase("true")) {
            doDbReset(rsp);
        }
        out.flush();
        out.close();
        return;
    } else {
        is = req.getInputStream();
    }

    // do the capture operation and handle exceptions
    String responseMsg = "";
    String detailedMsg = "";
    try {
        captureOperationsModule.doCapture(is, req.getUserPrincipal());
        rsp.setStatus(HttpServletResponse.SC_OK);
        responseMsg = "EPCIS capture request succeeded.";
    } catch (SAXException e) {
        responseMsg = "An error processing the XML document occurred.";
        detailedMsg = "Unable to parse incoming XML due to error: " + e.getMessage();
        LOG.info(detailedMsg);
        rsp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } catch (InvalidFormatException e) {
        responseMsg = "An error parsing the XML contents occurred.";
        detailedMsg = "Unable to parse incoming EPCISDocument due to error: " + e.getMessage();
        LOG.info(detailedMsg);
        rsp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } catch (final Exception e) {
        responseMsg = "An unexpected error occurred.";
        detailedMsg = "The repository is unable to handle the request due to an internal error.";
        LOG.error(responseMsg, e);
        rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    // dispatch the response
    req.setAttribute("responseMsg", responseMsg);
    req.setAttribute("detailedMsg", detailedMsg);
    RequestDispatcher dispatcher;
    String showCaptureForm = (String) req.getAttribute("showCaptureForm");
    if (showCaptureForm != null && "true".equals(showCaptureForm)) {
        dispatcher = getServletContext().getRequestDispatcher(PAGE_CAPTURE_FORM);
    } else {
        dispatcher = getServletContext().getRequestDispatcher(PAGE_CAPTURE_INTERFACE);
    }
    dispatcher.forward(req, rsp);
}

From source file:org.apache.hadoop.hdfsproxy.ProxyFilter.java

/** {@inheritDoc} */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest rqst = (HttpServletRequest) request;
    HttpServletResponse rsp = (HttpServletResponse) response;

    if (LOG.isDebugEnabled()) {
        StringBuilder b = new StringBuilder("Request from ").append(rqst.getRemoteHost()).append("/")
                .append(rqst.getRemoteAddr()).append(":").append(rqst.getRemotePort());

        @SuppressWarnings("unchecked")
        Enumeration<String> e = rqst.getAttributeNames();
        for (; e.hasMoreElements();) {
            String attribute = e.nextElement();
            b.append("\n  " + attribute + " => " + rqst.getAttribute(attribute));
        }/* w w  w  .ja v  a 2s  . co m*/

        X509Certificate[] userCerts = (X509Certificate[]) rqst
                .getAttribute("javax.servlet.request.X509Certificate");
        if (userCerts != null)
            for (X509Certificate cert : userCerts)
                b.append("\n Client certificate Subject Name is " + cert.getSubjectX500Principal().getName());

        b.append("\n The Scheme is " + rqst.getScheme());
        b.append("\n The Auth Type is " + rqst.getAuthType());
        b.append("\n The Path Info is " + rqst.getPathInfo());
        b.append("\n The Translated Path Info is " + rqst.getPathTranslated());
        b.append("\n The Context Path is " + rqst.getContextPath());
        b.append("\n The Query String is " + rqst.getQueryString());
        b.append("\n The Remote User is " + rqst.getRemoteUser());
        b.append("\n The User Principal is " + rqst.getUserPrincipal());
        b.append("\n The Request URI is " + rqst.getRequestURI());
        b.append("\n The Request URL is " + rqst.getRequestURL());
        b.append("\n The Servlet Path is " + rqst.getServletPath());

        LOG.debug(b.toString());
    }

    boolean unitTest = false;
    if (rqst.getScheme().equalsIgnoreCase("http") && rqst.getParameter("UnitTest") != null)
        unitTest = true;

    if (rqst.getScheme().equalsIgnoreCase("https") || unitTest) {
        boolean isAuthorized = false;
        X509Certificate[] certs = (X509Certificate[]) rqst
                .getAttribute("javax.servlet.request.X509Certificate");

        if (unitTest) {
            try {
                LOG.debug("==> Entering https unit test");
                String SslPath = rqst.getParameter("SslPath");
                InputStream inStream = new FileInputStream(SslPath);
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
                inStream.close();
                certs = new X509Certificate[] { cert };
            } catch (Exception e) {
                // do nothing here
            }
        }

        if (certs == null || certs.length == 0) {
            rsp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No client SSL certificate received");
            LOG.info("No Client SSL certificate received");
            return;
        }
        for (X509Certificate cert : certs) {
            try {
                cert.checkValidity();
            } catch (CertificateExpiredException e) {
                LOG.info("Received cert for " + cert.getSubjectX500Principal().getName() + " expired");
                rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate expired");
                return;
            } catch (CertificateNotYetValidException e) {
                LOG.info("Received cert for " + cert.getSubjectX500Principal().getName() + " is not yet valid");
                rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate is not yet valid");
                return;
            }
        }

        String[] tokens = certs[0].getSubjectX500Principal().getName().split("\\s*,\\s*");
        String userID = null;
        for (String s : tokens) {
            if (s.startsWith("CN=")) {
                userID = s;
                break;
            }
        }
        if (userID == null || userID.length() < 4) {
            LOG.info("Can't retrieve user ID from SSL certificate");
            rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Can't retrieve user ID from SSL certificate");
            return;
        }
        userID = userID.substring(3);

        String servletPath = rqst.getServletPath();
        if (unitTest) {
            servletPath = rqst.getParameter("TestSevletPathInfo");
            LOG.info("this is for unit test purpose only");
        }

        if (HFTP_PATTERN.matcher(servletPath).matches()) {
            // request is an HSFTP request
            if (FILEPATH_PATTERN.matcher(servletPath).matches()) {
                // file path as part of the URL
                isAuthorized = checkPath(userID, certs[0],
                        rqst.getPathInfo() != null ? rqst.getPathInfo() : "/");
            } else {
                // file path is stored in "filename" parameter
                isAuthorized = checkPath(userID, certs[0], rqst.getParameter("filename"));
            }
        } else if (RELOAD_PATTERN.matcher(servletPath).matches() && checkUser("Admin", certs[0])) {
            Configuration conf = new Configuration(false);
            conf.addResource("hdfsproxy-default.xml");
            Map<String, Set<Path>> permsMap = getPermMap(conf);
            Map<String, Set<BigInteger>> certsMap = getCertsMap(conf);
            if (permsMap == null || certsMap == null) {
                LOG.warn("Permission files reloading failed");
                rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Permission files reloading failed");
                return;
            }
            ProxyFilter.permsMap = permsMap;
            ProxyFilter.certsMap = certsMap;
            LOG.info("User permissions and user certs files reloaded");
            rsp.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        if (!isAuthorized) {
            rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Unauthorized access");
            return;
        }

        // request is authorized, set ugi for servlets
        UserGroupInformation ugi = UserGroupInformation.createRemoteUser(userID);
        rqst.setAttribute("authorized.ugi", ugi);
        rqst.setAttribute("org.apache.hadoop.hdfsproxy.authorized.userID", userID);
    } else if (rqst.getScheme().equalsIgnoreCase("http")) { // http request, set ugi for servlets, only for testing purposes
        String ugi = rqst.getParameter("ugi");
        if (ugi != null) {
            rqst.setAttribute("authorized.ugi", UserGroupInformation.createRemoteUser(ugi));
            rqst.setAttribute("org.apache.hadoop.hdfsproxy.authorized.userID", ugi.split(",")[0]);
        }
    }
    chain.doFilter(request, response);
}

From source file:org.gots.server.auth.TempTokenAuthenticationServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // Get request parameters
    String applicationName = req.getParameter(APPLICATION_NAME_PARAM);
    String deviceId = req.getParameter(DEVICE_ID_PARAM);
    String deviceDescription = req.getParameter(DEVICE_DESCRIPTION_PARAM);
    String permission = req.getParameter(PERMISSION_PARAM);
    String revokeParam = req.getParameter(REVOKE_PARAM);
    boolean revoke = Boolean.valueOf(revokeParam);

    // If one of the required parameters is null or empty, send an
    // error with the 400 status
    if (!revoke && (StringUtils.isEmpty(applicationName) || StringUtils.isEmpty(deviceId)
            || StringUtils.isEmpty(permission))) {
        log.error(// w  w w .  j  a v a  2 s .c o m
                "The following request parameters are mandatory to acquire an authentication token: applicationName, deviceId, permission.");
        resp.sendError(HttpStatus.SC_BAD_REQUEST);
        return;
    }
    if (revoke && (StringUtils.isEmpty(applicationName) || StringUtils.isEmpty(deviceId))) {
        log.error(
                "The following request parameters are mandatory to revoke an authentication token: applicationName, deviceId.");
        resp.sendError(HttpStatus.SC_BAD_REQUEST);
        return;
    }

    // Decode parameters
    applicationName = URIUtil.decode(applicationName);
    deviceId = URIUtil.decode(deviceId);
    if (!StringUtils.isEmpty(deviceDescription)) {
        deviceDescription = URIUtil.decode(deviceDescription);
    }
    if (!StringUtils.isEmpty(permission)) {
        permission = URIUtil.decode(permission);
    }

    // Get user name from request Principal
    Principal principal = req.getUserPrincipal();
    if (principal == null) {
        resp.sendError(HttpStatus.SC_UNAUTHORIZED);
        return;
    }
    String userName = principal.getName();
    log.error("The principal user is " + userName);
    // Write response
    String response = null;
    TokenAuthenticationService tokenAuthService = Framework.getLocalService(TokenAuthenticationService.class);
    try {
        // Token acquisition: acquire token and write it to the response
        // body
        if (!revoke) {
            response = tokenAuthService.acquireToken(userName, applicationName, deviceId, deviceDescription,
                    permission);
        }
        // Token revocation
        else {
            String token = tokenAuthService.getToken(userName, applicationName, deviceId);
            if (token == null) {
                response = String.format(
                        "No token found for userName %s, applicationName %s and deviceId %s; nothing to do.",
                        userName, applicationName, deviceId);
            } else {
                tokenAuthService.revokeToken(token);
                response = String.format("Token revoked for userName %s, applicationName %s and deviceId %s.",
                        userName, applicationName, deviceId);
            }
        }
        sendTextResponse(resp, response);
    } catch (Exception e) {
        // Should never happen as parameters have already been checked
        resp.sendError(HttpStatus.SC_NOT_FOUND);
    }
}

From source file:org.openamf.AdvancedGateway.java

/**
 * Uses the setting in openamf-config.xml to gets the correct invoker,
 * enforce access control, and store state-beans in the request/session
 * //from  w w w  . ja v  a 2 s  .c o m
 * @see org.openamf.DefaultGateway#getServiceInvoker(org.openamf.AMFBody,
 *         javax.servlet.http.HttpServletRequest)
 */
protected ServiceInvoker getServiceInvoker(AMFBody requestBody, HttpServletRequest httpServletRequest)
        throws ServiceInvocationException {

    ServiceInvoker serviceInvoker = null;

    try {
        ServiceConfig serviceConfig = getServiceConfig(requestBody);

        if (serviceConfig == null) {
            throw new AccessDeniedException(
                    "could not find service configuration for '" + requestBody.getServiceName() + "'");
        }

        ServiceRequest request = new ServiceRequest(requestBody, serviceConfig);
        ServiceMethodConfig methodConfig = getMethodConfig(serviceConfig, request);
        // abort if no method config is found. This allows us to restrict
        // access to the service in the openamf configuration.
        if (methodConfig == null) {
            NoSuchMethodException e = new NoSuchMethodException(request.getRequestBody().toString());

            log.warn("Method config not found: " + request.getRequestBody().toString());
            throw e;
        }

        // store methodConfig for later use
        request.setServiceMethodConfig(methodConfig);

        // Check access permissions if there are any in the configuration
        Iterator constraints = methodConfig.getAccessConstraintConfigs();
        if (constraints.hasNext()) {
            boolean accessDenied = true;
            while (accessDenied && constraints.hasNext()) {
                ServiceMethodAccessConstraintConfig constraint = (ServiceMethodAccessConstraintConfig) constraints
                        .next();
                accessDenied = !httpServletRequest.isUserInRole(constraint.getRoleName());
            }
            if (accessDenied) {
                Principal user = httpServletRequest.getUserPrincipal();
                throw new AccessDeniedException((user == null ? "<anonymous user>" : user.getName()));
            }
        }

        addStateBeansToParams(httpServletRequest, request, methodConfig);

        serviceInvoker = ServiceInvoker.load(serviceConfig.getServiceInvokerConfig().getClassName(), request,
                httpServletRequest, getServletContext());

        serviceInvoker.prepare(request);

    } catch (Exception e) {
        throw new ServiceInvocationException(requestBody, e);
    }

    return serviceInvoker;
}

From source file:org.duracloud.duradmin.spaces.controller.ContentItemUploadController.java

@RequestMapping(value = "/spaces/content/upload", method = RequestMethod.POST)
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {/*from   w ww.j a v  a 2s. c  o m*/
        log.debug("handling request...");

        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        String spaceId = null;
        String storeId = null;
        String contentId = null;
        List<ContentItem> results = new ArrayList<ContentItem>();

        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                String value = Streams.asString(item.openStream(), "UTF-8");
                if (item.getFieldName().equals("spaceId")) {
                    log.debug("setting spaceId: {}", value);
                    spaceId = value;
                } else if (item.getFieldName().equals("storeId")) {
                    storeId = value;
                } else if (item.getFieldName().equals("contentId")) {
                    contentId = value;
                }
            } else {
                log.debug("setting fileStream: {}", item);

                if (StringUtils.isBlank(spaceId)) {
                    throw new IllegalArgumentException("space id required.");
                }

                ContentItem ci = new ContentItem();
                if (StringUtils.isBlank(contentId)) {
                    contentId = item.getName();
                }

                ci.setContentId(contentId);
                ci.setSpaceId(spaceId);
                ci.setStoreId(storeId);
                ci.setContentMimetype(item.getContentType());
                ContentStore contentStore = contentStoreManager.getContentStore(ci.getStoreId());
                ContentItemUploadTask task = new ContentItemUploadTask(ci, contentStore, item.openStream(),
                        request.getUserPrincipal().getName());

                task.execute();
                ContentItem result = new ContentItem();
                Authentication auth = (Authentication) SecurityContextHolder.getContext().getAuthentication();
                SpaceUtil.populateContentItem(ContentItemController.getBaseURL(request), result,
                        ci.getSpaceId(), ci.getContentId(), contentStore, auth);
                results.add(result);
                contentId = null;
            }
        }

        return new ModelAndView("javascriptJsonView", "results", results);

    } catch (Exception ex) {
        ex.printStackTrace();
        throw ex;
    }

}

From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.RMWebServices.java

private UserGroupInformation getCallerUserGroupInformation(HttpServletRequest hsr, boolean usePrincipal) {

    String remoteUser = hsr.getRemoteUser();
    if (usePrincipal) {
        Principal princ = hsr.getUserPrincipal();
        remoteUser = princ == null ? null : princ.getName();
    }//from w w w  .j  av  a2  s. com

    UserGroupInformation callerUGI = null;
    if (remoteUser != null) {
        callerUGI = UserGroupInformation.createRemoteUser(remoteUser);
    }

    return callerUGI;
}

From source file:net.i2cat.csade.life2.backoffice.servlet.UserManagementService.java

/**
 * Funcin que se ejecuta cuando el servlet recibe los datos
 *///from ww  w .  j a va 2 s.  c  o m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ChangablePropertiesManager cpm = new ChangablePropertiesManager(this.getServletContext());
    String operation = request.getParameter("operation");
    PlatformUserManager pum = new PlatformUserManager();
    String data = "";
    if (operation != null && !"".equals(operation)) {
        if (operation.equals("savePicturePreference")) {
            String photo_hor = request.getParameter("photo_hor");
            cpm.saveProperty("photo_hor", photo_hor);

            data = "{ \"message\": \"preferences saved.\" }";
        }
        if (operation.equals("getPicturePreference")) {
            String photo_hor = cpm.getProperty("photo_hor");

            data = "{ \"photo_hor\": \"" + photo_hor + "\"}";
        }

        if (operation.equals("getPlatformUser")) {
            String login = request.getParameter("login");
            try {
                data = pum.getUser(login).toJSON().toString();
            } catch (RemoteException re) {
                data = "{ \"message\": \"Could not not retrieve user with login=" + login + " Reason:"
                        + re.getMessage() + ".\" }";
            } catch (ServiceException se) {
                data = "{ \"message\": \"Could not not retrieve user with login=" + login + " Reason:"
                        + se.getMessage() + ".\" }";
            }
        }
        if (operation.equals("delPlatformUser")) {
            String login = request.getParameter("login");
            try {
                if (!request.isUserInRole("admin"))
                    throw new ServiceException("You are not allowed to delete users");
                if (login != null && login.equals(request.getUserPrincipal().getName()))
                    throw new ServiceException("You cannot delete your own user");
                pum.deleteUser(login);
                data = "{ \"message\": \"User with login " + login + " deleted.\" }";
            } catch (RemoteException re) {
                data = "{ \"message\": \"Could not not delete user with login=" + login + " Reason:"
                        + re.getMessage() + ".\" }";
            } catch (ServiceException se) {
                data = "{ \"message\": \"Could not not delete user with login=" + login + " Reason:"
                        + se.getMessage() + ".\" }";
            }
        }
        if (operation.equals("savePlatformUser")) {
            FileItem uploadedFile = null;
            PlatformUser user = null;
            int res = 0;
            byte[] foto = null;
            try {
                if (!request.isUserInRole("admin"))
                    throw new ServiceException("You are not allowed to upadte users");
                user = new PlatformUser();
                user.setNew(false);
                ServletFileUpload sfu = new ServletFileUpload(new DiskFileItemFactory());
                sfu.setFileSizeMax(329000);
                sfu.setHeaderEncoding("UTF-8");
                @SuppressWarnings("unchecked")
                List<FileItem> items = sfu.parseRequest(request);

                for (FileItem item : items) {
                    if (item.isFormField()) {
                        if (item.getFieldName().equals("login"))
                            user.setLogin(item.getString());
                        if (item.getFieldName().equals("username"))
                            user.setLogin(item.getString());
                        if (item.getFieldName().equals("password")) {
                            user.setPass(item.getString());
                        }
                        if (item.getFieldName().equals("idUser")) {
                            if (item.getString() == null || "".equals(item.getString()))
                                user.setNew(true);
                        }
                        if (item.getFieldName().equals("name")) {
                            byte[] fnb = item.get();
                            String text = PasswordGenerator.utf8Decoder(fnb);
                            user.setName(text);
                        }
                        if (item.getFieldName().equals("email")) {
                            String mail = item.getString();
                            if (MailUtils.isValidEmail(mail))
                                user.setEmail(mail);
                            else
                                throw new ServiceException("El email del usuario es incorrecto");
                        }
                        if (item.getFieldName().equals("telephonenumber"))
                            user.setTelephonenumber(item.getString());
                        if (item.getFieldName().equals("role"))
                            user.setRole(Integer.parseInt(item.getString()));
                        if (item.getFieldName().equals("language"))
                            user.setLanguage(item.getString());
                        if (item.getFieldName().equals("notification_level"))
                            user.setNotification_level(item.getString());
                        if (item.getFieldName().equals("promoter_id"))
                            user.setPromoter_id(item.getString());
                        if (item.getFieldName().equals("user_average_mark"))
                            user.setUser_average_mark(item.getString());
                        if (item.getFieldName().equals("user_votes"))
                            user.setUser_votes(item.getString());
                        if (item.getFieldName().equals("latitude"))
                            user.setHome_area_lat(item.getString());
                        if (item.getFieldName().equals("longitude"))
                            user.setHome_area_lon(item.getString());
                        if (item.getFieldName().equals("enabled"))
                            user.setEnabled(item.getString().equals("0") ? 0 : 1);
                    } else {
                        uploadedFile = item;
                        String inputExtension = FilenameUtils
                                .getExtension(uploadedFile.getName().toLowerCase());
                        if ("jpg".equals(inputExtension) || "gif".equals(inputExtension)
                                || "png".equals(inputExtension)) {
                            InputStream filecontent = item.getInputStream();
                            foto = new byte[(int) uploadedFile.getSize()];
                            filecontent.read(foto, 0, (int) uploadedFile.getSize());

                        }
                        //else
                        //   throw new FileUploadException("Extension not supported. Only jpg,gif or png files are allowed");
                    }
                }
                res = pum.saveUser(user);
                if (foto != null) {
                    //String v=cpm.getProperty("photo_hor");
                    //byte[] resizedPhoto=ImageUtil.resizeImageAsJPG(foto, (v==null || "".equals(v)) ?200:Integer.parseInt(v));
                    pum.uploadFoto(user.getLogin(), foto);
                }
                data = "{ \"message\": \"User with login " + user.getLogin() + " (id=" + res + ") saved.\" }";
            } catch (RemoteException exc) {
                data = "{ \"message\": \"Could not not save user with login=" + user.getLogin() + " Reason:"
                        + exc.getMessage() + ".\" }";
            } catch (ServiceException exc) {
                data = "{ \"message\": \"Could not not save user with login=" + user.getLogin() + " Reason:"
                        + exc.getMessage() + ".\" }";
            } catch (FileUploadException exc) {
                data = "{ \"message\": \"User with login " + user.getLogin() + " (id=" + res
                        + ") saved, but there was a problem uploading picture:" + exc.getMessage() + "\" }";
            }
        }
        if (operation.equals("listPlatformUsers")) {
            JQueryDataTableParamModel param = DataTablesParamUtility.getParam(request);
            try {
                JSONObject jsonResponse = pum.getPlatformUsersJSON(param);
                data = jsonResponse.toString();

            } catch (RemoteException re) {
                data = "{ \"message\": \"Could not not retrieve platform user listing. Reason:"
                        + re.getMessage() + ".\" }";
            } catch (ServiceException se) {
                data = "{ \"message\": \"Could not not retrieve platform user listing.  Reason:"
                        + se.getMessage() + ".\" }";
            }
        }
    }
    response.setContentType("application/json;charset=UTF-8");
    //response.setContentType("application/json");
    response.getWriter().print(data);
    response.getWriter().close();
}

From source file:edu.jhuapl.openessence.controller.ReportController.java

@RequestMapping("/graphBar")
public void graphBar(HttpServletRequest req, HttpServletResponse resp,
        @RequestParam("graphDataId") String dataId, @RequestParam(required = false) Integer resolution)
        throws GraphException, IOException {
    GraphDataSerializeToDiskHandler hndl = new GraphDataSerializeToDiskHandler(graphDir);
    GraphController gc = getGraphController(dataId, hndl, req.getUserPrincipal().getName());

    GraphDataInterface data = hndl.getGraphData(dataId);
    GraphObject graph = gc.createBarGraph(data, false);
    String filename = graph.getImageFileName();
    filename = filename.replaceAll("\\s", "_");
    resp.setContentType("image/png;charset=utf-8");
    resp.setHeader("Content-disposition", "attachment; filename=" + filename);

    OutputStream out = resp.getOutputStream();
    // why can't the graph module handle this?
    if (resolution == null) {
        graph.writeChartAsPNG(out, data.getGraphWidth(), data.getGraphHeight());
    } else {//  www. java2s  . c o m
        graph.writeChartAsHighResolutionPNG(out, data.getGraphWidth(), data.getGraphHeight(), resolution);
    }

}

From source file:edu.jhuapl.openessence.controller.ReportController.java

@RequestMapping("/graphPie")
public void graphPie(HttpServletRequest req, HttpServletResponse resp,
        @RequestParam("graphDataId") String dataId, @RequestParam(required = false) Integer resolution)
        throws GraphException, IOException {

    GraphDataSerializeToDiskHandler hndl = new GraphDataSerializeToDiskHandler(graphDir);
    GraphController gc = getGraphController(dataId, hndl, req.getUserPrincipal().getName());

    GraphDataInterface data = hndl.getGraphData(dataId);
    GraphObject graph = gc.createPieGraph(data);
    String filename = graph.getImageFileName();
    filename = filename.replaceAll("\\s", "_");
    resp.setContentType("image/png;charset=utf-8");
    resp.setHeader("Content-disposition", "attachment; filename=" + filename);

    OutputStream out = resp.getOutputStream();
    // why can't the graph module handle this?
    if (resolution == null) {
        graph.writeChartAsPNG(out, data.getGraphWidth(), data.getGraphHeight());
    } else {// w w  w .ja v a 2  s  .  c o m
        graph.writeChartAsHighResolutionPNG(out, data.getGraphWidth(), data.getGraphHeight(), resolution);
    }
}

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

@RequestMapping(value = "/user/modify", method = RequestMethod.POST)
@ResponseBody//from   w  w w.  j  a  v a  2 s  . com
public Status modifyUser(@RequestParam(required = true) String json,
        @RequestParam(required = true) String action, HttpServletRequest request) {

    IUserManager userManager = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this);
    if (userManager == null) {
        return new Status(StatusCode.NOSERVICE, "User Manager unavailable");
    }

    if (!authorize(userManager, UserLevel.NETWORKADMIN, request)) {
        return new Status(StatusCode.UNAUTHORIZED, "Operation not permitted");
    }

    UserConfig newConfig = gson.fromJson(json, UserConfig.class);
    List<UserConfig> currentUserConfig = userManager.getLocalUserList();
    String password = null;
    byte[] salt = null;
    String user = newConfig.getUser();
    for (UserConfig userConfig : currentUserConfig) {
        if (userConfig.getUser().equals(user)) {
            password = userConfig.getPassword();
            salt = userConfig.getSalt();
            break;
        }
    }
    if (password == null) {
        String msg = String.format("User %s not found in configuration database", user);
        return new Status(StatusCode.NOTFOUND, msg);
    }

    //While modifying a user role, the password is not provided from GUI for any user.
    //The password is stored in hash mode, hence it cannot be retrieved and added to UserConfig object
    //The hashed password is injected below to the json string containing username and new roles before
    //converting to UserConfig object.
    Gson gson = new Gson();
    json = json.replace("\"roles\"",
            "\"salt\":" + gson.toJson(salt, salt.getClass()) + ",\"password\":\"" + password + "\",\"roles\"");

    newConfig = gson.fromJson(json, UserConfig.class);

    Status result = userManager.modifyLocalUser(newConfig);
    if (result.isSuccess()) {
        DaylightWebUtil.auditlog("Roles of", request.getUserPrincipal().getName(), "updated",
                newConfig.getUser() + " to " + newConfig.getRoles().toString());
    }
    return result;
}