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:nl.strohalm.cyclos.utils.LoginHelper.java

/**
 * Perform the login itself//from   w  w w. j  av a2 s.  c  o m
 */
public User login(final Class<? extends User> requiredUserClass, final String principalTypeString,
        final String memberUsername, final String principal, final String password, final String channel,
        final HttpServletRequest request, final HttpServletResponse response) throws LoginException {
    final String remoteAddress = request.getRemoteAddr();

    final PrincipalType principalType = channelService.resolvePrincipalType(channel, principalTypeString);

    // Validate the user
    String usernameToVerify = principal;
    if (principalType.getPrincipal() != Principal.USER) {
        try {
            Member member;
            member = elementService.loadByPrincipal(principalType, principal, Element.Relationships.USER,
                    Element.Relationships.GROUP);
            usernameToVerify = member.getUsername();
        } catch (final EntityNotFoundException e) {
            usernameToVerify = "";
        }
    }
    final User user = accessService.verifyLogin(memberUsername, usernameToVerify, remoteAddress);
    if (!requiredUserClass.isInstance(user)) {
        throw new AccessDeniedException();
    }

    // Find the user nature
    final Group group = user.getElement().getGroup();
    final boolean isAdmin = group instanceof AdminGroup;
    final boolean isMember = group instanceof MemberGroup;
    final boolean isBroker = group instanceof BrokerGroup;
    final boolean isOperator = group instanceof OperatorGroup;
    final boolean isPosWeb = RequestHelper.isPosWeb(request);

    final AccessSettings accessSettings = settingsService.getAccessSettings();

    // Check if the administrator is allowed to login
    if (isAdmin && !accessSettings.getAdministrationWhitelistValidator().isAllowed(request.getRemoteHost(),
            request.getRemoteAddr())) {
        throw new AccessDeniedException();
    }

    // According to the cyclos.properties flag, create a new session or use the current one
    HttpSession session;
    if (newSessionAfterLogin) {
        session = createNewSessionForlogin(request);
    } else {
        session = request.getSession();
    }

    // Login the user
    accessService.login(user, password, channel, isPosWeb, remoteAddress, session.getId());

    // Apply the session timeout
    final TimePeriod timeout = isPosWeb ? accessSettings.getPoswebTimeout()
            : isMember ? accessSettings.getMemberTimeout() : accessSettings.getAdminTimeout();
    int timeoutSeconds = (int) timeout.getValueIn(TimePeriod.Field.SECONDS);
    if (timeoutSeconds <= 0) {
        timeoutSeconds = -1;
    }
    session.setMaxInactiveInterval(timeoutSeconds);

    // If is a member, determine if the member has accounts, documents, loan groups and memberPos
    boolean hasAccounts = false;
    boolean singleAccount = false;
    boolean hasDocuments = false;
    boolean hasLoanGroups = false;
    boolean hasGeneralReferences = false;
    boolean hasTransactionFeedbacks = false;
    boolean hasPin = false;
    boolean hasExternalChannels = false;
    boolean hasCards = false;
    boolean hasPos = false;
    boolean hasCommissionContracts = false;
    if (isMember || isOperator) {
        Member member;
        if (isMember) {
            member = ((MemberUser) user).getMember();

            // Get the accessible channels
            final MemberGroup memberGroup = groupService.load(member.getMemberGroup().getId(),
                    MemberGroup.Relationships.CHANNELS);
            hasPin = groupService.usesPin(memberGroup);
            for (final Channel current : memberGroup.getChannels()) {
                if (!Channel.WEB.equals(current.getInternalName())) {
                    hasExternalChannels = true;
                    break;
                }
            }

            if (!member.getPosDevices().isEmpty()) {
                hasPos = true;
                if (member.getPosDevices().size() == 1) {
                    final Collection<MemberPos> memberPos = member.getPosDevices();
                    for (final MemberPos mpos : memberPos) {
                        session.setAttribute("uniqueMemberPosId ", mpos.getPos().getId());
                    }
                }
            }

        } else {
            member = ((OperatorUser) user).getOperator().getMember();
        }
        // Fetch broker
        member = elementService.load(member.getId(), Member.Relationships.BROKER);
        final MemberGroup memberGroup = member.getMemberGroup();

        // Check if the member has accounts
        final List<? extends Account> accounts = accountService.getAccounts(member);
        hasAccounts = !accounts.isEmpty();
        singleAccount = accounts.size() == 1;
        if (isMember) {
            // Check if the member has documents
            if (permissionService.hasPermission(MemberPermission.DOCUMENTS_VIEW)) {
                hasDocuments = true;
            } else {
                final DocumentQuery documentQuery = new DocumentQuery();
                documentQuery.setNatures(Collections.singleton(Document.Nature.MEMBER));
                documentQuery.setMember(member);
                documentQuery.setPageForCount();
                hasDocuments = PageHelper.hasResults(documentService.search(documentQuery));
            }
            // Check if the member has loan groups
            final LoanGroupQuery lgq = new LoanGroupQuery();
            lgq.setPageForCount();
            lgq.setMember(member);
            hasLoanGroups = PageHelper.hasResults(loanGroupService.search(lgq));

            // Check if the member has commission contracts
            hasCommissionContracts = commissionService.hasBrokerCommissionContracts();
        }
        // Check if the user has references
        final Collection<Nature> referenceNatures = referenceService.getNaturesByGroup(memberGroup);
        hasGeneralReferences = referenceNatures.contains(Nature.GENERAL);
        hasTransactionFeedbacks = referenceNatures.contains(Nature.TRANSACTION);

        // Check if the user can have guarantees
        try {
            final Collection<GuaranteeType.Model> guaranteeModels = guaranteeService
                    .getRelatedGuaranteeModels();
            session.setAttribute("loggedMemberHasGuarantees", guaranteeModels.size() > 0);
        } catch (final Exception e) {
            // Ignore
        }

        // Check if the user has cards
        hasCards = member.getCards().isEmpty() ? false : true;
    }

    if (isAdmin || isBroker) {
        // Retrieve the member record types the logged user can see on the menu
        final MemberRecordTypeQuery query = new MemberRecordTypeQuery();
        if (isAdmin) {
            query.setViewableByAdminGroup((AdminGroup) group);
        } else {
            query.setViewableByBrokerGroup((BrokerGroup) group);
        }
        query.setShowMenuItem(true);
        final List<MemberRecordType> types = memberRecordTypeService.search(query);
        session.setAttribute("memberRecordTypesInMenu", types);
    }

    // When a receipt printer cookie is set, and the printer no longer exists, or belongs to someone else, clear the cookie
    final String receiptPrinterId = RequestHelper.getCookieValue(request, "receiptPrinterId");
    if (StringUtils.isNotEmpty(receiptPrinterId)) {
        final Long id = IdConverter.instance().valueOf(receiptPrinterId);
        if (!receiptPrinterSettingsService.belongsToTheLoggedUser(id)) {
            final Cookie cookie = new Cookie("receiptPrinterId", "");
            cookie.setPath(request.getContextPath());
            response.addCookie(cookie);
        }
    }

    final String actionPrefix = "/" + (isAdmin ? "admin" : isMember ? "member" : "operator");

    // Set the request attributes
    request.setAttribute("loggedUser", user);
    request.setAttribute("loggedElement", user.getElement());

    // Set the session attributes
    session.setAttribute("loggedUserId", user.getId());
    session.setAttribute("isAdmin", isAdmin);
    session.setAttribute("isMember", isMember);
    session.setAttribute("isBroker", isBroker);
    session.setAttribute("isOperator", isOperator);
    session.setAttribute("isBuyer", guaranteeService.isBuyer());
    session.setAttribute("isSeller", guaranteeService.isSeller());
    session.setAttribute("isIssuer", guaranteeService.isIssuer());
    session.setAttribute("loggedMemberHasAccounts", hasAccounts);
    session.setAttribute("loggedMemberHasSingleAccount", singleAccount);
    session.setAttribute("loggedMemberHasDocuments", hasDocuments);
    session.setAttribute("loggedMemberHasLoanGroups", hasLoanGroups);
    session.setAttribute("loggedMemberHasGeneralReferences", hasGeneralReferences);
    session.setAttribute("loggedMemberHasTransactionFeedbacks", hasTransactionFeedbacks);
    session.setAttribute("hasPin", hasPin);
    session.setAttribute("hasCards", hasCards);
    session.setAttribute("hasPos", hasPos);
    session.setAttribute("hasCommissionContracts", hasCommissionContracts);
    session.setAttribute("hasExternalChannels", hasExternalChannels);
    session.setAttribute("actionPrefix", actionPrefix);
    session.setAttribute("pathPrefix", "/do" + actionPrefix);
    session.setAttribute("navigation", Navigation.get(session));

    // Return the logged user
    return user;
}

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

