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:com.gtwm.pb.servlets.ServletSchemaMethods.java

public synchronized static void addOperationalDashboardReport(SessionDataInfo sessionData,
        HttpServletRequest request, DatabaseInfo databaseDefn)
        throws MissingParametersException, ObjectNotFoundException, DisallowedException, CantDoThatException {
    BaseReportInfo report = ServletUtilMethods.getReportForRequest(sessionData, request, databaseDefn,
            ServletUtilMethods.USE_SESSION);
    AppUserInfo appUser = databaseDefn.getAuthManager().getUserByUserName(request, request.getRemoteUser());
    try {//  w w w.  ja  v a 2s  .  c  o  m
        HibernateUtil.startHibernateTransaction();
        HibernateUtil.activateObject(appUser);
        appUser.addOperationalDashboardReport(report);
        HibernateUtil.currentSession().getTransaction().commit();
    } catch (HibernateException hex) {
        rollbackConnections(null);
        throw new CantDoThatException(
                "adding report " + report + " to operational dashboard of user " + appUser + " failed", hex);
    } finally {
        HibernateUtil.closeSession();
    }
}

From source file:com.gtwm.pb.servlets.ServletSchemaMethods.java

public synchronized static void addFormTable(SessionDataInfo sessionData, HttpServletRequest request,
        DatabaseInfo databaseDefn)//w  w w .java2  s.co m
        throws MissingParametersException, ObjectNotFoundException, DisallowedException, CantDoThatException {
    TableInfo table = ServletUtilMethods.getTableForRequest(sessionData, request, databaseDefn,
            ServletUtilMethods.USE_SESSION);
    AppUserInfo appUser = databaseDefn.getAuthManager().getUserByUserName(request, request.getRemoteUser());
    try {
        HibernateUtil.startHibernateTransaction();
        HibernateUtil.activateObject(appUser);
        appUser.addFormTable(table);
        HibernateUtil.currentSession().getTransaction().commit();
    } catch (HibernateException hex) {
        rollbackConnections(null);
        throw new CantDoThatException("adding table " + table + " to forms for user " + appUser + " failed",
                hex);
    } finally {
        HibernateUtil.closeSession();
    }
}

From source file:com.gtwm.pb.servlets.ServletSchemaMethods.java

public synchronized static void removeFormTable(SessionDataInfo sessionData, HttpServletRequest request,
        DatabaseInfo databaseDefn)//from w  ww  .jav  a 2  s.  co m
        throws MissingParametersException, ObjectNotFoundException, DisallowedException, CantDoThatException {
    TableInfo table = ServletUtilMethods.getTableForRequest(sessionData, request, databaseDefn,
            ServletUtilMethods.USE_SESSION);
    AppUserInfo appUser = databaseDefn.getAuthManager().getUserByUserName(request, request.getRemoteUser());
    try {
        HibernateUtil.startHibernateTransaction();
        HibernateUtil.activateObject(appUser);
        appUser.removeFormTable(table);
        HibernateUtil.currentSession().getTransaction().commit();
    } catch (HibernateException hex) {
        rollbackConnections(null);
        throw new CantDoThatException("removing table " + table + " from forms for user " + appUser + " failed",
                hex);
    } finally {
        HibernateUtil.closeSession();
    }
}

From source file:es.sm2.openppm.front.servlets.AbstractGenericServlet.java

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

    // Set multipart
    if (ServletFileUpload.isMultipartContent(request)) {
        try {

            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List fileItemList = servletFileUpload.parseRequest(request);
            Hashtable<String, FileItem> multipartFields = parseFields(fileItemList);

            this.setMultipartFields(multipartFields);
        } catch (Exception e) {
            ExceptionUtil.evalueException(request, getResourceBundle(request), LOGGER, e);
        }
    }

    String accion = ParamUtil.getString(request, "accion");
    String accionLogin = ParamUtil.getString(request, "a");
    String scrollTop = ParamUtil.getString(request, "scrollTop", null);
    setForward(false);

    if (scrollTop != null) {
        request.setAttribute("scrollTop", scrollTop);
    }

    // Add information to response
    SettingLogic logic = new SettingLogic();
    try {

        setLocale(request);
        addSettings(request);

        String infoApp = logic.findSetting(Settings.SETTING_INFORMATION);

        request.setAttribute("infoApp", infoApp);
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }

    if (SecurityUtil.consUserRole(request) == -1 && !HomeServlet.CHOOSE_ROL.equals(accion)
            && request.getRemoteUser() != null && !LoginServlet.LOGOFF.equals(accionLogin)
            && !ErrorServlet.ERROR_403.equals(accion)) {

        setRolSession(request, response);
    }

    // Send info plugins
    sendInfoPlugins(request, ValidateUtil.isNullCh(accion, accionLogin));

    // Send notification center data
    if (getUser(request) != null) {

        // List notifications
        JSONArray notifications = new JSONArray();

        // Declare logic
        NotificationLogic notificationLogic = new NotificationLogic();

        try {

            // Logic
            notifications = notificationLogic.findByContact(getUser(request).getContact());
        } catch (Exception e) {
            ExceptionUtil.evalueException(request, getResourceBundle(request), LOGGER, e);
        }

        // Send notifications to client
        request.setAttribute("notificationCenter", notifications.toString());
    }

}

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

