Example usage for javax.servlet.http HttpSession getId

List of usage examples for javax.servlet.http HttpSession getId

Introduction

In this page you can find the example usage for javax.servlet.http HttpSession getId.

Prototype

public String getId();

Source Link

Document

Returns a string containing the unique identifier assigned to this session.

Usage

From source file:airport.web.controller.ServicesController.java

@JsonIgnore
@RequestMapping(value = "/service/dispatcher/delflight")
public boolean serviceDispatcherDelFlights(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(name = "runawayId") int runawayId) {
    HttpSession httpSession = request.getSession();
    User user = (User) httpSession.getAttribute("user");

    if (serviceUsers.checkUserOnline(user)) {
        String numberFlight = request.getParameter("numberFlight");

        Flight flight = new Flight();
        flight.setFlightNumber(numberFlight);

        if (serviceDispatcher.getFlightState(numberFlight).equals("")) {
            serviceStatistics.incAmountTakenOffPlane(user);
        } else {//from  www  .j a v  a  2s  . c o m
            serviceStatistics.incAmoubtLendedPlane(user);
        }

        boolean result = serviceDispatcher.delFlight(flight, runawayId);

        if (LOG.isInfoEnabled()) {
            LOG.info("user del flight. Session id : " + httpSession.getId() + ". User : " + user
                    + ". URL : /service/dispatcher/delflight");
        }

        return result;
    } else {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        if (LOG.isInfoEnabled()) {
            LOG.info("the user isn't authorized. Session id : " + httpSession.getId()
                    + ". URL : /service/dispatcher/delflight");
        }

        return false;
    }
}

From source file:gov.nih.nci.security.upt.actions.CommonDBAction.java