/**
 * Reinit the map with the default files stored in database and blobstore
 * @param request the HTTP request/*from  w ww  . j a  v  a 2  s  .  c  om*/
 * @param map the map <idEntry, RecordFields>
 * @param plugin the plugin
 */
public void reinitMap(HttpServletRequest request, Map<String, List<RecordField>> map, Plugin plugin) {
    HttpSession session = request.getSession();
    removeSessionFiles(session.getId());

    if ((map != null) && !map.isEmpty()) {
        for (java.util.Map.Entry<String, List<RecordField>> param : map.entrySet()) {
            for (RecordField recordField : param.getValue()) {
                if (recordField != null) {
                    IEntry entry = recordField.getEntry();

                    if ((recordField.getFile() != null) && (recordField.getFile().getPhysicalFile() != null)
                            && !recordField.isLittleThumbnail() && !recordField.isBigThumbnail()) {
                        // The little thumbnail and the big thumbnail should not be stored in the session
                        File file = recordField.getFile();
                        PhysicalFile physicalFile = PhysicalFileHome
                                .findByPrimaryKey(file.getPhysicalFile().getIdPhysicalFile(), plugin);
                        FileItem fileItem = new DirectoryFileItem(physicalFile.getValue(), file.getTitle());
                        // Add the file item to the map
                        addFileItemToUploadedFile(fileItem, Integer.toString(entry.getIdEntry()), session);
                    } else if (recordField.getEntry() instanceof EntryTypeDownloadUrl
                            && isBlobStoreClientServiceAvailable()) {
                        // Different behaviour if the entry is an EntryTypeDownloadUrl
                        FileItem fileItem;

                        try {
                            fileItem = doDownloadFile(recordField.getValue());

                            FileItem directoryFileItem = new DirectoryFileItem(fileItem.get(),
                                    fileItem.getName());
                            // Add the file item to the map
                            addFileItemToUploadedFile(directoryFileItem, Integer.toString(entry.getIdEntry()),
                                    session);
                        } catch (BlobStoreClientException e) {
                            AppLogService.error(DirectoryAsynchronousUploadHandler.class.getName()
                                    + " - Error when reinit map. Cause : " + e.getMessage());
                        }
                    }
                }
            }
        }
    }
}