/**
 * Processes a job submission request.//from ww  w . j  a  va 2  s .  c  om
 *
 * @param request The servlet request
 * @param response The servlet response
 *
 * @return A JSON object with a success attribute that indicates whether
 *         the job was successfully submitted.
 */
@RequestMapping("/submitJob.do")
public ModelAndView submitJob(HttpServletRequest request, HttpServletResponse response, GeodesyJob job) {

    logger.debug("Job details:\n" + job.toString());

    GeodesySeries series = null;
    boolean success = true;
    final String user = request.getRemoteUser();
    String jobInputDir = (String) request.getSession().getAttribute("jobInputDir");
    String newSeriesName = request.getParameter("seriesName");
    String seriesIdStr = request.getParameter("seriesId");
    ModelAndView mav = new ModelAndView("jsonView");
    Object credential = request.getSession().getAttribute("userCred");
    String localJobInputDir = (String) request.getSession().getAttribute("localJobInputDir");

    //Used to store Job Submission status, because there will be another request checking this.
    GridTransferStatus gridStatus = new GridTransferStatus();

    if (credential == null) {
        //final String errorString = "Invalid grid credentials!";
        logger.error(GridSubmitController.CREDENTIAL_ERROR);
        gridStatus.currentStatusMsg = GridSubmitController.CREDENTIAL_ERROR;
        gridStatus.jobSubmissionStatus = JobSubmissionStatus.Failed;

        // Save in session for status update request for this job.
        request.getSession().setAttribute("gridStatus", gridStatus);
        //mav.addObject("error", errorString);
        mav.addObject("success", false);
        return mav;
    }

    // if seriesName parameter was provided then we create a new series
    // otherwise seriesId contains the id of the series to use.
    if (newSeriesName != null && newSeriesName != "") {
        String newSeriesDesc = request.getParameter("seriesDesc");

        logger.debug("Creating new series '" + newSeriesName + "'.");
        series = new GeodesySeries();
        series.setUser(user);
        series.setName(newSeriesName);
        if (newSeriesDesc != null) {
            series.setDescription(newSeriesDesc);
        }
        jobManager.saveSeries(series);
        // Note that we can now access the series' new ID

    } else if (seriesIdStr != null && seriesIdStr != "") {
        try {
            int seriesId = Integer.parseInt(seriesIdStr);
            series = jobManager.getSeriesById(seriesId);
        } catch (NumberFormatException e) {
            logger.error("Error parsing series ID!");
        }
    }

    if (series == null) {
        success = false;
        final String msg = "No valid series found. NOT submitting job!";
        logger.error(msg);
        gridStatus.currentStatusMsg = msg;
        gridStatus.jobSubmissionStatus = JobSubmissionStatus.Failed;

    } else {
        //Reduce our list of input files to an array of urls
        List<GeodesyGridInputFile> gpsFiles = (List<GeodesyGridInputFile>) request.getSession()
                .getAttribute("gridInputFiles");
        logger.debug("gpsFiles: " + gpsFiles.toString());
        if (gpsFiles == null) {
            logger.warn("gridInputFiles is null, using empty list instead");
            gpsFiles = new ArrayList<GeodesyGridInputFile>();
        }

        String[] urlArray = new String[gpsFiles.size()];
        int urlArrayIndex = 0;
        for (GeodesyGridInputFile ggif : gpsFiles) {
            urlArray[urlArrayIndex++] = ggif.getFileUrl();
        }

        //Transfer job input files to Grid StageInURL
        //if(urlArray.length > 0){
        //   gridStatus = urlCopy(urlArray, request);
        //}          

        if (gridStatus.jobSubmissionStatus != JobSubmissionStatus.Failed) {

            job.setSeriesId(series.getId());
            //job.setArguments(new String[] { job.getScriptFile() });
            job.setJobType(job.getJobType().replace(",", ""));
            JSONArray args = JSONArray.fromObject(request.getParameter("arguments"));
            logger.info(
                    "Args count: " + job.getArguments().length + " | Args in Json : " + args.toArray().length);
            job.setArguments((String[]) args.toArray(new String[args.toArray().length]));

            // Create a new directory for the output files of this job
            //String certDN = (String)request.getSession().getAttribute("certDN");
            String certDN_DIR = "";
            try {
                certDN_DIR = generateCertDNDirectory(credential);
                logger.debug("certDN_DIR: " + certDN_DIR);
            } catch (GSSException e) {
                logger.error(FaultHelper.getMessage(e));
            }

            success = createGridDir(request, gridAccess.getGridFtpStageOutDir() + certDN_DIR + File.separator);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
            String dateFmt = sdf.format(new Date());
            String jobID = user + "-" + job.getName() + "-" + dateFmt + File.separator;
            String jobOutputDir = gridAccess.getGridFtpStageOutDir() + certDN_DIR + File.separator + jobID;

            // Add grid stage-in directory and local stage-in directory.
            String stageInURL = gridAccess.getGridFtpServer() + jobInputDir;
            logger.debug("stagInURL: " + stageInURL);

            if (job.getJobType().equals("single")) {

                //Transfer job input files to Grid StageInURL
                if (urlArray != null && urlArray.length > 0) {
                    // Full URL
                    // e.g. "gsiftp://pbstore.ivec.org:2811//pbstore/au01/grid-auscope/Abdi.Jama@csiro.au-20091103_163322/"
                    //       +"rinex/" + filename
                    String toURL = gridAccess.getGridFtpServer() + File.separator + jobInputDir
                            + GridSubmitController.RINEX_DIR + File.separator;
                    gridStatus = urlCopy(urlArray, request, toURL);
                }

                String localStageInURL = gridAccess.getLocalGridFtpServer()
                        + (String) request.getSession().getAttribute("localJobInputDir");
                job.setInTransfers(new String[] { stageInURL, localStageInURL });

                logger.debug("localStagInURL: " + localStageInURL);
            } else {
                //Here see if date range is used and not parameter list from the gui for multi job
                String strDateFrom = (String) request.getSession().getAttribute("dateFrom");
                String strDateTo = (String) request.getSession().getAttribute("dateTo");
                if (strDateFrom != null && strDateTo != null) {
                    String[] params = createSubjobs(strDateFrom, strDateTo, job.getArguments()[0], request,
                            gpsFiles);

                    //overwrite job args
                    job.setArguments(params);
                    String localStageInURL = gridAccess.getLocalGridFtpServer() + localJobInputDir;
                    job.setInTransfers(new String[] { localStageInURL });
                    gridStatus = (GridTransferStatus) request.getSession().getAttribute("gridStatus");
                } else {
                    if (urlArray != null && urlArray.length > 0) {
                        // Full URL
                        // e.g. "gsiftp://pbstore.ivec.org:2811//pbstore/au01/grid-auscope/Abdi.Jama@csiro.au-20091103_163322/"
                        //       +"rinex/" + filename
                        String toURL = gridAccess.getGridFtpServer() + File.separator + jobInputDir
                                + GridSubmitController.RINEX_DIR + File.separator;
                        gridStatus = urlCopy(urlArray, request, toURL);
                    }
                    String localStageInURL = gridAccess.getLocalGridFtpServer() + localJobInputDir;
                    job.setInTransfers(new String[] { stageInURL, localStageInURL });
                }

                //create the base directory for multi job, because this fails on stage out.
                success = createGridDir(request, jobOutputDir);

                //Add subJobStageIns
                Hashtable localSubJobDir = (Hashtable) request.getSession().getAttribute("localSubJobDir");
                if (localSubJobDir == null)
                    localSubJobDir = new Hashtable();
                job.setSubJobStageIn(localSubJobDir);
                request.getSession().removeAttribute("localSubJobDir");
                logger.debug("localSubJobDir size: " + localSubJobDir.size());

                //Add grigSubJobStageIns
                Hashtable gridSubJobStageInDir = (Hashtable) request.getSession()
                        .getAttribute("subJobStageInDir");
                if (gridSubJobStageInDir == null)
                    gridSubJobStageInDir = new Hashtable();
                job.setGridSubJobStageIn(gridSubJobStageInDir);
                request.getSession().removeAttribute("subJobStageInDir");
                logger.debug("gridSubJobStageInDir size: " + gridSubJobStageInDir.size());
            }

            String submitEPR = null;
            job.setEmailAddress(user);
            job.setOutputDir(jobOutputDir);
            job.setOutTransfers(new String[] { gridAccess.getGridFtpServer() + jobOutputDir });

            logger.info("Submitting job with name " + job.getName() + " to " + job.getSite());
            // ACTION!
            if (success && gridStatus.jobSubmissionStatus != JobSubmissionStatus.Failed)
                submitEPR = gridAccess.submitJob(job, credential);

            if (submitEPR == null) {
                success = false;
                gridStatus.jobSubmissionStatus = JobSubmissionStatus.Failed;
                gridStatus.currentStatusMsg = GridSubmitController.INTERNAL_ERROR;
            } else {
                logger.info("SUCCESS! EPR: " + submitEPR);
                String status = gridAccess.retrieveJobStatus(submitEPR, credential);
                job.setReference(submitEPR);
                job.setStatus(status);
                job.setSubmitDate(dateFmt);
                jobSupplementInfo(job);
                jobManager.saveJob(job);
                request.getSession().removeAttribute("jobInputDir");
                request.getSession().removeAttribute("localJobInputDir");

                //This means job submission to the grid done.
                gridStatus.jobSubmissionStatus = JobSubmissionStatus.Done;
                gridStatus.currentStatusMsg = GridSubmitController.TRANSFER_COMPLETE;
            }
        } else {
            success = false;
            logger.error(GridSubmitController.FILE_COPY_ERROR);
            gridStatus.currentStatusMsg = GridSubmitController.FILE_COPY_ERROR;
            gridStatus.jobSubmissionStatus = JobSubmissionStatus.Failed;
            mav.addObject("error", GridSubmitController.FILE_COPY_ERROR);
        }
    }
    // Save in session for status update request for this job.
    request.getSession().setAttribute("gridStatus", gridStatus);

    //reset the date range for next job
    request.getSession().removeAttribute("dateTo");
    request.getSession().removeAttribute("dateFrom");

    mav.addObject("success", success);

    return mav;
}