public String search(BaseDBForm baseDBForm) throws Exception {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpSession session = request.getSession();

    if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) {
        if (logDB.isDebugEnabled())
            logDB.debug("||" + baseDBForm.getFormName()
                    + "|search|Failure|No Session or User Object Forwarding to the Login Page||");
        return ForwardConstants.LOGIN_PAGE;
    }//from  ww  w. jav  a 2  s .c  o  m
    UserInfoHelper.setUserInfo(((LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId(),
            session.getId());
    try {
        UserProvisioningManager userProvisioningManager = (UserProvisioningManager) (request.getSession())
                .getAttribute(DisplayConstants.USER_PROVISIONING_MANAGER);
        baseDBForm.setRequest(request);
        SearchResult searchResult = baseDBForm.searchObjects(userProvisioningManager);
        if (searchResult.getSearchResultObjects() == null || searchResult.getSearchResultObjects().isEmpty()) {
            addActionError("The search criteria returned zero results");
            if (logDB.isDebugEnabled())
                logDB.debug(session.getId() + "|"
                        + ((LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId() + "|"
                        + baseDBForm.getFormName() + "|search|Failure|No Records found for "
                        + baseDBForm.getFormName() + " object|" + "|");
            baseDBForm.resetForm();
            return ForwardConstants.SEARCH_FAILURE;
        }
        if (searchResult.getSearchResultMessage() != null
                && !(searchResult.getSearchResultMessage().trim().equalsIgnoreCase(""))) {
            addActionMessage(searchResult.getSearchResultMessage());
        }

        session.setAttribute(DisplayConstants.SEARCH_RESULT, null);
        session.setAttribute(DisplayConstants.CREATE_WORKFLOW, null);
        session.setAttribute(DisplayConstants.ORIGINAL_SEARCH_RESULT, null);
        session.setAttribute(DisplayConstants.CURRENT_FORM, null);
        if (session.getAttribute(DisplayConstants.SEARCH_RESULT) != null) {
            String str = (String) session.getAttribute(DisplayConstants.CREATE_WORKFLOW);
            if (session.getAttribute(DisplayConstants.CREATE_WORKFLOW) == null) {
                if (session.getAttribute(DisplayConstants.ORIGINAL_SEARCH_RESULT) == null) {
                    session.setAttribute(DisplayConstants.ORIGINAL_SEARCH_RESULT,
                            session.getAttribute(DisplayConstants.SEARCH_RESULT));
                }
            }
        }
        session.setAttribute(DisplayConstants.SEARCH_RESULT, searchResult);
    } catch (CSException cse) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
        if (logDB.isDebugEnabled())
            logDB.debug(session.getId() + "|"
                    + ((LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId() + "|"
                    + baseDBForm.getFormName() + "|search|Failure|Error Searching the "
                    + baseDBForm.getFormName() + " object|" + "|" + cse.getMessage());
    }
    session.setAttribute(DisplayConstants.CURRENT_FORM, baseDBForm);
    if (logDB.isDebugEnabled())
        logDB.debug(session.getId() + "|"
                + ((LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId() + "|"
                + baseDBForm.getFormName() + "|search|Success|Success in searching " + baseDBForm.getFormName()
                + " object|" + "|");
    return ForwardConstants.SEARCH_SUCCESS;
}

From source file:fr.paris.lutece.plugins.directory.service.upload.DirectoryAsynchronousUploadHandler.java

/**
 * Performs an upload action.//from   w  w w  .  ja v a 2 s .c  om
 *
 * @param request the HTTP request
 * @param strUploadAction the name of the upload action
 * @param map the map of <idEntry, RecordFields>
 * @param record the record
 * @param plugin the plugin
 * @throws DirectoryErrorException exception if there is an error
 */
public void doUploadAction(HttpServletRequest request, String strUploadAction,
        Map<String, List<RecordField>> map, Record record, Plugin plugin) throws DirectoryErrorException {
    // Get the name of the upload field
    String strIdEntry = (strUploadAction.startsWith(UPLOAD_SUBMIT_PREFIX)
            ? strUploadAction.substring(UPLOAD_SUBMIT_PREFIX.length())
            : strUploadAction.substring(UPLOAD_DELETE_PREFIX.length()));

    String strFieldName = buildFieldName(strIdEntry);

    if (strUploadAction.startsWith(UPLOAD_SUBMIT_PREFIX)) {
        // A file was submitted
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        FileItem fileItem = multipartRequest.getFile(strFieldName);

        if (fileItem != null) {
            // Check if the file can be uploaded first
            List<FileItem> listFileItemsToUpload = new ArrayList<FileItem>();
            listFileItemsToUpload.add(fileItem);

            HttpSession session = request.getSession();
            // The following method call throws a DirectoryErrorException if the file cannot be uploaded
            canUploadFiles(strFieldName, getFileItems(strIdEntry, session.getId()), listFileItemsToUpload,
                    request.getLocale());

            // Add the file to the map of <idEntry, RecordFields>
            IEntry entry = EntryHome.findByPrimaryKey(DirectoryUtils.convertStringToInt(strIdEntry), plugin);

            if (entry != null) {
                RecordField recordField = new RecordField();
                recordField.setRecord(record);
                recordField.setEntry(entry);

                String strFilename = FileUploadService.getFileNameOnly(fileItem);

                if ((fileItem.get() != null) && (fileItem.getSize() < Integer.MAX_VALUE)) {
                    if (entry instanceof EntryTypeDownloadUrl) {
                        recordField.setFileName(strFilename);
                        recordField.setFileExtension(FileSystemUtil.getMIMEType(strFilename));
                    } else {
                        PhysicalFile physicalFile = new PhysicalFile();
                        physicalFile.setValue(fileItem.get());

                        File file = new File();
                        file.setPhysicalFile(physicalFile);
                        file.setTitle(strFilename);
                        file.setSize((int) fileItem.getSize());
                        file.setMimeType(FileSystemUtil.getMIMEType(strFilename));

                        recordField.setFile(file);
                    }
                }

                List<RecordField> listRecordFields = map.get(strIdEntry);

                if (listRecordFields == null) {
                    listRecordFields = new ArrayList<RecordField>();
                }

                listRecordFields.add(recordField);
                map.put(strIdEntry, listRecordFields);
            }

            // Add to the asynchronous uploaded files map
            addFileItemToUploadedFile(fileItem, strIdEntry, request.getSession());
        }
    } else if (strUploadAction.startsWith(UPLOAD_DELETE_PREFIX)) {
        HttpSession session = request.getSession(false);

        if (session != null) {
            // Some previously uploaded files were deleted
            // Build the prefix of the associated checkboxes
            String strPrefix = UPLOAD_CHECKBOX_PREFIX + strIdEntry;

            // Look for the checkboxes in the request
            Enumeration<String> enumParamNames = request.getParameterNames();
            List<Integer> listIndexes = new ArrayList<Integer>();

            while (enumParamNames.hasMoreElements()) {
                String strParamName = enumParamNames.nextElement();

                if (strParamName.startsWith(strPrefix)) {
                    // Get the index from the name of the checkbox
                    listIndexes.add(Integer.parseInt(strParamName.substring(strPrefix.length())));
                }
            }

            Collections.sort(listIndexes);
            Collections.reverse(listIndexes);

            for (int nIndex : listIndexes) {
                // Remove from the map of <idEntry, RecordField>
                List<RecordField> listRecordFields = map.get(strIdEntry);

                if (listRecordFields != null) {
                    listRecordFields.remove(nIndex);
                }

                // Remove from the asynchronous uploaded files map
                removeFileItem(strIdEntry, session.getId(), nIndex);
            }
        }
    }
}

From source file:gov.nih.nci.security.upt.actions.CommonDoubleAssociationAction.java

public String unlock(UserForm userForm) throws Exception {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpSession session = request.getSession();

    if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) {
        if (logDoubleAssociation.isDebugEnabled())
            logDoubleAssociation.debug("||" + userForm.getFormName()
                    + "|unlock|Failure|No Session or User Object Forwarding to the Login Page||");
        return ForwardConstants.LOGIN_PAGE;
    }//from  w  ww  . j  a  v a2 s .c o  m
    String userLoginName = userForm.getUserLoginName();
    String loginId = ((LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId();
    UserInfoHelper.setUserInfo(loginId, session.getId());
    try {
        UserProvisioningManager userProvisioningManager = (UserProvisioningManager) (request.getSession())
                .getAttribute(DisplayConstants.USER_PROVISIONING_MANAGER);
        userForm.setRequest(request);

        LockoutManager.getInstance().unLockUser(userLoginName);
        userForm.buildDBObject(userProvisioningManager);
        addActionMessage("UnLock Successful");
    } catch (CSException cse) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
        if (logDoubleAssociation.isDebugEnabled())
            logDoubleAssociation.debug(session.getId() + "|" + userLoginName + "|" + userForm.getFormName()
                    + "|unlock|Failure|Error unlock the " + userForm.getFormName() + " object|" + "|"
                    + cse.getMessage());
    }
    session.setAttribute(DisplayConstants.CURRENT_FORM, userForm);

    if (logDoubleAssociation.isDebugEnabled())
        logDoubleAssociation.debug(session.getId() + "|" + userLoginName + "|" + userForm.getFormName()
                + "|unlock|Success|Updating existing " + userForm.getFormName() + " object|" + "|");
    return ForwardConstants.UNLOCK_SUCCESS;
}

From source file:de.innovationgate.wgpublisher.WGAUsageStatistics.java

public void addRequestStatistic(HttpServletRequest req, HttpSession sess, WGDatabase db,
        TMLUserProfile profile) {//  w  w w  .j  a va 2s . c  o  m
    try {

        RequestStatistic requestStatistic = new RequestStatistic();
        requestStatistic.setDatabase(db.getDbReference());
        requestStatistic.setLastAccess(new Date());
        requestStatistic.setTask(db.getSessionContext().getTask());
        requestStatistic.setUser(db.getSessionContext().getUser());
        requestStatistic.setSessionId(sess.getId());
        requestStatistic.setSessionCreated(new Date(sess.getCreationTime()));
        requestStatistic.setNewSession(sess.isNew());
        requestStatistic.setRemoteHost(req.getRemoteAddr());
        String userAgent = req.getHeader("USER-AGENT");
        if (userAgent != null) {
            requestStatistic.setUserAgent(userAgent);
        } else {
            requestStatistic.setUserAgent("(unknown)");
        }

        if (profile != null) {
            requestStatistic.setProfile(profile.getprofile().getName());
        } else {
            requestStatistic.setProfile("(none)");
        }

        try {
            _requestStatisticQueue.add(requestStatistic);
        } catch (IllegalStateException e) {
            if (!_warnedAboutFullQueue) {
                _wgaCore.getLog().warn(
                        "Session statistics queue is temporarily full. Currently displayed statistics may not be accurate.");
                _warnedAboutFullQueue = true;
            }
        }

    } catch (Exception e) {
        _wgaCore.log.error("Unable to update usage statistics.", e);
    }
}

From source file:org.alfresco.repo.webdav.WebDAVLockServiceImpl.java

@Override
@SuppressWarnings("unchecked")
public void sessionDestroyed() {
    HttpSession session = currentSession.get();

    if (session == null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Couldn't find current session.");
        }// w  ww.  j a v  a  2  s .  c om
        return;
    }

    // look for locked documents list in http session
    final List<Pair<String, NodeRef>> lockedResources = (List<Pair<String, NodeRef>>) session
            .getAttribute(LOCKED_RESOURCES);

    if (lockedResources != null && lockedResources.size() > 0) {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Found " + lockedResources.size() + " locked resources for session: " + session.getId());
        }

        for (Pair<String, NodeRef> lockedResource : lockedResources) {
            String runAsUser = lockedResource.getFirst();
            final NodeRef nodeRef = lockedResource.getSecond();

            // there are some document that should be forcibly unlocked
            AuthenticationUtil.runAs(new RunAsWork<Void>() {
                @Override
                public Void doWork() throws Exception {
                    return transactionService.getRetryingTransactionHelper()
                            .doInTransaction(new RetryingTransactionCallback<Void>() {
                                @Override
                                public Void execute() throws Throwable {
                                    // check whether this document still exists in repo
                                    if (nodeService.exists(nodeRef)) {
                                        if (logger.isDebugEnabled()) {
                                            logger.debug("Trying to release lock for: " + nodeRef);
                                        }

                                        // check the lock status of document
                                        LockStatus lockStatus = lockService.getLockStatus(nodeRef);

                                        // check if document was checked out
                                        boolean hasWorkingCopy = checkOutCheckInService
                                                .getWorkingCopy(nodeRef) != null;
                                        boolean isWorkingCopy = nodeService.hasAspect(nodeRef,
                                                ContentModel.ASPECT_WORKING_COPY);

                                        // forcibly unlock document if it is still locked and not checked out
                                        if ((lockStatus.equals(LockStatus.LOCKED)
                                                || lockStatus.equals(LockStatus.LOCK_OWNER)) && !hasWorkingCopy
                                                && !isWorkingCopy) {
                                            try {
                                                // try to unlock it
                                                lockService.unlock(nodeRef);

                                                if (logger.isDebugEnabled()) {
                                                    logger.debug(
                                                            "Lock was successfully released for: " + nodeRef);
                                                }
                                            } catch (Exception e) {
                                                if (logger.isDebugEnabled()) {
                                                    logger.debug("Unable to unlock " + nodeRef + " cause: "
                                                            + e.getMessage());
                                                }
                                            }
                                        } else {
                                            // document is not locked or is checked out
                                            if (logger.isDebugEnabled()) {
                                                logger.debug("Skip lock releasing for: " + nodeRef
                                                        + " as it is not locked or is checked out");
                                            }
                                        }
                                    } else {
                                        // document no longer exists in repo 
                                        if (logger.isDebugEnabled()) {
                                            logger.debug(
                                                    "Skip lock releasing for an unexisting node: " + nodeRef);
                                        }
                                    }
                                    return null;
                                }
                            }, transactionService.isReadOnly());
                }
            }, runAsUser == null ? AuthenticationUtil.getSystemUserName() : runAsUser);
        }
    } else {
        // there are no documents with unexpected lock left on it
        if (logger.isDebugEnabled()) {
            logger.debug("No locked resources were found for session: " + session.getId());
        }
    }
}

From source file:de.innovationgate.wgpublisher.webtml.init.WebTMLEnvironmentBuilder.java

private TMLAction callAction(TMLContext context, TMLActionLink actionLink, boolean ajax) throws WGException {

    // Look for correct sequence number to prevent action execution by page reload. Fail silently
    HttpSession session = context.gethttpsession();
    if (!context.isCurrentSequenceNumber(actionLink, session, ajax)) {
        return null;
    }/*from   w  ww  .ja  v a2 s.c  om*/

    // Look if action was rendered in this session - if not do not execute, 
    if (!actionLink.getSessionID().equals(session.getId())) {
        if (ajax) {
            context.getrequest().setAttribute(WGACore.ATTRIB_AJAX_FAILURE, true);
        }
        throw new TMLInvalidActionLinkException("The action was registered for a different session ID");
    }

    // Try to retrieve action context - defaults to context of this tag
    TMLContext actionContext = context;
    if (actionLink.getContextPath() != null) {
        actionContext = actionContext.context(actionLink.getContextPath(), false);

        // Could not retrieve context. Too dangerous to execute action under the wrong context.
        if (actionContext == null) {
            throw new TMLActionException("Unable to retrieve action context: " + actionLink.getContextPath());
        }
    } else if (actionLink.getDbKey() != null) {
        //B00004602

        // no context path - switch to dummy context of the given db  
        actionContext = context.context("db:" + actionLink.getDbKey(), false);

        // Could not retrieve dummy context. Too dangerous to execute action under the wrong context.
        if (actionContext == null) {
            throw new TMLActionException("Unable to retrieve action context: db:" + actionLink.getDbKey());
        }
    }

    // Temporarily set portlet namespace, WebTML scope
    TMLOptionPreserver preserver = new TMLOptionPreserver(context.getDesignContext());
    preserver.preserve(Base.OPTION_PORTLET_NAMESPACE, actionLink.getPortletKey());
    preserver.preserve(Base.OPTION_WEBTML_SCOPE, actionLink.getWebtmlScope());

    try {

        // Additional objects for action: portletEvent
        Map<String, Object> objects = new HashMap<String, Object>();
        PortletEvent ev = context.fetchRequestPortletEvent();
        if (ev != null) {
            objects.put("portletEvent", ev);
        }

        // Execute default action
        if (actionLink.isDefaultAction()) {
            TMLAction action = new TMLAction(actionLink.getDefaultAction());
            Object result = actionContext.callDefaultAction(action, actionLink, objects);
            if (result == null || !result.equals(Boolean.FALSE)) {
                performPostActionOperations(action, actionLink, context, actionContext, result);
            }
            return action;
        }

        // Execute custom action
        else {
            TMLAction tmlAction = (TMLAction) context.getActionRegistration()
                    .get(actionLink.getActionKeyInteger());
            if (tmlAction == null) {
                throw new TMLActionException("Could not find action for key " + actionLink.getActionKey());
            }

            // Execute, enforce portletmode and context on success if given
            try {
                ExpressionResult expressionResult = actionContext.callCustomAction(tmlAction, actionLink,
                        objects);
                if (expressionResult.getResult() == null || expressionResult.getResult() instanceof String
                        || !expressionResult.isFalse()) {
                    performPostActionOperations(tmlAction, actionLink, context, actionContext,
                            expressionResult.getResult());
                }
            } catch (WGExpressionException e) {
                context.addwarning(WGUtils.encodeHTML(
                        e.getMessage() + (e.getExpression() != null ? "\nExpression line: " + e.getExpression()
                                : "\nExpression:\n" + tmlAction.getCode())),
                        false);
                _core.getLog().error("Error executing " + tmlAction.getDescription() + " : " + e.getMessage(),
                        e);
            }
            return tmlAction;
        }

    } finally {
        preserver.restore();
    }

}

From source file:com.cws.us.pws.controllers.CommonController.java

@RequestMapping(value = "/contact", method = RequestMethod.POST)
public final ModelAndView sendMessage(@ModelAttribute("message") final EmailMessage message,
        final BindingResult bindResult) {
    final String methodName = CommonController.CNAME
            + "#sendMessage(@ModelAttribute(\"message\") final EmailMessage message, final BindingResult bindResult)";

    if (DEBUG) {//from  w  w w.j  a  v a  2 s  .  c  om
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("EmailMessage: {}", message);
        DEBUGGER.debug("BindingResult: {}", bindResult);
    }

    ModelAndView mView = new ModelAndView();

    final ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    final HttpServletRequest hRequest = requestAttributes.getRequest();
    final HttpSession hSession = hRequest.getSession();

    if (DEBUG) {
        DEBUGGER.debug("ServletRequestAttributes: {}", requestAttributes);
        DEBUGGER.debug("HttpServletRequest: {}", hRequest);
        DEBUGGER.debug("HttpSession: {}", hSession);
        DEBUGGER.debug("Session ID: {}", hSession.getId());

        DEBUGGER.debug("Dumping session content:");
        @SuppressWarnings("unchecked")
        Enumeration<String> sessionEnumeration = hSession.getAttributeNames();

        while (sessionEnumeration.hasMoreElements()) {
            String sessionElement = sessionEnumeration.nextElement();
            Object sessionValue = hSession.getAttribute(sessionElement);

            DEBUGGER.debug("Attribute: " + sessionElement + "; Value: " + sessionValue);
        }

        DEBUGGER.debug("Dumping request content:");
        @SuppressWarnings("unchecked")
        Enumeration<String> requestEnumeration = hRequest.getAttributeNames();

        while (requestEnumeration.hasMoreElements()) {
            String requestElement = requestEnumeration.nextElement();
            Object requestValue = hRequest.getAttribute(requestElement);

            DEBUGGER.debug("Attribute: " + requestElement + "; Value: " + requestValue);
        }

        DEBUGGER.debug("Dumping request parameters:");
        @SuppressWarnings("unchecked")
        Enumeration<String> paramsEnumeration = hRequest.getParameterNames();

        while (paramsEnumeration.hasMoreElements()) {
            String requestElement = paramsEnumeration.nextElement();
            Object requestValue = hRequest.getParameter(requestElement);

            DEBUGGER.debug("Parameter: " + requestElement + "; Value: " + requestValue);
        }
    }

    // validate
    this.appConfig.getEmailValidator().validate(message, bindResult);

    if (bindResult.hasErrors()) {
        // errors occurred during validation
        ERROR_RECORDER.error("Form failed field validation");

        mView.addObject(Constants.ERROR_MESSAGE, this.appConfig.getMessageValidationFailed());
        mView.addObject("command", new EmailMessage());
        mView.setViewName(this.appConfig.getContactPage());

        if (DEBUG) {
            DEBUGGER.debug("ModelAndView: {}", mView);
        }

        return mView;
    }

    this.appConfig.getMessageValidator().validate(message, bindResult);

    if (bindResult.hasErrors()) {
        // errors occurred during validation
        ERROR_RECORDER.error("Form failed field validation");

        mView = new ModelAndView();
        mView.addObject(Constants.ERROR_MESSAGE, this.appConfig.getMessageValidationFailed());
        mView.addObject("command", new EmailMessage());
        mView.setViewName(this.appConfig.getContactPage());

        if (DEBUG) {
            DEBUGGER.debug("ModelAndView: {}", mView);
        }

        return mView;
    }

    try {
        EmailUtils.sendEmailMessage(message, true);

        EmailMessage autoResponse = new EmailMessage();
        autoResponse.setIsAlert(false);
        autoResponse.setMessageSubject(this.contactResponseEmail.getSubject());
        autoResponse.setMessageTo(new ArrayList<>(Arrays
                .asList(String.format(this.contactResponseEmail.getTo()[0], message.getEmailAddr().get(0)))));
        autoResponse.setEmailAddr(
                new ArrayList<>(Arrays.asList(String.format(this.contactResponseEmail.getFrom()))));
        autoResponse.setMessageBody(String.format(this.contactResponseEmail.getText(), message.getEmailAddr(),
                message.getMessageBody()));

        if (DEBUG) {
            DEBUGGER.debug("EmailMessage: {}", autoResponse);
        }

        EmailUtils.sendEmailMessage(autoResponse, true);

        mView = new ModelAndView(new RedirectView());
        mView.setViewName(this.appConfig.getRequestCompletePage());
    } catch (MessagingException msx) {
        ERROR_RECORDER.error(msx.getMessage(), msx);

        mView.setViewName(this.appConfig.getErrorResponsePage());
    }

    if (DEBUG) {
        DEBUGGER.debug("ModelAndView: {}", mView);
    }

    return mView;
}

From source file:com.idr.servlets.UploadServlet.java

/**
 * Uploading the file to the sever and complete the conversion
 * @param request/*from   w  ww.  j  ava  2  s  .c om*/
 * @param response 
 */
private void doFileUpload(HttpServletRequest request, HttpServletResponse response) {

    //        System.out.println("Doing upload"+System.currentTimeMillis());
    HttpSession session = request.getSession();

    session.setAttribute("href", null);
    session.setAttribute("FILE_UPLOAD_STATS", null);
    session.setAttribute("pageCount", 0);
    session.setAttribute("pageReached", 0);
    session.setAttribute("isUploading", "true");
    session.setAttribute("isConverting", "false");
    session.setAttribute("convertType", "html");
    session.setAttribute("isZipping", "false");
    con = new Converter();
    byte[] fileBytes = null;

    String sessionId = session.getId();
    String userFileName = "";
    HashMap<String, String> paramMap = new HashMap<String, String>();
    int conType = Converter.getConversionType(request.getRequestURI());

    int startPageNumber = 1;
    int pageCount = 0;

    try {

        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            UploadListener listener = new UploadListener();//listens file uploads                  
            upload.setProgressListener(listener);
            session.setAttribute("FILE_UPLOAD_STATS", listener);
            List<FileItem> fields = upload.parseRequest(request);
            Iterator<FileItem> it = fields.iterator();
            FileItem fileItem = null;
            if (!it.hasNext()) {
                return;//("No fields found");
            }
            while (it.hasNext()) {
                FileItem field = it.next();
                if (field.isFormField()) {
                    String fieldName = field.getFieldName();
                    Flag.updateParameterMap(fieldName, field.getString(), paramMap);
                    field.delete();
                } else {
                    fileItem = field;
                }
            }
            //Flags whether the file is a .zip or a .pdf
            if (fileItem.getName().contains(".pdf")) {
                isPDF = true;
                isZip = false;
            } else if (fileItem.getName().contains(".zip")) {
                isZip = true;
                isPDF = false;
            }
            //removes the last 4 chars and replaces odd chars with underscore
            userFileName = fileItem.getName().substring(0, fileItem.getName().length() - 4)
                    .replaceAll("[^a-zA-Z0-9]", "_");
            fileBytes = fileItem.get();
            fileItem.delete();
        }

        // Delete existing editor files if any exist. 
        if (isEditorLinkOutput) {
            File editorFolder = new File(Converter.EDITORPATH + "/" + sessionId + "/");
            if (editorFolder.exists()) {
                FileUtils.deleteDirectory(editorFolder);
            }
        }
        con.initializeConversion(sessionId, userFileName, fileBytes, isZip);
        PdfDecoderServer decoder = new PdfDecoderServer(false);
        decoder.openPdfFile(con.getUserPdfFilePath());
        pageCount = decoder.getPageCount();
        //Check whether or not the PDF contains forms
        if (decoder.isForm()) {
            session.setAttribute("isForm", "true"); //set an attrib for extraction.jps to use
            response.getWriter().println("<div id='isForm'></div>");
        } else if (!decoder.isForm()) {
            session.setAttribute("isForm", "false"); //set an attrib for extraction.jps to use
        }
        //Check whther or not the PDF is XFA
        if (decoder.getFormRenderer().isXFA()) {
            session.setAttribute("isXFA", "true");
            //                response.getWriter().println("<div id='isXFA'></div>");
        } else if (!decoder.getFormRenderer().isXFA()) {
            session.setAttribute("isXFA", "false");
        }
        decoder.closePdfFile(); //closes file

        if (paramMap.containsKey("org.jpedal.pdf2html.realPageRange")) {
            String tokensCSV = (String) paramMap.get("org.jpedal.pdf2html.realPageRange");
            PageRanges range = new PageRanges(tokensCSV);
            ArrayList<Integer> rangeList = new ArrayList<Integer>();
            for (int z = 0; z < pageCount; z++) {
                if (range.contains(z)) {
                    rangeList.add(z);
                }
            }
            int userPageCount = rangeList.size();
            if (rangeList.size() > 0) {
                session.setAttribute("pageCount", userPageCount);
            } else {
                throw new Exception("invalid Page Range");
            }
        } else {
            session.setAttribute("pageCount", pageCount);
        }

        session.setAttribute("isUploading", "false");
        session.setAttribute("isConverting", "true");

        String scales = paramMap.get("org.jpedal.pdf2html.scaling");
        String[] scaleArr = null;
        String userOutput = con.getUserFileDirName();
        if (scales != null && scales.contains(",")) {
            scaleArr = scales.split(",");
        }

        String reference = UploadServlet.getConvertedFileHref(sessionId, userFileName, conType, pageCount,
                startPageNumber, paramMap, scaleArr, isZip) + "<br/><br/>";

        if (isZipLinkOutput) {
            reference = reference + con.getZipFileHref(userOutput, scaleArr);
        }

        if (isEditorLinkOutput && conType != Converter.PDF2ANDROID && conType != Converter.PDF2IMAGE) {
            reference = reference + "<br/><br/>" + con.getEditorHref(userOutput, scaleArr); // editor link
        }
        String typeString = Converter.getConversionTypeAsString(conType);

        converterThread(userFileName, scaleArr, fileBytes, typeString, paramMap, session, pageCount, reference);

    } catch (Exception ex) {
        session.setAttribute("href", "<end></end><div class='errorMsg'>Error: " + ex.getMessage() + "</div>");
        Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
        cancelUpload(request, response);
    }
}

From source file:com.uniquesoft.uidl.servlet.UploadServlet.java

/**
 * This method parses the submit action, puts in session a listener where the
 * progress status is updated, and eventually stores the received data in
 * the user session./*  w  ww.j  a v a 2  s .  c  om*/
 * 
 * returns null in the case of success or a string with the error
 * 
 */
@SuppressWarnings("unchecked")
protected String parsePostRequest(HttpServletRequest request, HttpServletResponse response) {

    try {
        String delay = request.getParameter(PARAM_DELAY);
        uploadDelay = Integer.parseInt(delay);
    } catch (Exception e) {
    }

    HttpSession session = request.getSession();

    logger.debug("UPLOAD-SERVLET (" + session.getId() + ") new upload request received.");

    AbstractUploadListener listener = getCurrentListener(request);
    if (listener != null) {
        if (listener.isFrozen() || listener.isCanceled() || listener.getPercent() >= 100) {
            removeCurrentListener(request);
        } else {
            String error = getMessage("busy");
            logger.error("UPLOAD-SERVLET (" + session.getId() + ") " + error);
            return error;
        }
    }
    // Create a file upload progress listener, and put it in the user session,
    // so the browser can use ajax to query status of the upload process
    listener = createNewListener(request);

    List<FileItem> uploadedItems;
    try {

        // Call to a method which the user can override
        checkRequest(request);

        // Create the factory used for uploading files,
        FileItemFactory factory = getFileItemFactory(getContentLength(request));
        ServletFileUpload uploader = new ServletFileUpload(factory);
        uploader.setSizeMax(maxSize);
        uploader.setProgressListener(listener);

        // Receive the files
        logger.debug("UPLOAD-SERVLET (" + session.getId() + ") parsing HTTP POST request ");
        uploadedItems = uploader.parseRequest(request);
        session.removeAttribute(getSessionLastFilesKey(request));
        logger.debug("UPLOAD-SERVLET (" + session.getId() + ") parsed request, " + uploadedItems.size()
                + " items received.");

        // Received files are put in session
        List<FileItem> sessionFiles = getMySessionFileItems(request);
        if (sessionFiles == null) {
            sessionFiles = new ArrayList<FileItem>();
        }

        String error = "";

        if (uploadedItems.size() > 0) {

            // We append to the field name the sequence of the uploaded file
            int cnt = 0;
            for (FileItem i : uploadedItems) {
                if (!i.isFormField()) {
                    i.setFieldName(i.getFieldName().replace(UConsts.MULTI_SUFFIX, "") + "-" + cnt++);
                }
            }

            sessionFiles.addAll(uploadedItems);
            String msg = "";
            for (FileItem i : sessionFiles) {
                msg += i.getFieldName() + " => " + i.getName() + "(" + i.getSize() + " bytes),";
            }
            logger.debug("UPLOAD-SERVLET (" + session.getId() + ") puting items in session: " + msg);
            session.setAttribute(getSessionFilesKey(request), sessionFiles);
            session.setAttribute(getSessionLastFilesKey(request), uploadedItems);
        } else {
            logger.error("UPLOAD-SERVLET (" + session.getId() + ") error NO DATA received ");
            error += getMessage("no_data");
        }

        return error.length() > 0 ? error : null;

        // So much silly questions in the list about this issue.  
    } catch (LinkageError e) {
        logger.error("UPLOAD-SERVLET (" + request.getSession().getId() + ") Exception: " + e.getMessage() + "\n"
                + stackTraceToString(e));
        RuntimeException ex = new UploadActionException(getMessage("restricted", e.getMessage()), e);
        listener.setException(ex);
        throw ex;
    } catch (SizeLimitExceededException e) {
        RuntimeException ex = new UploadSizeLimitException(e.getPermittedSize(), e.getActualSize());
        listener.setException(ex);
        throw ex;
    } catch (UploadSizeLimitException e) {
        listener.setException(e);
        throw e;
    } catch (UploadCanceledException e) {
        listener.setException(e);
        throw e;
    } catch (UploadTimeoutException e) {
        listener.setException(e);
        throw e;
    } catch (Throwable e) {
        logger.error("UPLOAD-SERVLET (" + request.getSession().getId() + ") Unexpected Exception -> "
                + e.getMessage() + "\n" + stackTraceToString(e));
        e.printStackTrace();
        RuntimeException ex = new UploadException(e);
        listener.setException(ex);
        throw ex;
    }
}