From source file:gov.nih.nci.ispy.web.taglib.PCAPlotTag.java

public int doStartTag() {
    chart = null;//from   w  ww.j  ava  2s . co  m
    pcaResults = null;
    pcaData.clear();

    ServletRequest request = pageContext.getRequest();
    HttpSession session = pageContext.getSession();
    Object o = request.getAttribute(beanName);
    JspWriter out = pageContext.getOut();
    ServletResponse response = pageContext.getResponse();

    try {
        //retrieve the Finding from cache and build the list of PCAData points
        PrincipalComponentAnalysisFinding principalComponentAnalysisFinding = (PrincipalComponentAnalysisFinding) businessTierCache
                .getSessionFinding(session.getId(), taskId);

        Collection<ClinicalFactorType> clinicalFactors = new ArrayList<ClinicalFactorType>();
        List<String> sampleIds = new ArrayList<String>();
        Map<String, PCAresultEntry> pcaResultMap = new HashMap<String, PCAresultEntry>();

        pcaResults = principalComponentAnalysisFinding.getResultEntries();
        for (PCAresultEntry pcaEntry : pcaResults) {
            sampleIds.add(pcaEntry.getSampleId());
            pcaResultMap.put(pcaEntry.getSampleId(), pcaEntry);
        }

        //Get the clinical data for the sampleIds
        ClinicalDataService cqs = ClinicalDataServiceFactory.getInstance();
        IdMapperFileBasedService idMapper = IdMapperFileBasedService.getInstance();
        //Map<String, ClinicalData> clinicalDataMap = cqs.getClinicalDataMapForLabtrackIds(sampleIds);              

        PCAresultEntry entry;
        //ClinicalData clinData;
        //PatientData patientData;
        SampleInfo si;
        TimepointType timepoint;
        for (String id : sampleIds) {

            entry = pcaResultMap.get(id);
            ISPYPCADataPoint pcaPoint = new ISPYPCADataPoint(id, entry.getPc1(), entry.getPc2(),
                    entry.getPc3());

            si = idMapper.getSampleInfoForLabtrackId(id);

            //clinData = cqs.getClinicalDataForPatientDID(si.getRegistrantId(), si.getTimepoint());
            //patientData = cqs.getPatientDataForPatientDID(si.getISPYId());
            Set<String> ispyIds = new HashSet<String>();
            ispyIds.add(si.getISPYId());
            ISPYclinicalDataQueryDTO dto = new ISPYclinicalDataQueryDTO();
            dto.setRestrainingSamples(ispyIds);
            Set<PatientData> pdSet = cqs.getClinicalData(dto);
            for (PatientData patientData : pdSet) {
                pcaPoint.setISPY_ID(si.getISPYId());
                timepoint = si.getTimepoint();

                pcaPoint.setTimepoint(timepoint);

                if (patientData != null) {
                    pcaPoint.setClinicalStage(patientData.getClinicalStage());

                    int clinRespVal;
                    Double mriPctChange = null;
                    if (timepoint == TimepointType.T1) {
                        pcaPoint.setClinicalResponse(ClinicalResponseType.NA);
                        pcaPoint.setTumorMRIpctChange(null);
                    } else if (timepoint == TimepointType.T2) {
                        clinRespVal = PatientData.parseValue(patientData.getClinRespT1_T2());
                        //set the clinical respoinse to the T1_T2
                        pcaPoint.setClinicalResponse(ClinicalResponseType.getTypeForValue(clinRespVal));
                        pcaPoint.setTumorMRIpctChange(patientData.getMriPctChangeT1_T2());
                    } else if (timepoint == TimepointType.T3) {
                        //set the clinical response to T1_T3
                        clinRespVal = PatientData.parseValue(patientData.getClinRespT1_T3());
                        pcaPoint.setClinicalResponse(ClinicalResponseType.getTypeForValue(clinRespVal));
                        pcaPoint.setTumorMRIpctChange(patientData.getMriPctChangeT1_T3());
                    } else if (timepoint == TimepointType.T4) {
                        //set the clinical response to T1_T4
                        clinRespVal = PatientData.parseValue(patientData.getClinRespT1_T4());
                        pcaPoint.setClinicalResponse(ClinicalResponseType.getTypeForValue(clinRespVal));
                        pcaPoint.setTumorMRIpctChange(patientData.getMriPctChangeT1_T4());
                    } else {
                        pcaPoint.setClinicalResponse(ClinicalResponseType.UNKNOWN);
                        pcaPoint.setTumorMRIpctChange(null);
                    }
                }

                pcaData.add(pcaPoint);
            }
        }

        //check the components to see which graph to get
        if (components.equalsIgnoreCase("PC1vsPC2")) {
            ISPYPrincipalComponentAnalysisPlot plot = new ISPYPrincipalComponentAnalysisPlot(pcaData,
                    PCAcomponent.PC2, PCAcomponent.PC1,
                    ColorByType.valueOf(ColorByType.class, colorBy.toUpperCase()));
            chart = plot.getChart();
        }
        if (components.equalsIgnoreCase("PC1vsPC3")) {
            ISPYPrincipalComponentAnalysisPlot plot = new ISPYPrincipalComponentAnalysisPlot(pcaData,
                    PCAcomponent.PC3, PCAcomponent.PC1,
                    ColorByType.valueOf(ColorByType.class, colorBy.toUpperCase()));
            chart = plot.getChart();
        }
        if (components.equalsIgnoreCase("PC2vsPC3")) {
            ISPYPrincipalComponentAnalysisPlot plot = new ISPYPrincipalComponentAnalysisPlot(pcaData,
                    PCAcomponent.PC3, PCAcomponent.PC2,
                    ColorByType.valueOf(ColorByType.class, colorBy.toUpperCase()));
            chart = plot.getChart();
        }

        ISPYImageFileHandler imageHandler = new ISPYImageFileHandler(session.getId(), "png", 650, 600);
        //The final complete path to be used by the webapplication
        String finalPath = imageHandler.getSessionTempFolder();
        String finalURLpath = imageHandler.getFinalURLPath();
        /*
         * Create the actual charts, writing it to the session temp folder
        */
        ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        String mapName = imageHandler.createUniqueMapName();
        //PrintWriter writer = new PrintWriter(new FileWriter(mapName));
        ChartUtilities.writeChartAsPNG(new FileOutputStream(finalPath), chart, 650, 600, info);
        //ImageMapUtil.writeBoundingRectImageMap(writer,"PCAimageMap",info,true);
        //writer.close();

        /*   This is here to put the thread into a loop while it waits for the
         *   image to be available.  It has an unsophisticated timer but at 
         *   least it is something to avoid an endless loop.
         **/
        boolean imageReady = false;
        int timeout = 1000;
        FileInputStream inputStream = null;
        while (!imageReady) {
            timeout--;
            try {
                inputStream = new FileInputStream(finalPath);
                inputStream.available();
                imageReady = true;
                inputStream.close();
            } catch (IOException ioe) {
                imageReady = false;
                if (inputStream != null) {
                    inputStream.close();
                }
            }
            if (timeout <= 1) {

                break;
            }
        }

        out.print(ImageMapUtil.getBoundingRectImageMapTag(mapName, false, info));
        finalURLpath = finalURLpath.replace("\\", "/");
        long randomness = System.currentTimeMillis(); //prevent image caching
        out.print("<img id=\"geneChart\" name=\"geneChart\" src=\"" + finalURLpath + "?" + randomness
                + "\" usemap=\"#" + mapName + "\" border=\"0\" />");

        //(imageHandler.getImageTag(mapFileName));

    } catch (IOException e) {
        logger.error(e);
    } catch (Exception e) {
        logger.error(e);
    } catch (Throwable t) {
        logger.error(t);
    }

    return EVAL_BODY_INCLUDE;
}

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