From source file:byps.http.HHttpServlet.java

protected HSession doCreateSession(final HttpServletRequest request) throws BException {
    // Create new JSESSIONID to support load balancing.
    // For newer clients, we do not rely on the JSESSIONID to identify the BYPS
    // session in incoming requests.
    // Otherwise two JSON connections in a browser window could not be
    // distinguished.
    // Older clients still need to reach their HSession by the JSESSIONID.
    HttpSession hsess = request.getSession(true);
    if (log.isDebugEnabled())
        log.debug("JSESSIONID=" + hsess.getId());

    // Assign a set of BYPS session objects to the app server's session.
    hsess.setAttribute(HConstants.HTTP_SESSION_BYPS_SESSIONS, new HHttpSessionObject());

    // Constrain the lifetime of the session to 10s. It is extended, if the
    // session gets authenticated.
    hsess.setMaxInactiveInterval(HConstants.MAX_INACTIVE_SECONDS_BEFORE_AUTHENTICATED);

    // Create new BYPS session
    final HTargetIdFactory targetIdFactory = getTargetIdFactory();
    final BTargetId targetId = targetIdFactory.createTargetId();
    final HSession sess = createSession(hsess, request.getRemoteUser());
    sess.setTargetId(targetId);//from www  .j a v a 2 s  . c  om
    if (log.isDebugEnabled())
        log.debug("targetId=" + targetId);

    // Add session to session map
    final BHashMap<String, HSession> sessions = HSessionListener.getAllSessions();
    final String bsessionId = targetId.toSessionId();
    sessions.put(bsessionId, sess);

    // Add BRemote for utility requests.
    addUtilityRequestsInterface(sess);
    return sess;
}