/**
 * Shared method for webdav/vti to unlock node. Unlocked node is automatically removed from
 * current sessions's locked resources list.
 * // w ww . jav  a2 s . c om
 * @param nodeRef the node to lock
 */
@Override
public void unlock(NodeRef nodeRef) {
    lockService.unlock(nodeRef);

    if (logger.isDebugEnabled()) {
        logger.debug(nodeRef + " was unlocked.");
    }

    HttpSession session = currentSession.get();

    if (session == null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Couldn't find current session.");
        }
        return;
    }

    boolean removed = removeObjectFromSessionList(session, LOCKED_RESOURCES,
            new Pair<String, NodeRef>(AuthenticationUtil.getRunAsUser(), nodeRef));

    if (removed && logger.isDebugEnabled()) {
        logger.debug(nodeRef + " was removed from the session " + session.getId());
    }
}

From source file:gov.nih.nci.rembrandt.web.taglib.PCAPlotTag.java

public int doStartTag() {
    chart = null;/*from w  w  w .ja  v  a2s  .c  om*/
    pcaResults = null;
    pcaData.clear();

    ServletRequest request = pageContext.getRequest();
    HttpSession session = pageContext.getSession();
    Object o = request.getAttribute(beanName);
    JspWriter out = pageContext.getOut();
    ServletResponse response = pageContext.getResponse();

    try {
        //retrieve the Finding from cache and build the list of PCAData points
        PrincipalComponentAnalysisFinding principalComponentAnalysisFinding = (PrincipalComponentAnalysisFinding) businessTierCache
                .getSessionFinding(session.getId(), taskId);

        Collection<ClinicalFactorType> clinicalFactors = new ArrayList<ClinicalFactorType>();
        List<String> sampleIds = new ArrayList<String>();
        Map<String, PCAresultEntry> pcaResultMap = new HashMap<String, PCAresultEntry>();
        if (principalComponentAnalysisFinding != null) {
            pcaResults = principalComponentAnalysisFinding.getResultEntries();
            for (PCAresultEntry pcaEntry : pcaResults) {
                sampleIds.add(pcaEntry.getSampleId());
                pcaResultMap.put(pcaEntry.getSampleId(), pcaEntry);
            }

            Collection<SampleResultset> validatedSampleResultset = ClinicalDataValidator
                    .getValidatedSampleResultsetsFromSampleIDs(sampleIds, clinicalFactors);

            if (validatedSampleResultset != null) {
                String id;
                PCAresultEntry entry;

                for (SampleResultset rs : validatedSampleResultset) {
                    id = rs.getBiospecimen().getSpecimenName();
                    entry = pcaResultMap.get(id);
                    PrincipalComponentAnalysisDataPoint pcaPoint = new PrincipalComponentAnalysisDataPoint(id,
                            entry.getPc1(), entry.getPc2(), entry.getPc3());
                    String diseaseName = rs.getDisease().getValueObject();
                    if (diseaseName != null) {
                        pcaPoint.setDiseaseName(diseaseName);
                    } else {
                        pcaPoint.setDiseaseName(DiseaseType.NON_TUMOR.name());
                    }
                    GenderDE genderDE = rs.getGenderCode();
                    if (genderDE != null && genderDE.getValue() != null) {
                        String gt = genderDE.getValueObject().trim();
                        if (gt != null) {
                            GenderType genderType = GenderType.valueOf(gt);
                            if (genderType != null) {
                                pcaPoint.setGender(genderType);
                            }
                        }
                    }
                    Long survivalLength = rs.getSurvivalLength();
                    if (survivalLength != null) {
                        //survival length is stored in days in the DB so divide by 30 to get the 
                        //approx survival in months
                        double survivalInMonths = survivalLength.doubleValue() / 30.0;
                        pcaPoint.setSurvivalInMonths(survivalInMonths);
                    }
                    pcaData.add(pcaPoint);
                }
            }

            PCAcomponent pone = PCAcomponent.PC1;
            PCAcomponent ptwo = PCAcomponent.PC2;
            //check the components to see which graph to get
            if (components.equalsIgnoreCase("PC1vsPC2")) {
                pone = PCAcomponent.PC2;
                ptwo = PCAcomponent.PC1;
                //chart = (JFreeChart) CaIntegratorChartFactory.getPrincipalComponentAnalysisGraph(pcaData,PCAcomponent.PC2,PCAcomponent.PC1,PCAcolorByType.valueOf(PCAcolorByType.class,colorBy));
            }
            if (components.equalsIgnoreCase("PC1vsPC3")) {
                pone = PCAcomponent.PC3;
                ptwo = PCAcomponent.PC1;
                //chart = (JFreeChart) CaIntegratorChartFactory.getPrincipalComponentAnalysisGraph(pcaData,PCAcomponent.PC3,PCAcomponent.PC1,PCAcolorByType.valueOf(PCAcolorByType.class,colorBy));
            }
            if (components.equalsIgnoreCase("PC2vsPC3")) {
                pone = PCAcomponent.PC2;
                ptwo = PCAcomponent.PC3;
                //chart = (JFreeChart) CaIntegratorChartFactory.getPrincipalComponentAnalysisGraph(pcaData,PCAcomponent.PC3,PCAcomponent.PC2,PCAcolorByType.valueOf(PCAcolorByType.class,colorBy));
            }

            PrincipalComponentAnalysisPlot plot = new RBTPrincipalComponentAnalysisPlot(pcaData, pone, ptwo,
                    PCAcolorByType.valueOf(PCAcolorByType.class, colorBy));
            if (plot != null) {
                chart = (JFreeChart) plot.getChart();
            }

            RembrandtImageFileHandler imageHandler = new RembrandtImageFileHandler(session.getId(), "png", 650,
                    600);
            //The final complete path to be used by the webapplication
            String finalPath = imageHandler.getSessionTempFolder();
            String finalURLpath = imageHandler.getFinalURLPath();
            /*
             * Create the actual charts, writing it to the session temp folder
            */
            ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
            String mapName = imageHandler.createUniqueMapName();
            //PrintWriter writer = new PrintWriter(new FileWriter(mapName));
            ChartUtilities.writeChartAsPNG(new FileOutputStream(finalPath), chart, 650, 600, info);
            //ImageMapUtil.writeBoundingRectImageMap(writer,"PCAimageMap",info,true);
            //writer.close();

            /*   This is here to put the thread into a loop while it waits for the
             *   image to be available.  It has an unsophisticated timer but at 
             *   least it is something to avoid an endless loop.
             **/
            boolean imageReady = false;
            int timeout = 1000;
            FileInputStream inputStream = null;
            while (!imageReady) {
                timeout--;
                try {
                    inputStream = new FileInputStream(finalPath);
                    inputStream.available();
                    imageReady = true;
                    inputStream.close();
                } catch (IOException ioe) {
                    imageReady = false;
                    if (inputStream != null) {
                        inputStream.close();
                    }
                }
                if (timeout <= 1) {

                    break;
                }
            }

            out.print(ImageMapUtil.getBoundingRectImageMapTag(mapName, false, info));
            finalURLpath = finalURLpath.replace("\\", "/");
            long randomness = System.currentTimeMillis(); //prevent image caching
            out.print("<img id=\"geneChart\" name=\"geneChart\" alt=\"geneChart\" src=\"" + finalURLpath + "?"
                    + randomness + "\" usemap=\"#" + mapName + "\" border=\"0\" />");

            //(imageHandler.getImageTag(mapFileName));
        }
    } catch (IOException e) {
        logger.error(e);
    } catch (Exception e) {
        logger.error(e);
    } catch (Throwable t) {
        logger.error(t);
    }

    return EVAL_BODY_INCLUDE;
}

From source file:elw.web.ErrController.java

@RequestMapping(value = "*")
public ModelAndView do_handle(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
    final String url = (String) req.getAttribute("javax.servlet.error.request_uri");
    final Integer statusCode = (Integer) req.getAttribute("javax.servlet.error.status_code");

    if (statusCode != null && 404 == statusCode && ignoredUris.contains(url)) {
        resp.sendError(410, "ignored");
        return null;
    }// w w w. j  a  v  a 2s.  c o m

    try {
        final String message = (String) req.getAttribute("javax.servlet.error.message");
        final Throwable throwable = (Throwable) req.getAttribute("javax.servlet.error.exception");
        final String eventId = Long.toString(System.currentTimeMillis(), 36);

        final StringWriter logDest = new StringWriter();
        final PrintWriter logOut = new PrintWriter(logDest);
        final HttpSession session = req.getSession(false);

        logOut.println(
                "web error: eventId=" + eventId + " status=" + statusCode + " message='" + message + "'");
        logOut.println("url: " + url);
        logOut.print("attributes: ");
        final Enumeration reqAttrNames = req.getAttributeNames();
        while (reqAttrNames.hasMoreElements()) {
            final String aName = (String) reqAttrNames.nextElement();
            if (!aName.startsWith("javax.servlet") && !aName.startsWith("org.springframework")) {
                logOut.print(aName + "=" + String.valueOf(req.getAttribute(aName)) + " ");
            }
        }
        logOut.println();

        if (session != null) {
            logOut.println("session id: " + session.getId());
            logOut.print("session: ");
            final Enumeration sessAttrNames = session.getAttributeNames();
            while (sessAttrNames.hasMoreElements()) {
                final String aName = (String) sessAttrNames.nextElement();
                if (!aName.startsWith("javax.servlet") && !aName.startsWith("org.springframework")) {
                    logOut.print(aName + "=" + String.valueOf(session.getAttribute(aName)) + " ");
                }
            }
            logOut.println();
        }

        log.error(logDest.toString(), throwable);

        final PrintWriter out = resp.getWriter();

        out.print("<html><title>HTTP status " + statusCode + " : " + message + "</title>"
                + "<body><h3>HTTP status " + statusCode + " : " + message + "</h3>"
                + "Sorry for inconvenience and thanks for finding just another bug out there.<br/>"
                + "For the time being, you may log out, log in and then try the operation once again.<br/><br/>"
                + "Event reference id: <b>" + eventId + "</b>." + "</body></html>");
    } catch (Throwable t) {
        log.error("failed on reporting error", t);
    }

    return null;
}

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