From source file:org.cerberus.servlet.crud.countryenvironment.CreateApplicationObject.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from ww w.ja v a  2s.c om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 * @throws CerberusException
 * @throws JSONException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String charset = request.getCharacterEncoding();

    response.setContentType("application/json");

    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    Map<String, String> fileData = new HashMap<String, String>();
    FileItem file = null;

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        List<FileItem> fields = upload.parseRequest(request);
        Iterator<FileItem> it = fields.iterator();
        if (!it.hasNext()) {
            return;
        }
        while (it.hasNext()) {
            FileItem fileItem = it.next();
            boolean isFormField = fileItem.isFormField();
            if (isFormField) {
                fileData.put(fileItem.getFieldName(), ParameterParserUtil
                        .parseStringParamAndDecode(fileItem.getString("UTF-8"), null, charset));
            } else {
                file = fileItem;
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }

    /**
     * Parsing and securing all required parameters.
     */
    // Parameter that are already controled by GUI (no need to decode) --> We SECURE them
    // Parameter that needs to be secured --> We SECURE+DECODE them
    String application = fileData.get("application");
    String object = fileData.get("object");
    String value = fileData.get("value");

    String usrcreated = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getRemoteUser(), "",
            charset);
    String datecreated = new Timestamp(new java.util.Date().getTime()).toString();
    String usrmodif = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getRemoteUser(), "",
            charset);
    String datemodif = new Timestamp(new java.util.Date().getTime()).toString();
    // Parameter that we cannot secure as we need the html --> We DECODE them

    /**
     * Checking all constrains before calling the services.
     */
    if (StringUtil.isNullOrEmpty(application)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "ApplicationObject")
                .replace("%OPERATION%", "Create").replace("%REASON%", "Application name is missing!"));
        ans.setResultMessage(msg);
    } else if (StringUtil.isNullOrEmpty(object)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "ApplicationObject")
                .replace("%OPERATION%", "Create").replace("%REASON%", "Object name is missing!"));
        ans.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        ApplicationContext appContext = WebApplicationContextUtils
                .getWebApplicationContext(this.getServletContext());
        IApplicationObjectService applicationobjectService = appContext
                .getBean(IApplicationObjectService.class);
        IFactoryApplicationObject factoryApplicationobject = appContext
                .getBean(IFactoryApplicationObject.class);
        String fileName = "";
        if (file != null) {
            fileName = file.getName();
        }

        ApplicationObject applicationData = factoryApplicationobject.create(-1, application, object, value,
                fileName, usrcreated, datecreated, usrmodif, datemodif);
        ans = applicationobjectService.create(applicationData);

        if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
            /**
             * Object created. Adding Log entry.
             */
            ILogEventService logEventService = appContext.getBean(LogEventService.class);
            logEventService.createPrivateCalls("/CreateApplicationObject", "CREATE",
                    "Create Application Object: ['" + application + "','" + object + "']", request);

            if (file != null) {
                AnswerItem an = applicationobjectService.readByKey(application, object);
                if (an.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && an.getItem() != null) {
                    applicationData = (ApplicationObject) an.getItem();
                    ans = applicationobjectService.uploadFile(applicationData.getID(), file);
                    if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                    }
                }
            }
        }
    }

    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", ans.getResultMessage().getDescription());

    response.getWriter().print(jsonResponse);
    response.getWriter().flush();

}