public void lock(NodeRef nodeRef, LockInfo lockInfo) {
    boolean performSessionBehavior = false;
    long timeout;

    timeout = lockInfo.getRemainingTimeoutSeconds();

    // ALF-11777 fix, do not lock node for more than 24 hours (webdav and vti)
    if (timeout >= WebDAV.TIMEOUT_24_HOURS || timeout == WebDAV.TIMEOUT_INFINITY) {
        timeout = WebDAV.TIMEOUT_24_HOURS;
        lockInfo.setTimeoutSeconds((int) timeout);
        performSessionBehavior = true;/*from   www .j  a v a 2s.  c  o  m*/
    }

    // TODO: lock children according to depth? lock type?
    final String additionalInfo = lockInfo.toJSON();
    lockService.lock(nodeRef, LockType.WRITE_LOCK, (int) timeout, Lifetime.EPHEMERAL, additionalInfo);

    if (logger.isDebugEnabled()) {
        logger.debug(nodeRef + " was locked for " + timeout + " seconds.");
    }

    if (performSessionBehavior) {
        HttpSession session = currentSession.get();

        if (session == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Couldn't find current session.");
            }
            return;
        }

        storeObjectInSessionList(session, LOCKED_RESOURCES,
                new Pair<String, NodeRef>(AuthenticationUtil.getRunAsUser(), nodeRef));

        if (logger.isDebugEnabled()) {
            logger.debug(nodeRef + " was added to the session " + session.getId()
                    + " for post expiration processing.");
        }
    }
}

From source file:it.scoppelletti.programmerpower.web.security.CasClient.java

/**
 * Rimuove una sessione autenticata.//from  w w w.  j  a v a2 s. co  m
 * 
 * @param serviceTicket Ticket di servizio.
 */
public void removeAuthenticatedSession(String serviceTicket) {
    HttpSession session;

    if (Strings.isNullOrEmpty(serviceTicket)) {
        throw new ArgumentNullException("serviceTicket");
    }
    if (mySessionStorage == null) {
        throw new PropertyNotSetException(toString(), "sessionMappingStorage");
    }

    myLogger.debug("Removing service ticket {}.", serviceTicket);
    session = mySessionStorage.removeSessionByMappingId(serviceTicket);
    if (session == null) {
        return;
    }

    myLogger.debug("Invalidating session {}.", session.getId());
    try {
        session.invalidate();
    } catch (Exception ex) {
        myLogger.error("Failed to invalidate session.", ex);
    }
}

From source file:com.aurel.track.item.AddScreenshotAction.java

public String saveScreenshot() {
    LOGGER.debug("Save screenshot workItemID=" + workItemID);
    List<LabelValueBean> errors = new ArrayList<LabelValueBean>();
    if (file == null || file.length() == 0) {
        String err = getText("common.err.required",
                new String[] { getText("report.export.manager.upload.file") });
        errors.add(new LabelValueBean(err, "file"));
        JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
        return null;
    }//ww  w.  ja  va2s.co m
    if (!file.endsWith(".png")) {
        file = file + ".png";
    }
    ApplicationBean applicationBean = (ApplicationBean) application.get(Constants.APPLICATION_BEAN);
    Double maxAttachmentSizeInMb = AttachBL.getMaxAttachmentSizeInMb(applicationBean);
    int MAXFILESIZE = AttachBL.getMaxFileSize(applicationBean);
    if (maxAttachmentSizeInMb != null && Double.compare(maxAttachmentSizeInMb.doubleValue(), 0.0) != 0) {
        MAXFILESIZE = (int) (maxAttachmentSizeInMb.doubleValue() * 1024 * 1024);
    } else {
        MAXFILESIZE = 4 * 1024 * 1024;
    }
    byte[] bytearray = null;
    try {
        bytearray = new Base64().decode(bytes);
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        LOGGER.error(ExceptionUtils.getStackTrace(e1));
        errors.add(new LabelValueBean(e1.getMessage(), "file"));
        JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
        return null;
    }

    if (bytearray.length > MAXFILESIZE) {
        errors.add(new LabelValueBean(
                getText("attachment.maxLengthExceeded", new String[] { maxAttachmentSizeInMb + "" }), "file"));
        JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
        return null;
    }
    int maxDescriptionSize = ApplicationBean.getInstance().getDescriptionMaxLength();
    if (description.length() > maxDescriptionSize) {
        errors.add(new LabelValueBean(getText("item.err.tooLong",
                new String[] { getText("common.lbl.description"), Integer.toString(maxDescriptionSize) }),
                "description"));
        JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
        return null;

    }
    InputStream is = new ByteArrayInputStream(bytearray);
    ApplicationBean appBean = ApplicationBean.getInstance();
    if (appBean.isBackupInProgress()) {
        errors.add(new LabelValueBean(getText("item.tabs.attachment.err.backupInProgress"), "file"));
        JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
        return null;
    }
    if (workItemID == null/*||workItemID.intValue()==-1*/) {
        HttpServletRequest request = org.apache.struts2.ServletActionContext.getRequest();
        HttpSession httpSession = request.getSession();
        WorkItemContext ctx = (WorkItemContext) session.get("workItemContext");
        if (ctx == null) {
            LOGGER.error("No context on session");
            errors.add(new LabelValueBean("No context on session", "file"));
            JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
            return null;
        }
        List<TAttachmentBean> attachments = ctx.getAttachmentsList();
        if (attachments == null) {
            attachments = new ArrayList<TAttachmentBean>();
        }
        String sessionID = httpSession.getId();
        try {
            AttachBL.saveLocal(workItemID, description, file, is, attachments, sessionID, personID);
        } catch (AttachBLException e) {
            String err = "";
            if (e.getLocalizedKey() != null) {
                err = getText(e.getLocalizedKey(), e.getLocalizedParameteres());
            } else {
                err = e.getMessage();
            }
            errors.add(new LabelValueBean(err, "file"));
            JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
            return null;

        }
        ctx.setAttachmentsList(attachments);
    } else {
        try {
            AttachBL.save(workItemID, description, file, is, personID);
            //add to history
            HistorySaverBL.addAttachment(workItemID, personID, locale, file, description,
                    Long.valueOf(bytearray.length), false);
        } catch (AttachBLException e) {
            LOGGER.error("Can't save attachemnt", e);
            String err = "";
            if (e.getLocalizedKey() != null) {
                err = getText(e.getLocalizedKey(), e.getLocalizedParameteres());
            } else {
                err = e.getMessage();
            }
            errors.add(new LabelValueBean(err, "file"));
            JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
            return null;
        }
    }
    description = null;
    JSONUtility.encodeJSONSuccess(ServletActionContext.getResponse());
    return null;
}