From source file:org.cerberus.servlet.crud.countryenvironment.UpdateApplicationObject.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  w w  .  java2 s  .  c  o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    ApplicationContext appContext = WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext());
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    String charset = request.getCharacterEncoding();

    response.setContentType("application/json");

    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    Map<String, String> fileData = new HashMap<String, String>();
    FileItem file = null;

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        List<FileItem> fields = upload.parseRequest(request);
        Iterator<FileItem> it = fields.iterator();
        if (!it.hasNext()) {
            return;
        }
        while (it.hasNext()) {
            FileItem fileItem = it.next();
            boolean isFormField = fileItem.isFormField();
            if (isFormField) {
                fileData.put(fileItem.getFieldName(), ParameterParserUtil
                        .parseStringParamAndDecode(fileItem.getString("UTF-8"), null, charset));
            } else {
                file = fileItem;
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }

    /**
     * Parsing and securing all required parameters.
     */
    // Parameter that are already controled by GUI (no need to decode) --> We SECURE them
    // Parameter that needs to be secured --> We SECURE+DECODE them
    String application = fileData.get("application");
    String object = fileData.get("object");
    String value = fileData.get("value");

    String usrmodif = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getRemoteUser(), "",
            charset);
    String datemodif = new Timestamp(new java.util.Date().getTime()).toString();
    // Parameter that we cannot secure as we need the html --> We DECODE them

    // Getting list of application from JSON Call

    // Prepare the final answer.
    MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);
    Answer finalAnswer = new Answer(msg1);

    /**
     * Checking all constrains before calling the services.
     */
    if (StringUtil.isNullOrEmpty(application)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(
                msg.getDescription().replace("%ITEM%", "ApplicationObject").replace("%OPERATION%", "Update")
                        .replace("%REASON%", "Application name (applicationobject) is missing."));
        ans.setResultMessage(msg);
    } else if (StringUtil.isNullOrEmpty(object)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(
                msg.getDescription().replace("%ITEM%", "ApplicationObject").replace("%OPERATION%", "Update")
                        .replace("%REASON%", "Object name (applicationobject) is missing."));
        ans.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        IApplicationObjectService applicationObjectService = appContext
                .getBean(IApplicationObjectService.class);

        AnswerItem resp = applicationObjectService.readByKey(application, object);
        if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) {
            /**
             * Object could not be found. We stop here and report the error.
             */
            finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) resp);

        } else {
            /**
             * The service was able to perform the query and confirm the
             * object exist, then we can update it.
             */
            ApplicationObject applicationData = (ApplicationObject) resp.getItem();

            String fileName = applicationData.getScreenShotFileName();
            if (file != null) {
                ans = applicationObjectService.uploadFile(applicationData.getID(), file);
                if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                    fileName = file.getName();
                }
            }

            applicationData.setValue(value);
            applicationData.setScreenShotFileName(fileName);
            applicationData.setUsrModif(usrmodif);
            applicationData.setDateModif(datemodif);
            ans = applicationObjectService.update(applicationData);
            finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);

            if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                /**
                 * Update was succesfull. Adding Log entry.
                 */
                ILogEventService logEventService = appContext.getBean(LogEventService.class);
                logEventService.createPrivateCalls("/UpdateApplication", "UPDATE",
                        "Updated Application : ['" + application + "']", request);
            }
            finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
        }
    }

    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", finalAnswer.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", finalAnswer.getResultMessage().getDescription());

    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}

From source file:org.apache.nifi.processors.standard.HandleHttpRequest.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    try {/*ww  w . j a  v a2 s  . c  o  m*/
        if (!initialized.get()) {
            initializeServer(context);
        }
    } catch (Exception e) {
        context.yield();
        throw new ProcessException("Failed to initialize the server", e);
    }

    final HttpRequestContainer container = containerQueue.poll();
    if (container == null) {
        return;
    }

    final long start = System.nanoTime();
    final HttpServletRequest request = container.getRequest();
    FlowFile flowFile = session.create();
    try {
        flowFile = session.importFrom(request.getInputStream(), flowFile);
    } catch (final IOException e) {
        getLogger().error("Failed to receive content from HTTP Request from {} due to {}",
                new Object[] { request.getRemoteAddr(), e });
        session.remove(flowFile);
        return;
    }

    final String charset = request.getCharacterEncoding() == null
            ? context.getProperty(URL_CHARACTER_SET).getValue()
            : request.getCharacterEncoding();

    final String contextIdentifier = UUID.randomUUID().toString();
    final Map<String, String> attributes = new HashMap<>();
    try {
        putAttribute(attributes, HTTPUtils.HTTP_CONTEXT_ID, contextIdentifier);
        putAttribute(attributes, "mime.type", request.getContentType());
        putAttribute(attributes, "http.servlet.path", request.getServletPath());
        putAttribute(attributes, "http.context.path", request.getContextPath());
        putAttribute(attributes, "http.method", request.getMethod());
        putAttribute(attributes, "http.local.addr", request.getLocalAddr());
        putAttribute(attributes, HTTPUtils.HTTP_LOCAL_NAME, request.getLocalName());
        final String queryString = request.getQueryString();
        if (queryString != null) {
            putAttribute(attributes, "http.query.string", URLDecoder.decode(queryString, charset));
        }
        putAttribute(attributes, HTTPUtils.HTTP_REMOTE_HOST, request.getRemoteHost());
        putAttribute(attributes, "http.remote.addr", request.getRemoteAddr());
        putAttribute(attributes, "http.remote.user", request.getRemoteUser());
        putAttribute(attributes, HTTPUtils.HTTP_REQUEST_URI, request.getRequestURI());
        putAttribute(attributes, "http.request.url", request.getRequestURL().toString());
        putAttribute(attributes, "http.auth.type", request.getAuthType());

        putAttribute(attributes, "http.requested.session.id", request.getRequestedSessionId());
        final DispatcherType dispatcherType = request.getDispatcherType();
        if (dispatcherType != null) {
            putAttribute(attributes, "http.dispatcher.type", dispatcherType.name());
        }
        putAttribute(attributes, "http.character.encoding", request.getCharacterEncoding());
        putAttribute(attributes, "http.locale", request.getLocale());
        putAttribute(attributes, "http.server.name", request.getServerName());
        putAttribute(attributes, HTTPUtils.HTTP_PORT, request.getServerPort());

        final Enumeration<String> paramEnumeration = request.getParameterNames();
        while (paramEnumeration.hasMoreElements()) {
            final String paramName = paramEnumeration.nextElement();
            final String value = request.getParameter(paramName);
            attributes.put("http.param." + paramName, value);
        }

        final Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (final Cookie cookie : cookies) {
                final String name = cookie.getName();
                final String cookiePrefix = "http.cookie." + name + ".";
                attributes.put(cookiePrefix + "value", cookie.getValue());
                attributes.put(cookiePrefix + "domain", cookie.getDomain());
                attributes.put(cookiePrefix + "path", cookie.getPath());
                attributes.put(cookiePrefix + "max.age", String.valueOf(cookie.getMaxAge()));
                attributes.put(cookiePrefix + "version", String.valueOf(cookie.getVersion()));
                attributes.put(cookiePrefix + "secure", String.valueOf(cookie.getSecure()));
            }
        }

        if (queryString != null) {
            final String[] params = URL_QUERY_PARAM_DELIMITER.split(queryString);
            for (final String keyValueString : params) {
                final int indexOf = keyValueString.indexOf("=");
                if (indexOf < 0) {
                    // no =, then it's just a key with no value
                    attributes.put("http.query.param." + URLDecoder.decode(keyValueString, charset), "");
                } else {
                    final String key = keyValueString.substring(0, indexOf);
                    final String value;

                    if (indexOf == keyValueString.length() - 1) {
                        value = "";
                    } else {
                        value = keyValueString.substring(indexOf + 1);
                    }

                    attributes.put("http.query.param." + URLDecoder.decode(key, charset),
                            URLDecoder.decode(value, charset));
                }
            }
        }
    } catch (final UnsupportedEncodingException uee) {
        throw new ProcessException("Invalid character encoding", uee); // won't happen because charset has been validated
    }

    final Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        final String headerName = headerNames.nextElement();
        final String headerValue = request.getHeader(headerName);
        putAttribute(attributes, "http.headers." + headerName, headerValue);
    }

    final Principal principal = request.getUserPrincipal();
    if (principal != null) {
        putAttribute(attributes, "http.principal.name", principal.getName());
    }

    final X509Certificate certs[] = (X509Certificate[]) request
            .getAttribute("javax.servlet.request.X509Certificate");
    final String subjectDn;
    if (certs != null && certs.length > 0) {
        final X509Certificate cert = certs[0];
        subjectDn = cert.getSubjectDN().getName();
        final String issuerDn = cert.getIssuerDN().getName();

        putAttribute(attributes, HTTPUtils.HTTP_SSL_CERT, subjectDn);
        putAttribute(attributes, "http.issuer.dn", issuerDn);
    } else {
        subjectDn = null;
    }

    flowFile = session.putAllAttributes(flowFile, attributes);

    final HttpContextMap contextMap = context.getProperty(HTTP_CONTEXT_MAP)
            .asControllerService(HttpContextMap.class);
    final boolean registered = contextMap.register(contextIdentifier, request, container.getResponse(),
            container.getContext());

    if (!registered) {
        getLogger().warn(
                "Received request from {} but could not process it because too many requests are already outstanding; responding with SERVICE_UNAVAILABLE",
                new Object[] { request.getRemoteAddr() });

        try {
            container.getResponse().setStatus(Status.SERVICE_UNAVAILABLE.getStatusCode());
            container.getResponse().flushBuffer();
            container.getContext().complete();
        } catch (final Exception e) {
            getLogger().warn("Failed to respond with SERVICE_UNAVAILABLE message to {} due to {}",
                    new Object[] { request.getRemoteAddr(), e });
        }

        session.remove(flowFile);
        return;
    }

    final long receiveMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
    session.getProvenanceReporter().receive(flowFile, HTTPUtils.getURI(attributes),
            "Received from " + request.getRemoteAddr() + (subjectDn == null ? "" : " with DN=" + subjectDn),
            receiveMillis);
    session.transfer(flowFile, REL_SUCCESS);
    getLogger().info("Transferring {} to 'success'; received from {}",
            new Object[] { flowFile, request.getRemoteAddr() });
}