From source file:com.baiwang.banktax.controller.IdentifyController.java

/**
 * //from w  w  w .  j  a v a 2  s  . c  om
  * @author gkm
  * @Description: ???--(??)
  * @param @param id
  * @param @return  
  * @return ModelAndView  
  * @throws
  * @date 20151130 ?11:03:35
 */
@RequestMapping("/next")
public ModelAndView identifyNext(Integer id, String verifyUrl, HttpSession session) {
    User user = (User) session.getAttribute(ConfigUtil.getLoginedUserStr());
    logger.info("??? ? ----id:" + user.getId() + "------id:"
            + id);

    AreaBean area = service.getVerifyType(user, id);
    if (null != area) {
        logger.info("??? ? ----id:" + user.getId() + "------?:"
                + area.getVerifyType());
        if ("0".equals(area.getVerifyType())) {
            return new ModelAndView("identify/identify_platform1").addObject("province", area.getAname())
                    .addObject("id", session.getId()).addObject("verifyUrl", verifyUrl);
        } else if ("1".equals(area.getVerifyType())) {
            return new ModelAndView("identify/identify_platform2");
        } else if ("2".equals(area.getVerifyType())) {
            return new ModelAndView("identify/identify_platform3");
        }
    }
    return new ModelAndView("identify/identify_platform1");
}