From source file:org.eclipse.lyo.oslc.am.resource.ResourceService.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    boolean isFileUpload = ServletFileUpload.isMultipartContent(request);
    String contentType = request.getContentType();

    if (!isFileUpload && (RioStore.rdfFormatFromContentType(contentType) == null)) {
        throw new RioServiceException(IConstants.SC_UNSUPPORTED_MEDIA_TYPE);
    }/*from  www.j  a  va2s  .c o m*/

    InputStream content = request.getInputStream();

    if (isFileUpload) {
        // being uploaded from a web page
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            @SuppressWarnings("unchecked")
            List<FileItem> items = upload.parseRequest(request);

            // find the first (and only) file resource in the post
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (item.isFormField()) {
                    // this is a form field, maybe we can accept a title or descr?
                } else {
                    content = item.getInputStream();
                    contentType = item.getContentType();
                }
            }

        } catch (Exception e) {
            throw new RioServiceException(e);
        }
    }

    RioStore store = this.getStore();
    if (RioStore.rdfFormatFromContentType(contentType) != null) {
        try {
            String resUri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
            Resource resource = new Resource(resUri);
            List<RioStatement> statements = store.parse(resUri, content, contentType);
            resource.addStatements(statements);
            String userUri = getUserUri(request.getRemoteUser());

            // if it parsed, then add it to the store.
            store.update(resource, userUri);

            // now get it back, to find 
            OslcResource returnedResource = store.getOslcResource(resource.getUri());
            Date created = returnedResource.getCreated();
            String eTag = returnedResource.getETag();

            response.setStatus(IConstants.SC_CREATED);
            response.setHeader(IConstants.HDR_LOCATION, resource.getUri());
            response.setHeader(IConstants.HDR_LAST_MODIFIED, StringUtils.rfc2822(created));
            response.setHeader(IConstants.HDR_ETAG, eTag);

        } catch (RioServerException e) {
            throw new RioServiceException(IConstants.SC_BAD, e);
        }
    } else if (IAmConstants.CT_APP_X_VND_MSPPT.equals(contentType) || isFileUpload) {
        try {

            ByteArrayInputStream bais = isToBais(content);

            String uri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
            Resource resource = new Resource(uri);
            resource.addRdfType(IAmConstants.OSLC_AM_TYPE_RESOURCE);
            resource.addRdfType(IAmConstants.RIO_AM_PPT_DECK);
            String id = resource.getIdentifier();
            String deckTitle = "PPT Deck " + id;
            resource.setTitle(deckTitle);
            resource.setDescription("A Power Point Deck");
            String sourceUri = getBaseUrl() + '/' + IAmConstants.SERVICE_SOURCE + '/' + id;
            resource.setSource(sourceUri);
            resource.setSourceContentType(contentType);
            String userUri = getUserUri(request.getRemoteUser());

            store.storeBinaryResource(bais, id);
            bais.reset();

            SlideShow ppt = new SlideShow(bais);
            Dimension pgsize = ppt.getPageSize();

            Slide[] slide = ppt.getSlides();
            for (int i = 0; i < slide.length; i++) {
                String slideTitle = extractTitle(slide[i]);
                String slideUri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
                Resource slideResource = new Resource(slideUri);
                slideResource.addRdfType(IAmConstants.OSLC_AM_TYPE_RESOURCE);
                slideResource.addRdfType(IAmConstants.RIO_AM_PPT_SLIDE);
                String slideId = slideResource.getIdentifier();
                slideResource.setTitle(slideTitle);
                sourceUri = getBaseUrl() + '/' + IAmConstants.SERVICE_SOURCE + '/' + slideId;
                slideResource.setSource(sourceUri);
                slideResource.setSourceContentType(IConstants.CT_IMAGE_PNG);
                store.update(slideResource, userUri);

                BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = img.createGraphics();
                graphics.setPaint(Color.white);
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
                slide[i].draw(graphics);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                javax.imageio.ImageIO.write(img, "png", out);
                ByteArrayInputStream is = new ByteArrayInputStream(out.toByteArray());
                store.storeBinaryResource(is, slideId);
                out.close();
                is.close();
                try {
                    RioValue v = new RioValue(RioValueType.URI, slideResource.getUri());
                    resource.appendToSeq(IConstants.RIO_NAMESPACE + "slides", v);
                } catch (UnrecognizedValueTypeException e) {
                    // log this?  don't want to throw away everything, since this should never happen
                }
            }

            store.update(resource, userUri);

            // now get it back, to find eTag and creator stuff
            OslcResource returnedResource = store.getOslcResource(resource.getUri());
            Date created = returnedResource.getCreated();
            String eTag = returnedResource.getETag();

            response.setStatus(IConstants.SC_CREATED);
            response.setHeader(IConstants.HDR_LOCATION, resource.getUri());
            response.setHeader(IConstants.HDR_LAST_MODIFIED, StringUtils.rfc2822(created));
            response.setHeader(IConstants.HDR_ETAG, eTag);

        } catch (RioServerException e) {
            throw new RioServiceException(IConstants.SC_BAD, e);
        }

    } else {
        // must be a binary or unknown format, treat as black box
        // normally a service provider will understand this and parse it appropriately
        // however this server will accept any blank box resource

        try {
            String uri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
            Resource resource = new Resource(uri);
            String id = resource.getIdentifier();
            resource.setTitle("Resource " + id);
            resource.setDescription("A binary resource");
            String sourceUri = getBaseUrl() + IAmConstants.SERVICE_SOURCE + '/' + id;
            resource.setSource(sourceUri);
            resource.setSourceContentType(contentType);
            String userUri = getUserUri(request.getRemoteUser());
            store.update(resource, userUri);

            store.storeBinaryResource(content, id);

            // now get it back, to find eTag and creator stuff
            OslcResource returnedResource = store.getOslcResource(resource.getUri());
            Date created = returnedResource.getCreated();
            String eTag = returnedResource.getETag();

            response.setStatus(IConstants.SC_CREATED);
            response.setHeader(IConstants.HDR_LOCATION, resource.getUri());
            response.setHeader(IConstants.HDR_LAST_MODIFIED, StringUtils.rfc2822(created));
            response.setHeader(IConstants.HDR_ETAG, eTag);

        } catch (RioServerException e) {
            throw new RioServiceException(IConstants.SC_BAD, e);
        }
    }
}